@adhdev/daemon-standalone 0.8.51 → 0.8.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +938 -301
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-BrT7pA0n.js +71 -0
- package/public/assets/index-OHw5X7HM.css +1 -0
- package/public/index.html +2 -2
- package/vendor/session-host-daemon/index.d.mts +3 -0
- package/vendor/session-host-daemon/index.d.ts +3 -0
- package/vendor/session-host-daemon/index.js +33 -2
- package/vendor/session-host-daemon/index.js.map +1 -1
- package/vendor/session-host-daemon/index.mjs +34 -2
- package/vendor/session-host-daemon/index.mjs.map +1 -1
- package/public/assets/index-BNnOxdJy.css +0 -1
- package/public/assets/index-DW3wxPx9.js +0 -71
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var sc=Object.defineProperty;var rc=(e,s,r)=>s in e?sc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var lt=(e,s,r)=>rc(e,typeof s!="symbol"?s+"":s,r);import{r as a,j as t,M as Sn,a as Cn,b as lo,c as uo,u as ws,R as rt,d as Bs,t as nc,e as ac,D as oc,f as mn,g as pn,h as In,i as ic,k as cc,B as lc,l as dc,m as zt,N as fn,n as uc}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();function mc(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(o),r.length>s&&r.splice(0,r.length-s),o},list(n={}){const o=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-o).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const ss=mc();function ia(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}const mo=a.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),po=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ca(e){var r,n;let s=0;return"activeChat"in e&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function Hr(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},o=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,d=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,m=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),m&&(n.versionUpdateReason=m),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),d&&(n.versionUpdateRequired=!0),n)}function yr(e){return Array.isArray(e)?e.map(yr):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,yr(r)]))}function pc(e,s){try{return JSON.stringify(yr(e))===JSON.stringify(yr(s))}catch{return!1}}function qs(e,s,r){return pc(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function fc(e,s,r){var m,f,p,x,b,S,A;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(u=>({...u,_lastUpdate:n}));const i=new Map;for(const u of s)i.set(u.id,u);for(const u of e){const h=i.get(u.id);if(!h){i.set(u.id,{...u,_lastUpdate:n});continue}const y=ca(u),l=ca(h);if(y>l){const j=(m=u.chats)!=null&&m.length?u.chats:h.chats,P=Hr(h,u,{...h,...u,chats:j,_lastUpdate:n});i.set(u.id,qs(h,P,n))}else if(y<l){const j={};if(u.status&&u.status!==h.status&&(j.status=u.status),u.cdpConnected!==void 0&&(j.cdpConnected=u.cdpConnected),(f=u.chats)!=null&&f.length&&!((p=h.chats)!=null&&p.length)&&(j.chats=u.chats),u.machineNickname!==void 0&&u.machineNickname!==h.machineNickname&&(j.machineNickname=u.machineNickname),u.version!==void 0&&(j.version=u.version),u.serverVersion!==void 0&&(j.serverVersion=u.serverVersion),u.versionMismatch===!0&&(j.versionMismatch=!0),Object.keys(j).length>0){const P=Hr(h,u,{...h,...j,_lastUpdate:h._lastUpdate});i.set(u.id,qs(h,P,n))}else qs(h,{...h,_lastUpdate:h._lastUpdate},n)}else{const j=u.timestamp||n,P=h._lastUpdate||h.timestamp||0;if(j>=P){const k=(x=u.chats)!=null&&x.length?u.chats:h.chats,g=Hr(h,u,{...h,...u,chats:k,_lastUpdate:n});i.set(u.id,qs(h,g,n))}else(b=u.chats)!=null&&b.length&&!((S=h.chats)!=null&&S.length)&&i.set(u.id,{...h,chats:u.chats})}}const c=new Set(e.map(u=>u.id)),d=new Set;for(const u of e){const h=u.daemonId||((A=u.id)==null?void 0:A.split(":")[0]);h&&d.add(h)}for(const[u,h]of i){const y=h.daemonId||u.split(":")[0];if(!d.has(y))continue;if(o.has(y)&&!c.has(u)){i.delete(u);continue}const l=n-(h._lastUpdate||h.timestamp||0);(h.transport==="pty"&&!c.has(u)&&l>1e4||h.transport==="acp"&&!c.has(u)&&l>1e4||h.transport==="cdp-page"&&!c.has(u)&&l>3e4)&&i.delete(u)}for(const[u,h]of i)n-(h._lastUpdate||h.timestamp||0)>3e5&&h.status!=="online"&&i.delete(u);return Array.from(i.values())}function xc(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function hc({children:e,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,d]=a.useState([]),[m,f]=a.useState(void 0),p=a.useRef(r);a.useEffect(()=>{p.current=r},[r]);const x=a.useCallback((y,l)=>{n(j=>{let P=!1;const k=j.map(g=>g.id!==y||g.chats===l?g:(P=!0,{...g,chats:l}));return P?k:j})},[]),b=a.useCallback((y,l)=>{n(j=>{const P=j.length===0?y:fc(y,j,l),k=!xc(j,P);return k&&ss.record({kind:"dashboard.entries_applied",payload:{incoming:ia(y),next:ia(P)}}),k?P:j})},[]),S=a.useCallback(()=>i(!0),[]),A=a.useMemo(()=>({injectEntries:b,markLoaded:S,getIdes:()=>p.current}),[b,S]),u=s,h=a.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:o,toasts:c,setToasts:d,wsStatus:(u==null?void 0:u.wsStatus)??"connected",isConnected:(u==null?void 0:u.isConnected)??!0,connectionStates:(u==null?void 0:u.connectionStates)??{},connectionTransports:(u==null?void 0:u.connectionTransports)??{},showReconnected:(u==null?void 0:u.showReconnected)??!1,retryConnection:u==null?void 0:u.retryConnection,isP2PActive:(u==null?void 0:u.isP2PActive)??!1,p2pStates:(u==null?void 0:u.p2pStates)??{},userRole:u==null?void 0:u.userRole,userName:m,setUserName:f}),[r,x,o,c,u==null?void 0:u.wsStatus,u==null?void 0:u.isConnected,u==null?void 0:u.connectionStates,u==null?void 0:u.connectionTransports,u==null?void 0:u.showReconnected,u==null?void 0:u.retryConnection,u==null?void 0:u.isP2PActive,u==null?void 0:u.p2pStates,u==null?void 0:u.userRole,m]);return t.jsx(po.Provider,{value:A,children:t.jsx(mo.Provider,{value:h,children:e})})}function rs(){return a.useContext(mo)}function vr(){return a.useContext(po)}function fo(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function o(d){return d.startsWith("http")?d:`${s}${d.startsWith("/")?"":"/"}${d}`}function i(d){const m=r==null?void 0:r(),f=o(d),p=d.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return m&&p.searchParams.set("token",m),!d.startsWith("http")&&!s?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function c(d,m={}){const f={"Content-Type":"application/json",...m.headers||{}},p=r==null?void 0:r();p&&(f.Authorization=`Bearer ${p}`);const x=o(d),b=new AbortController,S=setTimeout(()=>b.abort(),15e3);try{const A=await fetch(x,{...m,headers:f,signal:b.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const u=await A.json().catch(()=>({error:A.statusText}));throw new Error(u.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,m,f={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),execTerminal:(d,m,f)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:f})}),sendAgentMessage:(d,m,f)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:f})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,m,f)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:m,action:f?"approve":"reject"})}),getMuxState:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/state`),getMuxSocketInfo:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/socket-info`),controlMux:(d,m,f={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),getMuxEventsUrl:d=>i(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>i(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const bc=fo({baseUrl:"http://localhost:3847"}),gc=a.createContext(bc);function yc({client:e,children:s}){return t.jsx(gc.Provider,{value:e,children:s})}const vc={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},xo=a.createContext(vc);function wc({value:e,children:s}){return t.jsx(xo.Provider,{value:e,children:s})}function Ct(){return a.useContext(xo)}const Ee={size:18};function ho({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Tn({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Bt({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function An({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function jc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function kc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function bo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Nc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Ar({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function go({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Sc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Kt({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function kt({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Mn({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Cc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function gs({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function js({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function ns({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ks({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function yo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function vo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function wo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Ic({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Mr({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Tc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function _n({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ac({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Mc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function _c({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Pc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Rc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function _r({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Lc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Dc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Ec({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function $c({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Bc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Kc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Wc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Oc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Hc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Uc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function zc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function la({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function da(e){return!!e&&typeof e=="object"&&"text"in e}function Pn(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(i=>typeof i=="string"?i:da(i)?String(i.text||""):"").join(r):da(e)?o=String(e.text||""):o=String(e||""),n?o.replace(/\s+/g," ").trim():o}function as(e){return Pn(e,{normalizeWhitespace:!0})}const Ur=new Map;function jo(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Fc(e,s,r){return Number(e.receivedAt||r[fs(e,s)]||0)||0}function ko(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Vc(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Ys(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function zr(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function ua(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):ko(e)?t.jsx(Sn,{remarkPlugins:[Cn,lo,uo],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Xs({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:ua(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const o=zr(r);return o?t.jsx("img",{src:o,alt:Ys(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const o=zr(r);return o?t.jsx("audio",{controls:!0,src:o,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const o=zr(r);return o?t.jsx("video",{controls:!0,src:o,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:Ys(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||Ys(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const o=Ys(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:o}),ua(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${n}`)}return null})})}function fs(e,s){const r=e,n=Pn(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const ma=5e3,Gc=a.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Sn,{remarkPlugins:[Cn],children:s.text}),t.jsx("span",{className:"action-time",children:jo(s.timestamp)})]})},(e,s)=>e.log===s.log),qc=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:d}){var g,N,v;const m=(s.role||"").toLowerCase(),f=m==="user"||m==="human",p=s.kind||(m==="tool"?"tool":"standard"),x=Vc(s.content)?s.content:null,b=!!(x!=null&&x.some(w=>w.type!=="text")),S=Pn(s.content,{joiner:`
|
|
4
|
+
`});if(p==="thought"){const w=typeof((g=s.meta)==null?void 0:g.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Pc,{size:13}),t.jsx("span",{children:w})]}),t.jsx("div",{className:"chat-msg-body",children:S})]})}if(p==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),b&&x?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Xs,{parts:x,renderAsPreformatted:!1})}):t.jsx("span",{className:"tool-text",children:S.split(`
|
|
5
|
+
`)[0].slice(0,80)})]});if(p==="terminal"){const w=(N=s.meta)!=null&&N.isRunning?"⏳":"✅",M=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:w}),t.jsx("span",{children:M})]}),b&&x?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Xs,{parts:x,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:S})]})}if(p==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:b&&x?t.jsx(Xs,{parts:x,renderAsPreformatted:!1}):S.slice(0,100)});const A=s.meta,h=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",y=S,l=!b&&i&&!f&&!h&&y.length>ma,j=l&&!c?y.slice(0,ma):y,P=h,k=!P&&ko(j);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(y||b||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${y||b?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?o||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:jo(r)})]}),(y||b)&&t.jsx("div",{className:"chat-markdown",children:b&&x?t.jsx(Xs,{parts:x,renderAsPreformatted:P}):P?t.jsx("pre",{className:"chat-preformatted",children:j}):k?t.jsx(Sn,{remarkPlugins:[Cn,lo,uo],children:j}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:j})}),l&&t.jsx("button",{onClick:d,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(y.length/100)*100} chars) ↓`})]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Yc=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:m={},emptyState:f,onLoadMore:p,isLoadingMore:x,hasMoreHistory:b,hiddenLiveCount:S=0,loadError:A,scrollToBottomRequestNonce:u},h){var ve;const y=a.useRef(null),l=a.useRef(null),j=a.useRef(null),P=a.useRef(0),k=a.useRef(""),g=a.useRef(!1),N=a.useRef(null),v=a.useRef(!1),w=a.useRef(null),M=a.useRef(!1),[T,$]=a.useState(new Set),E=a.useRef(!1),F=a.useRef(!1),D=()=>{const Q=y.current;return Q?Q.scrollHeight-Q.scrollTop-Q.clientHeight<200:!0},C=a.useCallback((Q="auto")=>{const xe=y.current;xe&&xe.scrollTo({top:xe.scrollHeight,behavior:Q})},[]),V=a.useCallback(()=>{const Q=y.current;!Q||!d||Ur.set(d,{top:Q.scrollTop,fromBottom:Math.max(0,Q.scrollHeight-Q.scrollTop-Q.clientHeight)})},[d]),J=a.useCallback(()=>{var ne;const Q=y.current,xe=(ne=window.getSelection)==null?void 0:ne.call(window);if(!Q||!xe||xe.rangeCount===0||xe.isCollapsed){M.current=!1;return}const W=xe.anchorNode,ee=xe.focusNode;M.current=!!(W&&ee&&Q.contains(W)&&Q.contains(ee))},[]),I=a.useCallback((Q="auto")=>{N.current!=null&&cancelAnimationFrame(N.current),N.current=requestAnimationFrame(()=>{N.current=null,C(Q)})},[C]),R=s.length>0?`${s.length}:${(((ve=s[s.length-1])==null?void 0:ve.content)||"").length}`:"0:0";a.useEffect(()=>{const Q=!g.current,xe=k.current!==d;if(k.current=d,Q||xe){if(g.current=!0,E.current=!1,v.current=!0,!M.current){const ee=d?Ur.get(d):null;ee?requestAnimationFrame(()=>{const ne=y.current;if(!ne)return;const oe=Math.max(0,ne.scrollHeight-ne.clientHeight-ee.fromBottom);ne.scrollTop=Number.isFinite(oe)?oe:ee.top,F.current=!0}):I("auto")}P.current=s.length;return}s.length>P.current?!E.current&&!M.current&&I("auto"):D()&&!E.current&&!M.current&&I("auto"),P.current=s.length},[R,d,c,s.length,I]),a.useEffect(()=>{u&&(E.current=!1,v.current=!0,F.current=!0,w.current!=null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{v.current=!1,w.current=null},180),M.current||I("auto"))},[I,u]),a.useEffect(()=>()=>{V(),N.current!=null&&cancelAnimationFrame(N.current),w.current!=null&&window.clearTimeout(w.current)},[V]),a.useEffect(()=>{const Q=l.current;if(!Q)return;const xe=()=>{w.current!=null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{v.current=!1,w.current=null},180)},W=new ResizeObserver(()=>{v.current&&(M.current||(I("auto"),xe()))});return W.observe(Q),()=>{W.disconnect(),w.current!=null&&(window.clearTimeout(w.current),w.current=null)}},[I,d]),a.useImperativeHandle(h,()=>({scrollToBottom:(Q="smooth")=>{C(Q)}}),[C]),a.useEffect(()=>{const Q=y.current;if(!Q)return;let xe;const W=()=>{clearTimeout(xe),xe=setTimeout(()=>{E.current=!D(),V()},50)};return Q.addEventListener("scroll",W,{passive:!0}),()=>{Q.removeEventListener("scroll",W),clearTimeout(xe)}},[V]),a.useEffect(()=>(document.addEventListener("selectionchange",J),()=>document.removeEventListener("selectionchange",J)),[J]);const B=a.useRef(0),z=a.useRef(!1);a.useEffect(()=>{const Q=y.current;if(!Q||!z.current||B.current===0)return;const xe=Q.scrollHeight-B.current;xe>0&&(Q.scrollTop=xe),V(),B.current=0,z.current=!1},[s.length,V]),a.useEffect(()=>{if(F.current||!d)return;const Q=Ur.get(d),xe=y.current;if(!Q||!xe)return;const W=Math.max(0,xe.scrollHeight-xe.clientHeight-Q.fromBottom);xe.scrollTop=Number.isFinite(W)?W:Q.top,F.current=!0},[d,s.length]);const Z=()=>{const Q=y.current;Q&&(B.current=Q.scrollHeight),z.current=!0,p==null||p()},fe=a.useMemo(()=>{const Q=s.map((ne,oe)=>({type:"message",data:ne,index:oe,ts:Fc(ne,oe,m)}));if(!r||r.length===0)return Q;const xe=[...r].sort((ne,oe)=>ne.timestamp-oe.timestamp).map((ne,oe)=>({type:"action",data:ne,index:oe,ts:ne.timestamp})),W=[];let ee=0;for(const ne of Q){for(;ee<xe.length&&ne.ts>0&&xe[ee].ts<ne.ts;)W.push(xe[ee++]);W.push(ne)}for(;ee<xe.length;)W.push(xe[ee++]);return W},[s,r,m]),Pe=S>0||!!b,ke=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:l,className:"chat-container-content",children:[x&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Pe&&!x&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:Z,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&S===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:ke})}),fe.length===0&&!Pe&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),fe.map(Q=>{if(Q.type==="action"){const te=Q.data;return t.jsx(Gc,{log:te},`action-${Q.index}`)}const xe=Q.data,W=Q.index,ee=fs(xe,W),ne=xe.receivedAt||m[ee],oe=`${d}-${ee}`,he=T.has(oe);return t.jsx(qc,{message:xe,receivedAt:ne,agentName:n,userName:o,isCliMode:i,isTextExpanded:he,onToggleTextExpanded:()=>$(te=>{const de=new Set(te);return he?de.delete(oe):de.add(oe),de})},`msg-${ee}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:j})]})})}),Xc=a.memo(Yc,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),Jc="modulepreload",Zc=function(e){return"/"+e},pa={},Qc=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(m=>{if(m=Zc(m),m in pa)return;pa[m]=!0;const f=m.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${p}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":Jc,f||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),f)return new Promise((b,S)=>{x.addEventListener("load",b),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&i(d.reason);return s().catch(i)})};let fa=!1;const No=a.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,d]=a.useState(null),m=a.useRef([]),f=a.useRef(!1),p=a.useRef(!1),x=a.useRef(!1),b=()=>{const S=i.current;if(S){f.current&&(S.clear(),f.current=!1);for(const A of m.current)S.write(A);m.current=[],p.current&&(S.fit(),p.current=!1),x.current&&(S.bumpResize(),x.current=!1)}};return a.useImperativeHandle(o,()=>({write:S=>{i.current?i.current.write(S):m.current.push(S)},clear:()=>{i.current?i.current.clear():(m.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.current=[],f.current=!0)},resize:(S,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(S,A)},fit:()=>{i.current?i.current.fit():p.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const S=requestAnimationFrame(()=>{b()});return()=>cancelAnimationFrame(S)},[c]),a.useEffect(()=>{let S=!1;return Qc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(A=>{fa||(fa=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||d(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{S=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});No.displayName="CliTerminal";function Js({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function xa({value:e,max:s,label:r,color:n="#8b5cf6",detail:o,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,d=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:d}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${d}, ${d}cc)`}})}),o&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function el({cursorPos:e,viewportRef:s,imgRef:r}){var l;if(!e||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(l=s.current)==null?void 0:l.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,d=n.naturalHeight||o.height,m=c/d,f=o.width/o.height;let p,x,b,S;m>f?(p=o.width,x=o.width/m,b=0,S=(o.height-x)/2):(x=o.height,p=o.height*m,b=(o.width-p)/2,S=0);const A=o.left-i.left+b+p*e.nx,u=o.top-i.top+S+x*e.ny,h=Math.max(8,Math.min(i.width-8,A)),y=Math.max(8,Math.min(i.height-8,u));return t.jsxs("div",{style:{position:"absolute",left:h-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function tl({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:d,handleImeSubmit:m,isConnActive:f,zoom:p,isMobile:x,mobileFillZoom:b,onZoomOut:S,onZoomReset:A,onZoomIn:u,transportType:h,screenshotUsage:y,lastActionStatus:l}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:j=>j.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(j=>!j),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:j=>j.stopPropagation(),onChange:j=>d(j.target.value),onKeyDown:j=>{m(j)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(j=>!j),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),p>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*100),"%"]}),h==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),h==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),l&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:l})]})]}),o&&t.jsxs("div",{onTouchStart:j=>j.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",p<=(x?b:1)+.01?x?"FILL":"FIT":`${Math.round(p*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:j=>{j.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:j=>{j.stopPropagation(),A()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:x?"FILL":"FIT"}),t.jsx("button",{onClick:j=>{j.stopPropagation(),u()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function sl({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function rl(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function ha(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function zs(e,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!rl())return;n.current+=1;const o=r.current;if(!o){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,d])=>[c,ha(d)]))}),r.current=s;return}const i=Object.keys({...o,...s}).filter(c=>!Object.is(o[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,ha(s[c])]))}),r.current=s})}function nl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:d,panYRef:m,setPanX:f,setPanY:p,setZoom:x,lastWheelTimeRef:b,onAction:S,setLastActionStatus:A,spawnRippleFromNormalized:u,clampPan:h,isMobile:y,mobileFillZoom:l}){const[j,P]=a.useState(null),k=a.useRef(null),g=a.useRef(null),N=a.useRef(null),v=a.useRef(!1),w=a.useRef(null),M=a.useRef(0),T=a.useRef(null),$=a.useRef(1),E=a.useRef({x:0,y:0}),F=a.useRef(!1),D=a.useRef(n),C=a.useRef(S),V=30,J=550,I=18,R=60,B=400,z=12,Z=()=>{if(k.current)return;const ke={nx:.5,ny:.5};k.current=ke,P(ke)};return a.useEffect(()=>{D.current=n,n==="mouse"&&Z()},[n]),a.useEffect(()=>{C.current=S},[S]),a.useEffect(()=>{const ke=e.current;if(!ke)return;const ve=oe=>{if(!r.current)return null;const he=r.current.getBoundingClientRect();return!he.width||!he.height?null:{nx:Math.max(0,Math.min(1,(oe.clientX-he.left)/he.width)),ny:Math.max(0,Math.min(1,(oe.clientY-he.top)/he.height))}},Q=(oe,he)=>{if(!r.current)return{dnx:0,dny:0};const te=r.current,de=te.getBoundingClientRect(),se=te.naturalWidth||de.width,pe=te.naturalHeight||de.height,ae=se/pe,Ne=de.width/de.height;let ge,_;return ae>Ne?(ge=de.width,_=de.width/ae):(_=de.height,ge=de.height*ae),{dnx:oe/ge,dny:he/_}},xe=(oe,he,te)=>{if(te<=1.05)return;const de=-(oe-.5)*100,se=-(he-.5)*100,pe=h(de,se,te);(Math.abs(pe.x-d.current)>.1||Math.abs(pe.y-m.current)>.1)&&(f(pe.x),p(pe.y),d.current=pe.x,m.current=pe.y)},W=oe=>{const he=s.current;if(he&&oe.target instanceof Node&&he.contains(oe.target))oe.preventDefault();else return;if(oe.touches.length===1){const te=oe.touches[0];g.current={x:te.clientX,y:te.clientY,time:Date.now()},N.current={x:te.clientX,y:te.clientY},F.current||(v.current=!1),w.current=setTimeout(()=>{if(!v.current&&!F.current)if(v.current=!0,D.current==="mouse"){const de=k.current||{nx:.5,ny:.5};A("Right Click"),u(de.nx,de.ny,"right"),C.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=ve(te);de&&(A("Right Click"),u(de.nx,de.ny,"right"),C.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(oe.touches.length===2){w.current&&clearTimeout(w.current),v.current=!0,F.current=!0;const te=oe.touches[1].clientX-oe.touches[0].clientX,de=oe.touches[1].clientY-oe.touches[0].clientY;T.current=Math.sqrt(te*te+de*de),$.current=c.current,E.current={x:(oe.touches[0].clientX+oe.touches[1].clientX)/2,y:(oe.touches[0].clientY+oe.touches[1].clientY)/2}}},ee=oe=>{const he=s.current;if(he&&oe.target instanceof Node&&he.contains(oe.target)&&oe.preventDefault(),oe.touches.length===1&&N.current){const te=oe.touches[0],de=te.clientX-N.current.x,se=te.clientY-N.current.y;if(!v.current&&g.current){const pe=te.clientX-g.current.x,ae=te.clientY-g.current.y;Math.sqrt(pe*pe+ae*ae)>8&&(v.current=!0,w.current&&clearTimeout(w.current))}if(v.current)if(D.current==="mouse"){const pe=Q(de,se),ae=k.current||{nx:.5,ny:.5},Ne=Math.max(0,Math.min(1,ae.nx+pe.dnx)),ge=Math.max(0,Math.min(1,ae.ny+pe.dny));k.current={nx:Ne,ny:ge},P({nx:Ne,ny:ge}),A(`Cursor: ${Math.round(Ne*100)}%, ${Math.round(ge*100)}%`),xe(Ne,ge,c.current);const _=Date.now();_-b.current>=30&&(b.current=_,C.current("input_mouseMoved",{nx:Ne,ny:ge}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const ae=pe.clientWidth,Ne=pe.clientHeight,ge=d.current+de/ae*100,_=m.current+se/Ne*100,ue=h(ge,_,c.current);f(ue.x),p(ue.y),d.current=ue.x,m.current=ue.y}}else{const pe=ve(te);if(pe){const ae=Date.now();ae-b.current>=40&&(b.current=ae,A("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}N.current={x:te.clientX,y:te.clientY};return}if(oe.touches.length===2&&T.current!==null){const te=oe.touches[1].clientX-oe.touches[0].clientX,de=oe.touches[1].clientY-oe.touches[0].clientY,pe=Math.sqrt(te*te+de*de)/T.current,ae=(oe.touches[0].clientX+oe.touches[1].clientX)/2,Ne=(oe.touches[0].clientY+oe.touches[1].clientY)/2,ge=ae-E.current.x,_=Ne-E.current.y,ue=Math.abs(pe-1)>.03;if(D.current==="mouse"){if(ue){const X=Math.max(i,Math.min(5,$.current*pe));x(X),c.current=X}else if(Math.abs(ge)>2||Math.abs(_)>2){const X=k.current||{nx:.5,ny:.5},ce=Date.now();ce-b.current>=30&&(b.current=ce,A("Scroll"),C.current("input_wheel",{nx:X.nx,ny:X.ny,deltaX:Math.round(-ge*3),deltaY:Math.round(-_*3)}).catch(()=>{}))}}else{const X=Math.max(i,Math.min(5,$.current*pe));x(X),c.current=X;const ce=s.current;if(ce&&X>1){const Ce=ce.clientWidth,Re=ce.clientHeight,me=d.current+ge/Ce*100,We=m.current+_/Re*100,Be=h(me,We,X);f(Be.x),p(Be.y),d.current=Be.x,m.current=Be.y}}E.current={x:ae,y:Ne}}},ne=oe=>{var he;if(w.current&&clearTimeout(w.current),T.current=null,oe.touches.length===1&&F.current){const te=oe.touches[0];g.current={x:te.clientX,y:te.clientY,time:Date.now()},N.current={x:te.clientX,y:te.clientY},v.current=!0;return}if(oe.touches.length===0){if(F.current){F.current=!1,v.current=!1;return}if(oe.changedTouches.length===1){const te=oe.changedTouches[0],de=Date.now(),se=de-(((he=g.current)==null?void 0:he.time)||0),pe=g.current?te.clientX-g.current.x:0,ae=g.current?te.clientY-g.current.y:0,Ne=Math.sqrt(pe*pe+ae*ae);if(D.current==="mouse"){if(se<V||se>J||Ne>I){v.current=!1;return}const ge=k.current||ve(te);ge&&(A(`Click: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),u(ge.nx,ge.ny,"left"),C.current("input_click",{...ge}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(se<R||se>B||Ne>z){v.current=!1;return}const ge=ve(te);if(!ge)return;de-M.current<300?(A("Double tap"),u(ge.nx,ge.ny,"double"),C.current("input_click",{...ge,clickCount:2}).catch(()=>{}),M.current=0):(A(`Tap: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),u(ge.nx,ge.ny,"left"),C.current("input_click",{...ge}).catch(()=>{}),M.current=de)}}v.current=!1}};return ke.addEventListener("touchstart",W,{passive:!1}),ke.addEventListener("touchmove",ee,{passive:!1}),ke.addEventListener("touchend",ne,{passive:!1}),()=>{ke.removeEventListener("touchstart",W),ke.removeEventListener("touchmove",ee),ke.removeEventListener("touchend",ne),w.current&&clearTimeout(w.current)}},[e,s,r,i,c,d,m,f,p,x,b,A,u,h]),{cursorPos:j,cursorPosRef:k,handleToggleInputMode:()=>{o(ke=>{const ve=ke==="touch"?"mouse":"touch";return ve==="mouse"&&Z(),ve})},handleZoomReset:()=>{const ke=y?l:1;x(ke),c.current=ke,f(0),p(0),d.current=0,m.current=0}}}function So({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),d=a.useRef(null),m=a.useRef(null),[f,p]=a.useState(null),[x,b]=a.useState(""),[,S]=a.useState(!1),[A,u]=a.useState([]),h=a.useRef(0),[y,l]=a.useState(!1),[j,P]=a.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,N]=a.useState(k?"mouse":"touch"),[v,w]=a.useState(1),M=a.useRef(!1),[T,$]=a.useState(1),[E,F]=a.useState(0),[D,C]=a.useState(0);zs("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:g,zoom:T,panX:E,panY:D,isMenuOpen:y,isImeOpen:j});const V=a.useRef(0),J=a.useRef(T),I=a.useRef(E),R=a.useRef(D);a.useEffect(()=>{J.current=T},[T]),a.useEffect(()=>{I.current=E},[E]),a.useEffect(()=>{R.current=D},[D]),a.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const B=r==="connected",z=n,Z=B?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",fe=B?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!k||M.current||!z)return;const se=m.current,pe=d.current;if(!se||!pe)return;const ae=()=>{const Ne=pe.clientWidth,ge=pe.clientHeight,_=se.naturalWidth,ue=se.naturalHeight;if(!_||!ue||!Ne||!ge)return;const X=Math.min(Ne/_,ge/ue),Ce=Math.max(Ne/_,ge/ue)/X;Ce>1.01&&(w(Ce),$(Ce),J.current=Ce),M.current=!0};se.complete&&se.naturalWidth?ae():se.addEventListener("load",ae,{once:!0})},[z,k]);const Pe=.5;a.useEffect(()=>{T<=Pe&&(F(0),C(0))},[T,Pe]);const ke=(se,pe,ae)=>{if(ae<=Pe)return{x:0,y:0};const Ne=(ae-1)/(2*ae)*100,ge=(ae-1)/(2*ae)*100;return{x:Math.max(-Ne,Math.min(Ne,se)),y:Math.max(-ge,Math.min(ge,pe))}},ve=(se,pe)=>{if(!m.current)return null;const ae=m.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(se-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(pe-ae.top)/ae.height))}},Q=(se,pe,ae)=>{const Ne=d.current;if(!Ne)return;const ge=Ne.getBoundingClientRect(),_=++h.current;u(ue=>[...ue,{id:_,x:se-ge.left,y:pe-ge.top,type:ae}]),setTimeout(()=>u(ue=>ue.filter(X=>X.id!==_)),600)},xe=(se,pe,ae)=>{const Ne=m.current,ge=d.current;if(!Ne||!ge)return;const _=Ne.getBoundingClientRect(),ue=ge.getBoundingClientRect(),X=Ne.naturalWidth||_.width,ce=Ne.naturalHeight||_.height,Ce=X/ce,Re=_.width/_.height;let me,We,Be,Ze;Ce>Re?(me=_.width,We=_.width/Ce,Be=0,Ze=(_.height-We)/2):(We=_.height,me=_.height*Ce,Be=(_.width-me)/2,Ze=0);const Ge=_.left-ue.left+Be+me*se,gt=_.top-ue.top+Ze+We*pe,Xe=++h.current;u(ot=>[...ot,{id:Xe,x:Ge,y:gt,type:ae}]),setTimeout(()=>u(ot=>ot.filter(ut=>ut.id!==Xe)),600)},W=async se=>{var ae;const pe=ve(se.clientX,se.clientY);if(pe){p(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),Q(se.clientX,se.clientY,"left"),(ae=c.current)==null||ae.focus();try{const Ne=await e("input_click",{nx:pe.nx,ny:pe.ny});Ne!=null&&Ne.success||s(`❌ Click failed: ${Ne==null?void 0:Ne.error}`)}catch(Ne){s(`❌ Click error: ${Ne.message||Ne}`)}}},ee=async(se,pe,ae,Ne=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:se,code:pe,text:ae?se:void 0,unmodifiedText:ae?se:void 0,modifiers:Ne})}catch(ge){s(`❌ Key error: ${ge.message||ge}`)}},ne=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let ae=0;se.altKey&&(ae|=1),se.ctrlKey&&(ae|=2),se.metaKey&&(ae|=4),se.shiftKey&&(ae|=8),p(`Key: ${se.key}`),await ee(se.key,se.code,se.key.length===1,ae)},oe=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(x){const pe=x;b(""),p(`IME Sent: ${pe}`);try{const ae=await e("input_type",{text:pe});ae!=null&&ae.success||s(`❌ IME error: ${ae==null?void 0:ae.error}`)}catch(ae){s(`❌ IME error: ${ae.message}`)}}else p("Key: Enter"),await ee("Enter","Enter",!1)}};a.useEffect(()=>{const se=c.current;if(!se)return;const pe=ae=>{var Ne;if((Ne=m.current)!=null&&Ne.contains(ae.target)){ae.preventDefault();const ge=Date.now();if(ge-V.current<40)return;V.current=ge;const _=ve(ae.clientX,ae.clientY);if(!_)return;p(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:_.nx,ny:_.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",pe,{passive:!1}),()=>se.removeEventListener("wheel",pe)},[e]);const{cursorPos:he,handleToggleInputMode:te,handleZoomReset:de}=nl({containerRef:c,viewportRef:d,imgRef:m,inputMode:g,setInputMode:N,minZoom:Pe,zoomRef:J,panXRef:I,panYRef:R,setPanX:F,setPanY:C,setZoom:$,lastWheelTimeRef:V,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:xe,clampPan:ke,isMobile:k,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ne,onContextMenu:se=>se.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[t.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[z?t.jsx("img",{ref:m,src:z,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${E}%, ${D}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):t.jsx(sl,{waitingLabel:Z,waitingHint:fe,transportType:i}),g==="mouse"&&z&&t.jsx(el,{cursorPos:he,viewportRef:d,imgRef:m}),A.map(se=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return t.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ae}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ae}, 0.9)`,boxShadow:`0 0 12px rgba(${ae}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},se.id)})]}),t.jsx(tl,{inputMode:g,onToggleInputMode:te,isImeOpen:j,setIsImeOpen:P,isMenuOpen:y,setIsMenuOpen:l,imeText:x,setImeText:b,handleImeSubmit:oe,isConnActive:B,zoom:T,isMobile:k,mobileFillZoom:v,onZoomOut:()=>$(se=>Math.max(.5,se-.25)),onZoomReset:de,onZoomIn:()=>$(se=>Math.min(5,se+.25)),transportType:i,screenshotUsage:o,lastActionStatus:f}),t.jsx("style",{children:`
|
|
6
|
+
@keyframes slideUp {
|
|
7
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
8
|
+
to { opacity: 1; transform: translateY(0); }
|
|
9
|
+
}
|
|
10
|
+
@keyframes slideUpSidebar {
|
|
11
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
12
|
+
to { opacity: 1; transform: translateY(0); }
|
|
13
|
+
}
|
|
14
|
+
@keyframes click-ripple-ring {
|
|
15
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
16
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
17
|
+
}
|
|
18
|
+
@keyframes click-ripple-dot {
|
|
19
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
20
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
21
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
22
|
+
}
|
|
23
|
+
@keyframes remote-float {
|
|
24
|
+
0% { transform: translateY(0px); }
|
|
25
|
+
50% { transform: translateY(-7px); }
|
|
26
|
+
100% { transform: translateY(0px); }
|
|
27
|
+
}
|
|
28
|
+
`})]})}function Rn(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<o)return n;const d=Math.floor(c/60);if(d<60)return`${d}m${r}`;const m=Math.floor(d/60);if(m<24)return`${m}h${r}`;const f=Math.floor(m/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Co=e=>Rn(e);function al(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function ks(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",o=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Fs(e){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...al(o)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Ws(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Os(e,s,r){const n=Ws(e,s),o=ks(e),i=o.isReconnecting,c=o.isConnecting,d=o.isGenerating,m=o.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||m,p=n.inboxBucket==="working"||d,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:f,isWorking:p,isReconnecting:i,isConnecting:c,isGenerating:d,isWaiting:m,inboxBucket:f?"needs_attention":p?"working":x?"task_complete":"idle"}}function ol(e,s,r){return Os(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function il(e,s,r){return Ws(e,r||new Map).surfaceHidden}function Io({activeConv:e,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!ks(e).isWaiting||!e.modalButtons)return null;const i=d=>{r||(n(d),s(d))},c=d=>d.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(ns,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((d,m)=>{const f=c(d).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),b=r===d,S=r!==null;return t.jsx("button",{onClick:()=>i(d),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!b?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:b?"⏳ ...":c(d)},m)})})]})]})}var cl=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ll(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function bt(e,s){if(ll(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":cl.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function To(e){return bt(e)==="generating"}function et(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"IDE"}function dl(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const o=Math.floor(r/24),i=r%24;return`${o}d ${i}h`}function Fr(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Pr(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function ul(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function ml(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function pl(e){return ul(e.trim().replace(/\.local$/i,""))}function fl(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Ao(e,s={}){var o,i;const r=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!ml(c));if(r&&r!=="Unknown")return pl(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function jt(e,s={}){return fl(e)||Ao(e,s)}function Hs(e){return e.transport==="pty"}function xs(e){return e.transport==="acp"}function ba(e,s){return et(e)}function ga(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=et(r||"").trim().toLowerCase();return n===o||n===i||n===c}function xl(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function hl(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=bt(n.status);if(!i){s.set(o,{...n,status:c});continue}const d=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(d<0||m<d)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function bl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function gl(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&bl(s.receivedAt)||0}function yl(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function xn(e){return Math.max(yl(e),gl(e.activeChat))}function vl(e,s,r,n,o,i){const c=s-e;if(c!==0)return c;const d=r.localeCompare(n);return d!==0?d:o.localeCompare(i)}function Ln(e,s){return vl(xn(e),xn(s),jt(e,{fallbackId:e.id}),jt(s,{fallbackId:s.id}),e.id,s.id)}const Mo="adhdev_notification_prefs",ya={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function wl(){try{const e=localStorage.getItem(Mo);if(e){const s=JSON.parse(e);return{...ya,...s}}}catch{}return{...ya}}function jl(e){try{localStorage.setItem(Mo,JSON.stringify(e))}catch{}}let Et=wl(),pr=[];function kl(){pr.forEach(e=>e())}function Nl(e){Et={...Et,...e},jl(Et),kl()}function Sl(){const[,e]=a.useState(0);a.useEffect(()=>{const r=()=>e(n=>n+1);return pr.push(r),()=>{pr=pr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Nl(r)},[]);return[{...Et},s]}function Ps(e){if(!Et.globalEnabled)return!1;switch(e){case"disconnect":return Et.disconnectAlert;case"completion":return Et.completionAlert;case"approval":return Et.approvalAlert;case"browser":return Et.browserNotifications;default:return!0}}const Cl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Il(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function _o(){return"Notification"in window&&Notification.permission==="granted"}let Ft=null;async function Tl(){if(Ft!==null)return Ft;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ft=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ft=!!await e.pushManager.getSubscription(),Ft):(Ft=!1,!1)}catch{return Ft=!1,!1}}function hn(e,s,r){if(_o())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Al(e,s={}){const r={...Cl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Tl().then(d=>{i.current=d})},[]);const c=a.useCallback((d,m,f)=>{const p=Date.now();p-o.current<r.throttleMs||(o.current=p,hn(d,m,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!_o())&&Ps("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of e)n.current.set(m.id,bt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const f=n.current.get(m.id),p=bt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Ps("approval")&&p==="waiting_approval"&&f!=="waiting_approval"){const b=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,b.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ps("completion")&&To(f)&&p==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Ml=/^(run|approve|accept|yes|allow|always)/,_l=/^(run|approve|accept|yes|allow|always|proceed|save)/,Pl=/^(reject|deny|delete|remove|abort|cancel|no)/;function Dn(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Rl(e){const s=Dn(e).toLowerCase();return Ml.test(s)?"primary":Pl.test(s)?"danger":"default"}function Ll(e){return _l.test(Dn(e).toLowerCase())?"approve":"reject"}function Dl(e){return e.map((s,r)=>({label:Dn(s),variant:Rl(s),action:Ll(s),button:s,buttonIndex:r}))}function El(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
29
|
+
${n}`}function $l(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Bl(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class Kl{constructor(){lt(this,"dedupMap",new Map);lt(this,"DEDUP_WINDOW_MS",5e3);lt(this,"DEDUP_MAX_SIZE",50);lt(this,"DEDUP_CLEANUP_AGE_MS",1e4);lt(this,"toastCallbacks",[]);lt(this,"systemMessageCallbacks",[]);lt(this,"clearSystemMessageCallbacks",[]);lt(this,"resolveActionFn",null);lt(this,"viewRequestRespondFn",null);lt(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const o=(n==null?void 0:n.id)||Date.now();this.emitToast({id:o,message:s,type:r,timestamp:o,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(s){if(s.daemonId){const o=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(o)return o}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const o=r.daemonId;if(o){const i=this.ides.find(c=>c.id===o&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(o=>o.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(o=>(o==null?void 0:o.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var A,u;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),d=`${i}:${s.event}:${c}`;if(this.isDuplicate(d))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(m==null?void 0:m.type)||"";let p=et(f);const x=this.resolveOwningDaemon(s);if(x){const h=jt(x,{fallbackId:x.id});h&&(p=!f||f==="adhdev-daemon"?h:`${h}/${p}`)}let b="",S="info";if(s.event==="agent:generating_completed"){const h=s.duration?` (${s.duration}s)`:"";b=`✅ ${p} agent task completed${h}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(b=`⚡ ${p} approval needed`,S="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:El(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(s);if(!h)return;const y=this.resolveActionFn,l=Dl(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{y(h,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),j=$l(p,s.modalMessage,b),P=Date.now();this.emitToast({id:P,message:j,type:S,timestamp:P,targetKey:n||h,actions:l,duration:15e3}),b=""}}else if(s.event==="monitor:long_generating"){const h=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";b=`⚠️ ${p} agent is taking a long time${h}`,S="warning",Ps("browser")&&!document.hasFocus()&&hn(`⚠️ ${p} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const h=s.requesterName||"A team member",y=s.requestId,l=s.orgId;if(b=`👁️ ${h} wants to view your session`,S="warning",y&&l&&this.viewRequestRespondFn){const j=Date.now(),P=Bl(l,y,this.viewRequestRespondFn,(k,g)=>console.error(`[EventManager] ${k} view request failed:`,g));this.emitToast({id:j,message:b,type:S,timestamp:j,actions:P,duration:3e4}),b=""}Ps("browser")&&!document.hasFocus()&&hn("👁️ View Request",`${h} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(b="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(b=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(b){const h=Date.now();this.emitToast({id:h,message:b,type:S,timestamp:h,targetKey:n||s.daemonId,duration:5e3})}}}const tt=new Kl,va=new Map;function ys(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Po(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Wl(e){return!ys(e)||!ys(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Zs(e){return!ys(e)||!ys(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Cs(e){if(!(!ys(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Qs(e){return ys(e)&&e.success===!1}function Ol(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const o=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,o);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const o=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,o)}}}function Hl(e,s){return e&&Po(e.currentValue)?e.currentValue:s}function fr(e,s){return e.options||s[e.id]||[]}function Ul(e,s,r){var o;return r?((o=fr(e,s).find(i=>i.value===r))==null?void 0:o.label)||r:""}const zl={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Fl({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c}){const{sendCommand:d}=Ct(),m=`${e}:${s||n}`,f=zl[n]||"#94a3b8",[p,x]=a.useState({}),b=a.useRef(0),S={};for(const D of i||[])D.defaultValue!==void 0&&(S[D.id]=D.defaultValue);const A={...S,...c||{},...Date.now()<b.current?p:{}};a.useEffect(()=>{c&&Date.now()>b.current&&x({})},[c]);const[u,h]=a.useState(va.get(m)||{}),[y,l]=a.useState(null),[j,P]=a.useState(null),k=a.useCallback(async(D,C={})=>{const V={...C,...s&&{targetSessionId:s}};return await d(e,D,V)},[e,s,d]),g=a.useCallback(async(D,C={})=>{const V=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...V,scriptName:D,...C})},[k,n,r,s]);if(!i||i.length===0)return null;const N=i.filter(D=>D.placement==="bar"&&D.hidden!==!0).sort((D,C)=>(D.order??50)-(C.order??50));if(N.length===0)return null;const v=a.useCallback((D,C,V)=>{const J=Hl(V,C);x(I=>({...I,[D.id]:J})),Ol(V==null?void 0:V.effects)},[]),w=a.useCallback((D,C)=>{x(V=>{const J={...V};return C===void 0?delete J[D.id]:J[D.id]=C,J}),b.current=0},[]),M=async D=>{if(y===D.id){l(null);return}if(fr(D,u).length>0){l(D.id);return}if(D.dynamic&&D.listScript){P(D.id);try{const V=await g(D.listScript,{}),J=Wl(V);if(!J){const R=Cs(V);R&&tt.showToast(R,"warning");return}const I=J.options;h(R=>{const B={...R,[D.id]:I};return va.set(m,B),B}),Po(J.currentValue)&&x(R=>({...R,[D.id]:J.currentValue})),l(D.id)}catch(V){const J=V instanceof Error?V.message:`Could not load ${D.label}`;tt.showToast(J,"warning")}finally{P(null)}}},T=async(D,C)=>{l(null);const V=(c==null?void 0:c[D.id])??S[D.id];x(J=>({...J,[D.id]:C})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const J=await g(D.setScript,{model:D.id==="model"?C:void 0,mode:D.id==="mode"?C:void 0,value:C}),I=Zs(J);if(I&&!I.ok||Qs(J))throw new Error((I==null?void 0:I.error)||Cs(J)||`Could not update ${D.label}`);v(D,C,I)}catch(J){w(D,V);const I=J instanceof Error?J.message:`Could not update ${D.label}`;tt.showToast(I,"warning")}},$=async D=>{const C=fr(D,u).map(z=>z.value);if(C.length===0)return;const V=String(A[D.id]||""),I=(C.indexOf(V)+1)%C.length,R=C[I];if(typeof R!="string")return;const B=(c==null?void 0:c[D.id])??S[D.id];x(z=>({...z,[D.id]:R})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const z=await g(D.setScript,{value:R}),Z=Zs(z);if(Z&&!Z.ok||Qs(z))throw new Error((Z==null?void 0:Z.error)||Cs(z)||`Could not update ${D.label}`);v(D,R,Z)}catch(z){w(D,B);const Z=z instanceof Error?z.message:`Could not update ${D.label}`;tt.showToast(Z,"warning")}},E=async D=>{const V=!A[D.id],J=(c==null?void 0:c[D.id])??S[D.id];x(I=>({...I,[D.id]:V})),b.current=Date.now()+5e3;try{if(!D.setScript)return;const I=await g(D.setScript,{value:V}),R=Zs(I);if(R&&!R.ok||Qs(I))throw new Error((R==null?void 0:R.error)||Cs(I)||`Could not update ${D.label}`);v(D,V,R)}catch(I){w(D,J);const R=I instanceof Error?I.message:`Could not update ${D.label}`;tt.showToast(R,"warning")}},F=async D=>{if(!D.invokeScript)return;if(D.confirmMessage){const V=[D.confirmTitle,D.confirmMessage,D.confirmLabel].filter(I=>typeof I=="string"&&I.trim().length>0);if(!window.confirm(V.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const C=(c==null?void 0:c[D.id])??S[D.id];try{const V=await g(D.invokeScript),J=Zs(V);if(J&&!J.ok||Qs(V))throw new Error((J==null?void 0:J.error)||Cs(V)||`Could not run ${D.label}`);J&&v(D,C??!0,J)}catch(V){w(D,C);const J=V instanceof Error?V.message:`Could not run ${D.label}`;tt.showToast(J,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:f},children:o}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),N.map(D=>{const C=String(A[D.id]||""),V=Ul(D,u,C),J=y===D.id,I=j===D.id,R=fr(D,u);switch(D.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:J?`${f}55`:"transparent",border:"1px solid",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),I?"...":V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),J&&R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>l(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:D.label.toUpperCase()}),R.map(B=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:B.value===C?`${f}18`:"transparent",color:B.value===C?f:"var(--text-secondary)",fontWeight:B.value===C?600:400,borderLeft:B.value===C?`2px solid ${f}`:"2px solid transparent"},title:B.description||B.label,onMouseEnter:z=>{z.currentTarget.style.background=`${f}12`},onMouseLeave:z=>{z.currentTarget.style.background=B.value===C?`${f}18`:"transparent"},onClick:()=>T(D,B.value),children:B.label},B.value))]})]})]},D.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(D),title:`Click to cycle: ${R.map(B=>B.label).join(" → ")}`,children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),V||D.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},D.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:C?`${f}44`:"transparent",background:C?`${f}14`:"var(--surface-tertiary)",color:C?f:"var(--text-muted)"},onClick:()=>E(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.label]},D.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>F(D),children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),D.resultDisplay==="inline"&&C?`${D.label}: ${C}`:D.label]},D.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:C?"var(--text-primary)":"var(--text-muted)"},children:[D.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:D.icon}),C?`${D.label}: ${C}`:D.label]},D.id);default:return null}})]})}const Vl=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const f=()=>{const p=d.trim();!p||n||(m(""),o(p))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:p=>m(p.target.value),onPaste:p=>{const x=p.clipboardData.getData("text");x&&m(b=>b+x),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),f()}},onBlur:p=>{if(window.innerWidth<768){const x=p.relatedTarget;if((x==null?void 0:x.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:f,disabled:!d.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),Ye=e=>e.transport==="pty",vs=(e,s)=>Ye(e)?e.mode||"terminal":"chat",Ro=(e,s)=>Ye(e)&&vs(e)==="terminal",Ve=e=>e.transport==="acp";function $t(e){return e.streamSource!=="agent-stream"}function Ut(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Lo(e){return e.machineName||""}function wr(e){return Ut(e)}function wt(e){return e.agentType||""}function En(e){return e.hostIdeType||""}function Rr(e){return e.displayPrimary||e.agentName||"Agent"}function $n(e){return[e.displaySecondary,Lo(e)].filter(Boolean)}function Vs(e){return e.agentName||et(wt(e))}function Gl(e){var s,r;if(!$t(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return et(En(e)||wt(e))}function Bn(e){return $t(e)?e.sessionId:e.nativeSessionId}function wa(e){return $t(e)?"native":e.tabKey}function ql(e){return e.sessionId}function Yl(e,s){if(s)return $t(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Xl(e,s){const r=wt(e),n=$t(e)?s!=null&&s.type?et(s.type):et(En(e)||r):Vs(e);return{isNativeConversation:$t(e),isCli:Ye(e),isAcp:Ve(e),isCliTerminal:Ro(e),providerType:r,displayLabel:n,targetEntry:Yl(e,s)}}function Do({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ws(),c=Ut(e),d=Lo(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,p=!f&&(e.transport==="pty"||e.transport==="acp"),x=Vs(e),b=Gl(e),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=a.useCallback(()=>{if(r){r();return}const u=Bn(e);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:A,title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]}):t.jsxs("span",{className:"conversation-meta-chip",title:b,children:[t.jsx(kt,{size:12}),t.jsx("span",{children:b})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Ks,{size:12}),t.jsx("span",{children:x})]}),d&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(Bt,{size:12}),t.jsx("span",{children:d})]}))]})}function ja(e,s){return`${e}:${s}`}function Jl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function er(e,s){Jl()&&console.debug(`[subscription-manager] ${e}`,s)}class Zl{constructor(){lt(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=ja(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,p),er("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const m=()=>{var b;const p=this.active.get(i);if(!p||(p.handlers.delete(o),p.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};er("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(b=s.sendData)==null||b.call(s,r,x)};return m.initialSendAccepted=d,m}publish(s){const r=ja(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),ss.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;er("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var o;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);er("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const Ot=new Zl;function Ql(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,currentModel:n.currentModel,currentPlan:n.currentPlan,currentAutoApprove:n.currentAutoApprove,controlValues:n.controlValues,providerControls:n.providerControls,acpConfigOptions:n.acpConfigOptions,acpModes:n.acpModes,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function tr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:e.currentModel??(s==null?void 0:s.currentModel),currentPlan:e.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:e.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:e.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:e.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function ed(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const o=r.get(n.parentId)||[];o.push(n),r.set(n.parentId,o)}else s.push(n);return{topLevel:s,childrenByParent:r}}function jr(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:f,childrenByParent:p}=ed(m),x=Ql(i,n),b=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,S=f.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),A=f.filter(h=>h.kind==="agent"&&h.transport==="pty"),u=f.filter(h=>h.kind==="agent"&&h.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:d,...e.version&&{version:e.version},...b&&{machine:b,platform:b.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:S.some(h=>!!h.cdpConnected)});for(const h of S){const y=x.get(h.id),l=tr(h,y),j=(p.get(h.id)||[]).map(P=>tr(P,x.get(P.id)));r.push({id:`${n}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:h.id,workspace:l.workspace,terminals:0,childSessions:j,agents:j.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.status})),activeChat:l.activeChat,chats:[],cdpConnected:l.cdpConnected,...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.currentAutoApprove!==void 0&&{currentAutoApprove:l.currentAutoApprove},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d})}for(const h of A){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:l.mode||(y==null?void 0:y.mode)||"terminal",workspace:l.workspace||"",activeChat:l.activeChat,...l.resume!==void 0&&{resume:l.resume},...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isCli:!0})}for(const h of u){const y=x.get(h.id),l=tr(h,y);r.push({id:`${n}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:h.id,cliName:l.providerName||l.providerType,mode:"chat",workspace:l.workspace||"",activeChat:l.activeChat,...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.acpConfigOptions!==void 0&&{acpConfigOptions:l.acpConfigOptions},...l.acpModes!==void 0&&{acpModes:l.acpModes},...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isAcp:!0})}return r}const Vr=new Map,Gr=new Map,qr=new Set,Rs=new Map,td=1200;function sd(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const o=n.status;if(o&&typeof o=="object")return o}return s}function ka(e,s){const r=Rs.get(e);!r||r.size===0||(Rs.delete(e),r.forEach(n=>n(s)))}function rd(e,s){return new Promise(r=>{const n=Rs.get(e)||new Set;Rs.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Rs.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Gs(){const{sendCommand:e,sendData:s}=Ct(),{injectEntries:r,getIdes:n}=vr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=Gr.get(o)||0;if(!(i!=null&&i.force)&&qr.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const m=Vr.get(o);if(m)return m;const f=(async()=>{if(s&&!qr.has(o)&&(qr.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const h=n(),y=h.find(j=>j.id===o),l=jr(u.status,{daemonId:o,existingDaemon:y,existingEntries:h,timestamp:u.timestamp});l.length>0&&r(l),Gr.set(o,Date.now()),ka(o,!0)}),!(i!=null&&i.force)&&await rd(o,td)))return;const p=await e(o,"get_status_metadata"),x=sd(p);if(!x)return;const b=n(),S=b.find(u=>u.id===o),A=jr(x,{daemonId:o,existingDaemon:S,existingEntries:b,timestamp:x.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[o]}),Gr.set(o,Date.now()),ka(o,!0)})().finally(()=>{Vr.delete(o)});return Vr.set(o,f),f},[n,r,e,s])}function os(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Eo(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=as(e.content),i=as(s.content);if(!o||o!==i)return!1;const c=os(e),d=os(s);return c&&d?Math.abs(c-d)<=15e3:!!e._localId!=!!s._localId}function Na(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),os(e)&&(s+=1),s}function nd(e,s){const r=Na(e),n=Na(s);return n!==r?n>r?s:e:as(s.content).length>=as(e.content).length?s:e}function Ls(e){const s=[];for(const r of e){const n=s.findIndex(o=>Eo(o,r));if(n>=0){s.splice(n,1,nd(s[n],r));continue}s.push(r)}return s}function Sa(e){return[...e].sort((s,r)=>{const n=os(s),o=os(r);return n&&o&&n!==o?n-o:0})}function Ca(e){return`${String((e==null?void 0:e.role)||"").toLowerCase()}:${as(e==null?void 0:e.content).slice(0,100)}`}function Ia(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>Eo(i,n));return o>=0?(r.splice(o,1),!1):!0})}function ad(e,s){const r=new Set(s.map(n=>Ca(n)));return e.filter(n=>!r.has(Ca(n)))}const od=60,id=200;function cd(e={}){return e.isCliLike?id:od}function ld(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function dd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let o=0;o<n.length;o+=1)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Ta(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function $o(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return dd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function ud(e){return{knownMessageCount:e.length,lastMessageSignature:$o(e[e.length-1])}}function md(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Ls([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Ls([...e.slice(0,n),...r])}case"full":default:return r}}const Aa=60;function bn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:p=!0}){var Q,xe;const x=a.useRef(new Map),b=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:A,sendData:u}=Ct(),h=Gs();zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=rt.useMemo(()=>ks(e),[e.status,e.connectionState]),l=a.useMemo(()=>Xl(e,s),[e,s]),j=cd({isCliLike:l.isCli||l.isAcp}),P=a.useRef(new Map),k=a.useCallback(W=>(P.current.has(W)||P.current.set(W,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:j}),P.current.get(W)),[j]),g=a.useCallback((W,ee)=>{const ne=k(W);P.current.set(W,{...ne,...ee}),N(oe=>oe+1)},[k]),[,N]=a.useState(0),v=e.tabKey,w=k(v),M=w.messages,T=w.hasMore,$=w.error,E=b.current.get(v),F=e.messages.filter(W=>!!(W!=null&&W._localId)),D=E?Ls([...E,...F]):e.messages;a.useEffect(()=>{w.visibleLiveCount>=j||g(v,{visibleLiveCount:j})},[j,w.visibleLiveCount,v,g]);const C=Math.max(0,D.length-w.visibleLiveCount),V=Rr(e),J=wr(e),I=e.sessionId||"",R=e.providerSessionId||I,[B,z]=a.useState(!1);a.useEffect(()=>{const W=l.targetEntry;J&&(!W||W.providerControls===void 0||W.controlValues===void 0)&&h(J,{minFreshMs:3e4}).catch(()=>{})},[J,l.isAcp,(Q=l.targetEntry)==null?void 0:Q.providerControls,(xe=l.targetEntry)==null?void 0:xe.controlValues,h]),a.useEffect(()=>{if(!J||!I||!u)return;const W=b.current.get(v)||[],ee=S.current.get(v),ne=ee&&ee.knownMessageCount?ee:ud(W),oe=`daemon:${J}:session:${I}`;return Ot.subscribe({sendData:u},J,{type:"subscribe",topic:"session.chat_tail",key:oe,params:{targetSessionId:I,historySessionId:R,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:Aa}}},te=>{const de=b.current.get(v)||[],se=md(de,te),pe=Math.max(se.length,Number(te.totalMessages||0));S.current.set(v,{knownMessageCount:pe,lastMessageSignature:typeof te.lastMessageSignature=="string"?te.lastMessageSignature:$o(se[se.length-1])}),Ta(de)!==Ta(se)&&(b.current.set(v,se),ss.record({interactionId:te.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:I,syncMode:te.syncMode,previousCount:de.length,nextCount:se.length}}),N(Ne=>Ne+1))})},[J,R,u,I,v]);const Z=a.useCallback(async()=>{if(B)return;const W=e.tabKey,ee=k(W);if(D.length>ee.visibleLiveCount){g(W,{visibleLiveCount:Math.min(D.length,ee.visibleLiveCount+Aa),error:null});return}z(!0),g(W,{error:null});try{const ne=wr(e);if(!ne){g(W,{hasMore:!1});return}const oe=wt(e),he=await A(ne,"chat_history",{agentType:oe,offset:ee.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),te=ld(he),de=te.messages||[];if(de.length>0){const se=k(W);g(W,{messages:[...de,...se.messages],offset:se.offset+de.length,hasMore:!!te.hasMore})}else g(W,{hasMore:!!te.hasMore})}catch(ne){const oe=(ne==null?void 0:ne.message)||"";oe.includes("P2P not available")||oe.includes("channel not open")||oe.includes("P2P not connected")||oe.includes("timeout")?g(W,{error:"Connection not ready — tap to retry"}):g(W,{hasMore:!1,error:"Failed to load history"})}finally{z(!1)}},[B,e,D.length,A,k,g]),{allMessages:fe,receivedAtMap:Pe}=a.useMemo(()=>{const W=C>0?D.slice(-w.visibleLiveCount):D;if(M.length===0){const he=Sa(Ls(W)),te={};return he.forEach((de,se)=>{const pe=`${e.tabKey}:${fs(de,se)}`;let ae=os(de)||x.current.get(pe)||0;ae||(ae=Date.now(),x.current.set(pe,ae)),te[fs(de,se)]=ae}),{allMessages:he,receivedAtMap:te}}const ee=ad(M,W),ne=Sa(Ls([...ee,...W])),oe={};return ne.forEach((he,te)=>{const de=`${e.tabKey}:${fs(he,te)}`;let se=os(he)||x.current.get(de)||0;se||(se=Date.now(),x.current.set(de,se)),oe[fs(he,te)]=se}),{allMessages:ne,receivedAtMap:oe}},[e.tabKey,C,M,D,w.visibleLiveCount]),ke=a.useMemo(()=>c.filter(W=>W.routeId===e.tabKey).sort((W,ee)=>W.timestamp-ee.timestamp),[c,e.tabKey]),ve=a.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&z(!1),e.status==="not_monitored")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ks,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(yo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gs,{size:14})," Open ",V," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,o,i,B,D.length,V,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(Do,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Xc,{messages:fe,actionLogs:ke,agentName:Vs(e)||V||"Agent",userName:d,isCliMode:l.isCli||l.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Pe,onLoadMore:Z,isLoadingMore:B,hasMoreHistory:T,hiddenLiveCount:C,loadError:$??void 0,emptyState:ve,scrollToBottomRequestNonce:f}),p&&!l.isCliTerminal&&(()=>{var W,ee;return t.jsx(Fl,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:l.providerType,displayLabel:l.displayLabel,controls:(W=l.targetEntry)==null?void 0:W.providerControls,controlValues:(ee=l.targetEntry)==null?void 0:ee.controlValues})})(),!l.isCliTerminal&&t.jsx(Vl,{contextKey:e.tabKey,panelLabel:V,isSending:n,onSend:r,isActive:p})]})}let Bo=rs;function Ko(){return Bo()}class pd{constructor(){lt(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let Wo=new pd;class fd{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let at=new fd;function xd(e){e.dashboardWS&&(Wo=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(Bo=e.useDaemonsHook)}function st(e){return Rr(e)}function is(e){return $n(e).join(" · ")}function Oo(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=as(s==null?void 0:s.content);return r||(e.title?e.title:is(e)||"No messages yet")}function Ho(e,s){const{isReconnecting:r,isConnecting:n}=ks(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function hd(e,s){const r=["Chat",...$n(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function qt(e){return Ho(e)||is(e)}function bd(e){return`${st(e)} · ${Oo(e)}`}function gd(e){const s=En(e)||wt(e);return`${st(e)} — ${et(s)}`}function yd(e){return Vs(e)||"CLI"}function Uo(e){return e.title||Vs(e)||e.routeId}function zo(e){return e?`Remote · ${st(e)||e.workspaceName||"Session"}`:"Remote"}function vd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var R;const{ides:c}=rs(),d=a.useRef(null),{sendCommand:m,sendData:f}=Ct(),[p,x]=a.useState(""),[b,S]=a.useState(!1),[A,u]=a.useState(1),h=a.useRef(!1),y=a.useRef(0),l=a.useRef(!1),j=a.useRef(""),P=a.useRef(null),k=a.useRef(!1),g=a.useRef(null),N=e.tabKey,v=e.sessionId||"",w=e.daemonId||((R=e.routeId)==null?void 0:R.split(":")[0])||e.routeId||"",M=c.find(B=>B.id===w&&B.type==="adhdev-daemon"),T=(M==null?void 0:M.terminalSizingMode)==="fit"?"fit":"measured",$=.6,E=1.15,F=()=>{if(typeof window>"u")return 1;const B=window.innerWidth||0;return B<=360?.68:B<=390?.74:B<=430?.82:B<=480?.9:1},D=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!1),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},C=()=>{var B,z;y.current=0,l.current=!1,j.current="",P.current=null,k.current=!1,g.current!==null&&(cancelAnimationFrame(g.current),g.current=null),S(!0),(z=(B=r.current)==null?void 0:B.reset)==null||z.call(B)},V=()=>{var z;if(g.current=null,!i)return;const B=j.current;B&&(j.current="",(z=r.current)==null||z.write(B))},J=B=>{B&&(j.current+=B,i&&g.current===null&&(g.current=requestAnimationFrame(V)))},I=(B,z=0,Z,fe)=>{var Pe,ke,ve,Q,xe;z>0&&y.current>=z||z===0&&l.current||(y.current=z,S(!0),typeof Z=="number"&&typeof fe=="number"&&Z>0&&fe>0&&((ke=(Pe=r.current)==null?void 0:Pe.resize)==null||ke.call(Pe,Z,fe)),(Q=(ve=r.current)==null?void 0:ve.reset)==null||Q.call(ve),B&&((xe=r.current)==null||xe.write(B)))};return a.useEffect(()=>{D()},[v]),a.useEffect(()=>{var z;if(!v)return;const B=((z=at.onRuntimeEvent)==null?void 0:z.call(at,v,Z=>{if(!(!Z||Z.sessionId!==v)){if(Z.type==="runtime_snapshot"){if(!i){P.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows};return}I(Z.text||"",Z.seq||0,Z.cols,Z.rows);return}if(Z.type==="session_output"){l.current=!0,typeof Z.seq=="number"&&(y.current=Math.max(y.current,Z.seq)),b||S(!0),typeof Z.data=="string"&&J(Z.data);return}if(Z.type==="session_cleared"){if(!i){k.current=!0,j.current="",P.current=null;return}C()}}}))||(()=>{});return()=>{B()}},[w,v,r,i,b]),a.useEffect(()=>{var z,Z,fe;if(!v)return;w&&((z=at.getState)==null?void 0:z.call(at,w))==="connected"&&(S(!0),(Z=at.requestRuntimeSnapshot)==null||Z.call(at,w,v).catch(()=>{}));const B=(fe=at.onStateChange)==null?void 0:fe.call(at,(Pe,ke)=>{var ve;Pe!==w||ke!=="connected"||(S(!0),(ve=at.requestRuntimeSnapshot)==null||ve.call(at,w,v).catch(()=>{}))});return()=>{B==null||B()}},[w,v,r]),a.useEffect(()=>{s&&D()},[s,N,r]),a.useEffect(()=>{x("")},[e.tabKey]),a.useEffect(()=>{const B=()=>{h.current||u(F())};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),a.useEffect(()=>{var z;if(!i){(z=d.current)==null||z.blur();return}k.current&&(k.current=!1,C());const B=P.current;B&&(P.current=null,I(B.text,B.seq,B.cols,B.rows)),j.current&&g.current===null&&(g.current=requestAnimationFrame(V)),requestAnimationFrame(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})},[i]),a.useEffect(()=>()=>{g.current!==null&&(cancelAnimationFrame(g.current),g.current=null)},[]),a.useEffect(()=>{const B=z=>{var fe;const Z=z.detail;Z!=null&&Z.sessionId&&Z.sessionId!==v||b&&((fe=r.current)==null||fe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[b,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.max($,Number((B-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{h.current=!0,u(B=>Math.min(E,Number((B+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(No,{ref:r,readOnly:!b||!i,sizingMode:T,onInput:B=>{b&&(f!=null&&f(w,{type:"pty_input",targetSessionId:v,data:B})||m(w,"pty_input",{targetSessionId:v,data:B}).catch(console.error))}})})}),!b&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${st(e)}...`,value:p,disabled:!b||!i||o,onChange:B=>x(B.target.value),onPaste:B=>{const z=B.clipboardData.getData("text");z&&x(Z=>Z+z),B.preventDefault()},onKeyDown:B=>{if(B.key!=="Enter")return;if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault();const z=p.trim();!b||!z||o||(x(""),n(z))},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const B=p.trim();!b||!B||o||(x(""),n(B))},disabled:!b||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function wd({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",o=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},d={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[o],borderBottom:c[o],color:d[o]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function jd({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!e||e.backend!=="xterm"||i)return null;const d=(r==null?void 0:r.trim())||"This machine",m=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[d," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:m,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Kn({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Mr,{size:n}):t.jsx(Kt,{size:n})})}function kd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Ht(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||kd(s==null?void 0:s.receivedAt)||0}function gn(e,s=0){return Ht(e)||e.lastUpdated||s||0}function Fo(e){return Ht(e)||e.lastUpdated||0}function kr(e,s,r=Fo){const n=r(s)-r(e);if(n!==0)return n;const o=(e.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function yn(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Nd(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!yn(e)&&!e.title.trim()}function Sd(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(yn(r))-Number(yn(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:kr(s,r)})[0]||null}function Lt(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,o=r.filter(c=>c.streamSource==="agent-stream"),i=Sd(o);return n?i&&Nd(n)?i:n:i||r[0]||null}function Ma({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function _a({conversation:e,isAttention:s,shortcutIndex:r,onClick:n}){const o=$n(e),i=Rn(Ht(e)),c=[...o,i].filter(Boolean);return t.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:Rr(e)}),(r||c.length>0)&&t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function Cd({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:p,onHideConversation:x,hiddenConversations:b=[],onShowConversation:S,onShowAllHidden:A,onResetPanelsToMain:u,inboxOpen:h,onInboxOpenChange:y,hiddenOpen:l,onHiddenOpenChange:j,onOpenNewSession:P,actionShortcuts:k}){const{ides:g,p2pStates:N={}}=rs(),v=!!e&&Ye(e)&&!Ve(e),w=!!e&&Ve(e),M=m||(e?Ro(e)?"terminal":"chat":null),[T,$]=a.useState(!1),E=a.useRef(null),F=a.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",V=g.filter(W=>W.type==="adhdev-daemon"),J=a.useMemo(()=>Fs(g),[g]),I=Object.values(N),R=I.filter(W=>W==="connected").length,B=I.filter(W=>W==="connecting"||W==="new"||W==="checking").length,Z=r!=="connected"||V.length===0?null:B>0&&R===0?"P2P connecting...":R>0&&s===0?"Waiting for IDE...":null,fe=a.useMemo(()=>o.filter(W=>!il(W,o,J)),[o,J]),Pe=a.useMemo(()=>fe.filter(W=>Os(W,J).requiresAction).sort(kr),[fe,J]),ke=a.useMemo(()=>fe.filter(W=>{const ee=(e==null?void 0:e.tabKey)===W.tabKey;return Os(W,J,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ee}).unread}).sort(kr),[e,fe,J]),ve=a.useMemo(()=>[...Pe,...ke].slice(0,9),[Pe,ke]),Q=Pe.length+ke.length;a.useEffect(()=>{if(!h)return;const W=ee=>{var ne;(ne=E.current)!=null&&ne.contains(ee.target)||y(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[h,y]),a.useEffect(()=>{if(!l)return;const W=ee=>{var ne;(ne=F.current)!=null&&ne.contains(ee.target)||j(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[l,j]),a.useEffect(()=>{if(!l&&!h)return;const W=ee=>{if(!ee.altKey)return;const ne=ee.code.match(/^Digit([1-9])$/);if(!ne)return;const oe=Number(ne[1])-1,he=l?b[oe]:void 0,te=h?ve[oe]:void 0,de=he||te;if(de){if(ee.preventDefault(),ee.stopPropagation(),he){S==null||S(he),j(!1);return}p==null||p(de),y(!1)}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[b,l,h,ve,j,y,p,S]);const xe=W=>{if(!W)return;const ee=o.find(ne=>ne.tabKey===W);ee&&(x==null||x(ee))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Kt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?st(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:C}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:C}}),Z&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Z]}),P&&t.jsx("button",{type:"button",onClick:P,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Ac,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(v||w||!Ve(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:is(e)||st(e),children:st(e)}),(v||w)&&d&&t.jsxs(t.Fragment,{children:[v&&f&&M&&t.jsx(Kn,{mode:M,onChange:f,compact:!0}),t.jsx("button",{onClick:()=>d(e),className:"btn btn-secondary btn-sm",title:w?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})})]}),!Ve(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Mn,{size:14})}),!v&&!Ve(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(kt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[t.jsxs("div",{className:`dashboard-header-hidden${T?" is-drop-target":""}`,ref:F,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),$(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",$(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||$(!1)},onDrop:W=>{const ee=W.dataTransfer.getData("text/tab-key");W.preventDefault(),$(!1),xe(ee)},children:[t.jsxs("button",{type:"button",onClick:()=>j(!l),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(vo,{size:16}),b.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:b.length})]}),l&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Ma,{value:k==null?void 0:k.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),b.length>0&&A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{A(),j(!1)},children:"Restore all"})]})]}),e&&x&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>x(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ma,{value:k==null?void 0:k.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:st(e)})]}),b.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:b.map(W=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(W),j(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:st(W)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[b.indexOf(W)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",b.indexOf(W)+1]}):null,is(W)]})]},W.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>y(!h),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(_r,{size:16}),Q>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:Q})]}),h&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Pe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Pe.map(W=>t.jsx(_a,{conversation:W,isAttention:!0,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),ke.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),ke.map(W=>t.jsx(_a,{conversation:W,shortcutIndex:ve.indexOf(W)>=0?ve.indexOf(W)+1:void 0,onClick:()=>{p==null||p(W),y(!1)}},W.tabKey))]}),Q===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nr(e){return e?"Resume saved history":"Start fresh"}function Wn(e){return e?"Resuming saved history…":"Starting fresh…"}function Vo(){return"Start fresh"}function Id(){return"Recover hosted runtime"}function Go(){return"Open saved history"}function Td(){return"Saved History"}function Ad(){return"No saved history found yet."}function Md(){return"Refresh saved history"}function _d(){return"Refreshing saved history…"}function Yt(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function Xt(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Jt(e){return e==="start-fresh"?"Start fresh":"Restart"}function Zt(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qo(e){return`Resume saved history with ${e}?`}function Yo(){return"Review or change the target workspace before resuming saved history."}function Pd(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function On({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:p,onResumeSavedSession:x}){var y;const b=s.find(l=>l.id===e.routeId),S=(b==null?void 0:b.chats)||[],A=(y=b==null?void 0:b.activeChat)==null?void 0:y.id,u=Ye(e)&&!Ve(e),h=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[t.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[t.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?Td():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:gd(e)})]}),t.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?t.jsx(t.Fragment,{children:o.map(l=>{const j=e.providerSessionId===l.providerSessionId,P=j||!l.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{P||!x||x(l)},disabled:P,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${j?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${P?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${j?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Pd(l.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:j?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>t.jsxs("div",{onClick:()=>{f(e.routeId,l.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${A===l.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${A===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[l.id.substring(0,12),"..."]}),A===l.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},l.id)),(u&&!i&&o.length===0||!u&&S.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(Rc,{size:32})}),t.jsx("div",{className:"text-[13px]",children:u?Ad():"No recent chat sessions found."})]}),u&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:_d()})})]}),t.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:t.jsx("button",{onClick:p,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(js,{size:13})," ",u?Md():"Refresh History"]})})})]})]});return typeof document>"u"?h:Bs.createPortal(h,document.body)}const Pa={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Xo({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const o=Pa[n.type]||Pa.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(vt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:o.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Rd=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ld(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Dd(e){return e.sessionId||e.instanceId||e.agentType}function Yr(e,s){return e||s}function Ra(e,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of e[o]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((o,i)=>o.timestamp-i.timestamp)}function Jo(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=jt(r,{fallbackId:r.id}));return s}function Zo(e,s={}){var n,o;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((o=s.machineNames)==null?void 0:o[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Hn(e,s,r={}){return Ed(e,s,Zo(e,r))}function Ed(e,s,r={}){var b,S,A,u,h,y;const n=[],o=r.machineName,i=r.connectionState,c=Ld(e),d=et(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(l=>{var j,P;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||et(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((j=l.activeChat)==null?void 0:j.messages)||[],activeModal:((P=l.activeChat)==null?void 0:P.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=Rd(e),p=e.activeChat||{title:""},x=p.title&&String(p.title).trim()?String(p.title).trim():"";if(f){const l=e.sessionId||e.instanceId,j=ba(e.type),P=(b=e.activeChat)==null?void 0:b.activeModal,k=P&&Array.isArray(P.buttons)&&P.buttons.length>0,g=bt((S=e.activeChat)==null?void 0:S.status,{activeModal:(A=e.activeChat)==null?void 0:A.activeModal})||bt((h=(u=e.agents)==null?void 0:u[0])==null?void 0:h.status)||"idle",N=e.activeChat||{title:"",messages:[]};let v=N.title&&String(N.title).trim()?String(N.title).trim():"";const w=(y=e.activeChat)==null?void 0:y.id,M=e.chats;if(w&&Array.isArray(M)&&M.length>0){const C=M.find(V=>V.id===w||V.id&&String(V.id)===String(w));C!=null&&C.title&&String(C.title).trim()&&(v=String(C.title).trim())}const T=(Ye(e)||Ve(e),e.type),$=(Ye(e)||Ve(e))&&ga(v,j,T)?"":v,E=N.messages||[],F=Ra(s,[e.id,l]),D=Ia(E,F);n.push({routeId:e.id,sessionId:l,providerSessionId:e.providerSessionId,nativeSessionId:l,transport:e.transport,daemonId:e.daemonId||void 0,mode:Ye(e)?e.mode||"terminal":"chat",agentName:j,agentType:T,status:g,title:$,messages:[...E,...D],resume:e.resume,hostIdeType:!Ye(e)&&!Ve(e)?e.type:void 0,workspaceName:c,displayPrimary:c||$||(Ye(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:k?P.buttons:void 0,modalMessage:k?P.message:void 0,streamSource:"native",tabKey:Yr(l,e.id),machineName:o,connectionState:i})}if(f&&(Ye(e)||Ve(e)))return n;for(const l of m){const j=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,P=xl(l),k=Dd(l),g=`${e.id}:${k}`,N=l.title&&String(l.title).trim()||"",v=ga(N,l.agentName,l.agentType)?"":N,w=l.messages||[],M=Ra(s,[g,l.sessionId,l.instanceId]),T=Ia(w,M);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||w.length>0||T.length>0||j||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(P))&&n.push({routeId:e.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:l.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:P,title:v,messages:[...w,...T],hostIdeType:e.type,workspaceName:c,displayPrimary:c||x||v||d,displaySecondary:`${d} · ${l.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||e.lastUpdated,modalButtons:j?l.activeModal.buttons:void 0,modalMessage:j?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yr(l.sessionId||l.instanceId,g),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,mode:"chat",agentName:ba(e.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Yr(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function $d(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function Bd(e,s){const r=$d(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Qo=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],ei=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],ti=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Kd=Qo,Wd=ei,Od=ti;function cs(...e){return nc(ac(e))}function Hd({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:cs("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&t.jsx("div",{className:"flex gap-2",children:o})]})}function si({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Hd,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:cs("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Mt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:cs("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",o),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function ri({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:cs("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Ud={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},zd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Fd({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:cs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ud[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:zd[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Vd={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Gd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function qd({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:cs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Vd[e],r),children:[t.jsx("span",{className:cs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Gd[e])}),n]})}const vn="adhdev:themechange";function Yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ms(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ps(e){return e==="system"?Yd():e}function ni(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function xr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(vn,{detail:{preference:e,theme:s}}))}function Xd(){const e=ms(),s=ps(e);ni(s),xr(e,s)}function Un(){const[e,s]=a.useState(ms),[r,n]=a.useState(()=>ps(ms()));a.useEffect(()=>{ni(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=m=>{if(e==="system"){const f=m.matches?"light":"dark";n(f),xr("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[e]),a.useEffect(()=>{const c=m=>{const f=m.detail||{},p=f.preference,x=f.theme;s(p==="dark"||p==="light"||p==="system"?p:ms()),n(x==="dark"||x==="light"?x:ps(ms()))},d=m=>{if(m.key!=="theme")return;const f=ms(),p=ps(f);s(f),n(p)};return window.addEventListener(vn,c),window.addEventListener("storage",d),()=>{window.removeEventListener(vn,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=ps(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}xr(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",m=ps(d);n(m);try{localStorage.setItem("theme",d)}catch{}return xr(d,m),d})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const La={dark:"Dark",light:"Light",system:"System"};function Jd({collapsed:e}){const{preference:s,cycleTheme:r}=Un(),n=s==="dark"?t.jsx(Dc,{size:16}):s==="light"?t.jsx(Lc,{size:16}):t.jsx(Ec,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${La[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:La[s]})]})}function Gt({label:e,description:s,checked:r,disabled:n,onChange:o,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>o(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Zd({onPrefChange:e}){const[s,r]=Sl(),n=(o,i)=>{r({[o]:i}),e==null||e(o,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_r,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($c,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ks,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Sr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Qd(e,s){const r=Sr(e),n=Sr(s);if(!r||!n)return e.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function ai(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ds(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Qd(r,s)>=0)return!1;const n=Sr(r),o=Sr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function eu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xr(e,s){return e instanceof Error?e.message:s}function tu({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(ru,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Da({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:o,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Bs.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:o,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function su(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Kd,...Wd,...Od].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function ru({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var F,D;const[i,c]=a.useState("idle"),[d,m]=a.useState(""),[f,p]=a.useState(null),[x,b]=a.useState("idle"),[S,A]=a.useState(""),u=e.version||null,h=((F=e.machine)==null?void 0:F.platform)||((D=e.system)==null?void 0:D.platform)||"",y=jt(e,{fallbackId:e.id}),l=h==="win32"?"🪟":h==="darwin"?"🍎":"🐧",j=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),P=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),g=e.p2p,N=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const C=eu(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),m(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),m(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(C.error||"Upgrade failed"))}catch(C){c("error"),m(Xr(C,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){b("loading");try{await n(e.id),b("done"),A("Machine disconnected.")}catch(C){b("error"),A(Xr(C,"Failed to disconnect"))}}},w=async()=>{if(p(null),!!o){b("loading");try{await o(e.id),b("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){b("error"),A(Xr(C,"Failed to revoke token"))}}},M="0.8.53",T=ai(e,M),$=Ds(e,M),E=j.length+P.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:l}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),u&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!T&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&t.jsx("button",{onClick:N,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${M}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${$?"↑ Update now":`↑ Update${` to v${M}`}`}`}),n&&t.jsx("button",{onClick:()=>p("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&t.jsx("button",{onClick:()=>p("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(qd,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&E>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(C=>{const V=su(C.type),J=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:V.icon}),t.jsx("span",{children:V.name}),J!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${J?"bg-green-400":"animate-pulse"}`,style:J?void 0:{background:"var(--status-warning)"},title:J?"CDP connected":"CDP connecting..."})]},C.id)}),P.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&t.jsx(Da,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
32
|
+
|
|
33
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
|
+
|
|
35
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>p(null)}),f==="revoke"&&t.jsx(Da,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
36
|
+
|
|
37
|
+
This will:
|
|
38
|
+
• Immediately disconnect the machine
|
|
39
|
+
• Delete the machine registration
|
|
40
|
+
• Require restarting ADHDev on that machine
|
|
41
|
+
|
|
42
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>p(null)})]})}const nu=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function au(){const{preference:e,setPreference:s}=Un();return t.jsx("div",{className:"flex gap-2",children:nu.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function ou(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function iu(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Jr(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ea(e){const{r:s,g:r,b:n}=iu(e);return .2126*Jr(s)+.7152*Jr(r)+.0722*Jr(n)}function $a(e,s){const r=Ea(e),n=Ea(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function oi(e){const s=ou(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return $a(s,r)>=$a(s,n)?r:n}const wn={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},jn={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},cu=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],ii="adhdev-chat-theme",ci="adhdev-chat-theme-custom";function hr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ii)||"ember"}catch{return"ember"}}function _t(e){try{const s=localStorage.getItem(ci);if(s){const r=JSON.parse(s);return{...e==="dark"?wn:jn,...r[e]}}}catch{}return e==="dark"?wn:jn}function sr(e,s){try{localStorage.setItem(ci,JSON.stringify({dark:e,light:s}))}catch{}}function Nt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function Cr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),o=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const lu={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Es(e,s){var o;const r=(o=lu[e])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Cr(r,24)),n.style.setProperty("--accent-on-primary",oi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Cr(r,18)})`),n.style.setProperty("--border-accent",Nt(r,.35)),n.style.setProperty("--nav-active-bg",Nt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Nt(r,.06)}`)}function Qt(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Nt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Nt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Nt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Nt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Nt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Cr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",oi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Cr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Nt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Nt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Nt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Nt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function zn(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function du(e){try{localStorage.setItem(ii,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function uu(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=hr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=es()?"dark":"light";Qt(_t(s))}else zn(),Es(e,es()?"dark":"light")}function es(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ht({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Is({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function mu({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>_t(r));a.useEffect(()=>{o(_t(r))},[r]);const i=a.useCallback((c,d)=>{o(m=>{const f={...m,[c]:d},x=_t(r==="dark"?"light":"dark");return r==="dark"?sr(f,x):sr(x,f),Qt(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Is,{title:"App Background",children:[t.jsx(ht,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(ht,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(ht,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Is,{title:"App Text",children:[t.jsx(ht,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(ht,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(ht,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Is,{title:"Borders & Accent",children:[t.jsx(ht,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(ht,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(ht,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Is,{title:"Chat Bubbles",children:[t.jsx(ht,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(ht,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(ht,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(ht,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Is,{title:"Chat Layout",children:[t.jsx(ht,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(ht,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(ht,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?wn:jn,m=_t(e?"light":"dark");e?sr(c,m):sr(m,c),o(c),Qt(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function pu(){const[e,s]=a.useState(hr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>_t("dark"));a.useEffect(()=>{n(es());const m=new MutationObserver(()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const x=es();n(x);const b=hr();b==="custom"?Qt(_t(x?"dark":"light")):Es(b,x?"dark":"light")};return f.addEventListener("change",p),()=>{m.disconnect(),f.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Qt(_t(r?"dark":"light")):(zn(),Es(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=m=>{s(m),du(m)},d=[...cu,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(m=>{const f=e===m.id,p=r?m.preview.dark:m.preview.light,x=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:p.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.userBubble,color:x},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(mu,{dark:r,onColorsChange:m=>i(m)})]})}const li="adhdev_mobileDashboardMode_v1";function di(){try{return localStorage.getItem(li)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fu(e){try{localStorage.setItem(li,e)}catch{}}function xu(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(di()==="chat")},[]),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),fu(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function hu(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function bu(e,s){const{sendData:r}=Ct(),{injectEntries:n,getIdes:o}=vr(),i=Array.from(new Set(e.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const d=c.map(m=>Ot.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const p=o().find(b=>b.id===m),x=hu(p,m,f);n([x])}));return()=>{d.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const gu=4e3;function ui(e,s){const{sendData:r}=Ct(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!e){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const m=Ot.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{d&&(clearTimeout(d),d=null),o(f.diagnostics),c(!1)});return m.initialSendAccepted?d=setTimeout(()=>{c(!1)},gu):c(!1),()=>{d&&clearTimeout(d),m()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:o}}function yu(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function mi(e){const{sendData:s}=Ct(),[r,n]=a.useState({});return a.useEffect(()=>{const o=yu(e);if(!o||!e.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),ss.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const pi="adhdev_hiddenTabs";function vu(){try{const e=localStorage.getItem(pi);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ds(e){try{localStorage.setItem(pi,JSON.stringify([...e]))}catch{}}function wu(){const[e,s]=a.useState(vu),r=a.useCallback(f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),ds(x),x})},[]),n=a.useCallback(f=>{s(p=>{if(p.has(f))return p;const x=new Set(p);return x.add(f),ds(x),x})},[]),o=a.useCallback(f=>{s(p=>{if(!p.has(f))return p;const x=new Set(p);return x.delete(f),ds(x),x})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const p=new Set;return ds(p),p})},[]),c=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.add(S);return ds(b),b})},[]),d=a.useCallback((f,p)=>{s(x=>{const b=new Set(x);for(const S of p)b.delete(S);return ds(b),b})},[]),m=a.useCallback(f=>e.has(f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:m}}function ju({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Il()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:Uo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Al(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const m=Date.now(),f={};for(const[p,x]of Object.entries(d))m-x<5e3&&(f[p]=x);return Object.keys(f).length===Object.keys(d).length?d:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const m=d.filter(f=>f.timestamp>c).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[n]),null}function ku(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const o=r.get(n.id);if(!o){r.set(n.id,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function rr(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Nu(e,s){const r=Date.now();return e.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Su(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const o of e.childSessions||[]){const i=o.id||o.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Cu(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function Iu(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Tu(e){const s=Iu(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=as(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Au({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const g=ku(e);return rr(i.current,g)?i.current:(i.current=g,g)},[e]),p=a.useMemo(()=>Jo(e),[e]),x=a.useRef(new Map),b=a.useRef(new Map),S=a.useMemo(()=>{const g=new Map,N=[];for(const T of f){const{connectionState:$="new",machineName:E}=Zo(T,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),F=Su(T,r),D=x.current.get(T.id);if(D&&D.ide===T&&D.connectionState===$&&D.machineName===E&&Cu(D.localRefs,F)){g.set(T.id,D),N.push(...D.conversations);continue}const C=Hn(T,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),V={ide:T,connectionState:$,machineName:E,localRefs:F,conversations:C};g.set(T.id,V),N.push(...C)}x.current=g;const v=new Map,w=T=>{const $=Tu(T),E=b.current.get(T.tabKey);if(E&&E.signature===$)return v.set(T.tabKey,E),E.timestamp;const F={signature:$,timestamp:Fo(T)||(E==null?void 0:E.timestamp)||0};return v.set(T.tabKey,F),F.timestamp},M=[...N].sort((T,$)=>kr(T,$,w));return b.current=v,M},[f,r,s,p]),A=a.useMemo(()=>{const g=Nu(S,n);return rr(c.current,g)?c.current:(c.current=g,g)},[S,n]),u=a.useMemo(()=>{const g=new Map,N=Array.from(new Set(A.map(v=>v.routeId)));for(const v of N){const w=Lt(A,v);w&&g.set(v,w)}return g},[A]),h=a.useMemo(()=>{const g=new Map;for(const N of A)if(N.sessionId&&g.set(N.sessionId,N),N.streamSource==="native"&&N.sessionId){const v=u.get(N.routeId);v&&g.set(N.sessionId,v)}return g},[A,u]),y=a.useMemo(()=>{const g=new Map;for(const N of A)N.sessionId&&g.set(N.sessionId,N),g.set(N.routeId,u.get(N.routeId)||N),g.set(N.tabKey,N);return g},[A,u]),l=a.useCallback(g=>{if(g)return h.get(g)},[h]),j=a.useCallback(g=>{if(g)return y.get(g)},[y]),P=a.useMemo(()=>{const g=A.filter(N=>!o.has(N.tabKey));return rr(d.current,g)?d.current:(d.current=g,g)},[A,o]),k=a.useMemo(()=>{const g=P.map(N=>N.tabKey);return rr(m.current,g)?m.current:(m.current=g,g)},[P]);return{chatIdes:f,conversations:A,visibleConversations:P,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:j}}function Mu({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var d;return!e||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(d=>{const m=new URLSearchParams(d);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function _u({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{tt.setIdes(e)},[e]),a.useEffect(()=>{tt.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=tt.onToast(m=>{r(p=>p.some(b=>b.message===m.message&&m.timestamp-b.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const f=m.duration||5e3;setTimeout(()=>r(p=>p.filter(x=>x.id!==m.id)),f)}),c=tt.onSystemMessage((m,f)=>{var S,A;const p=o(m),x=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),b=!!(p&&(p.status==="waiting_approval"||(A=p.modalButtons)!=null&&A.length||p.modalMessage));x&&b||n(u=>({...u,[m]:[...u[m]||[],f]}))}),d=tt.onClearSystemMessage((m,f)=>{n(p=>{var x;return(x=p[m])!=null&&x.length?{...p,[m]:p[m].filter(b=>{var S;return!(b.role==="system"&&((S=b._localId)!=null&&S.startsWith(f)))})}:p})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=Wo.on("status_event",c=>{tt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var h;const m=d.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const f=m.targetSessionId||m.targetKey||m.daemonId,p=o(f),x=(p==null?void 0:p.routeId)||m.daemonId;if(!x)return;const b=Number(m.buttonIndex),S=m.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[b])||"Approve",A=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(x,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(b)&&{buttonIndex:b},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var d;return(d=navigator.serviceWorker)==null?void 0:d.removeEventListener("message",i)}},[o,s])}const Pu="adhdev_dashboardLayout_v1",Ru="adhdev_dashboardDockview_v1",Lu="adhdev_dashboardDockviewHiddenRestore_v1",Ts={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Fn(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function fi(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function xi(e){return`${Pu}:${e}`}function Du(e){const s=xi(e);return Fn(s,null)}function Eu(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=xi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function hi(e){return`${Ru}:${e}`}function $u(e){const s=hi(e);return Fn(s,null)}function Bu(e,s){try{const r=hi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function bi(e){return`${Lu}:${e}`}function Ku(e){const s=bi(e);return Fn(s,{})}function Wu(e,s){try{const r=bi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ou(){return{groupAssignments:[...Ts.groupAssignments],focusedGroup:Ts.focusedGroup,groupActiveTabIds:{...Ts.groupActiveTabIds},groupTabOrders:{...Ts.groupTabOrders},groupSizes:[...Ts.groupSizes]}}function Hu(){const[e]=a.useState(()=>fi(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,m]=a.useState({}),[f,p]=a.useState([]),[x,b]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,A]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const h=Du(e)??Ou();r(new Map(h.groupAssignments)),o(h.focusedGroup),c(h.groupActiveTabIds),m(h.groupTabOrders),p(h.groupSizes),A(!0)},[S,e]);return a.useEffect(()=>{S&&Eu(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,e,s,n,i,d,f]),a.useEffect(()=>{const h=window.matchMedia("(max-width: 767px)"),y=l=>b(l.matches);return h.addEventListener("change",y),()=>h.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:m,groupSizes:f,setGroupSizes:p,isMobile:x,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function Uu(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function zu({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:m,historyModalOpen:f,activeConv:p,isRefreshingHistory:x,ides:b,handleRefreshHistory:S}){const A=a.useRef(!1),u=a.useRef(!1),h=a.useRef(null),y=a.useRef(!1);a.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!o){i();return}const l=r(e);if(!l)return;const j=n.get(l.tabKey)??0;c(P=>({...P,[j]:l.tabKey})),d(j),A.current=!0,u.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),m(P=>{const k=new URLSearchParams(P);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,o,i,c,d,m]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!e){i(),u.current=!0;return}if(A.current){u.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!f){y.current=!1;return}if(!p||y.current||x)return;const l=b.find(j=>j.id===p.routeId);l&&(!l.chats||l.chats.length===0||Uu(l.chats,p))&&(y.current=!0,S())},[f,p,x,b,S]),a.useEffect(()=>{if(!p)return;let l=null,j=0,P=-1,k=0;const g=()=>{l=null;const N=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(w=>w.offsetParent!==null);if(N.length===0){j<18&&(j+=1,l=requestAnimationFrame(g));return}let v=0;for(const w of N)w.scrollTop=w.scrollHeight,v+=w.scrollHeight;v===P?k+=1:(k=0,P=v),j+=1,!(k>=2||j>=18)&&(l=requestAnimationFrame(g))};return l=requestAnimationFrame(g),()=>{l!=null&&cancelAnimationFrame(l)}},[p==null?void 0:p.tabKey])}function Fu({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[m,f]=a.useState(null),[p,x]=a.useState(null),b=a.useMemo(()=>{if(e||!n)return null;const y=d(n);return y&&!Ye(y)&&!Ve(y)?y:null},[e,n,d]),S=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const l=m!=null&&m.tabKey?i.find(j=>j.tabKey===m.tabKey):o?i.find(j=>j.tabKey===o):null;return(l==null?void 0:l.routeId)===y?l:Lt(i,y)},[i,m,o]),A=a.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);a.useEffect(()=>{b&&(f({routeId:b.routeId,tabKey:wa(b)}),x(b),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,b]);const u=a.useCallback(y=>{y&&(f({routeId:y.routeId,tabKey:wa(y)}),x(y))},[]),h=a.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:A,remoteDialogActiveConv:p,setRemoteDialogActiveConv:x,openRemoteDialog:u,closeRemoteDialog:h}}function hs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Ye(e)||Ve(e)?{agentType:wt(e)}:e.streamSource==="agent-stream"?{agentType:wt(e)}:s}function Us(e){return e?wr(e):""}function As(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Zr(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ba({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,m]=a.useState(!1),[f,p]=a.useState(!1),x=a.useCallback(async u=>{try{await e("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),b=a.useCallback(async(u,h)=>{try{const y=u||(s==null?void 0:s.daemonId)||"",l=await e(y,"switch_chat",{id:h,sessionId:h,...hs(s)}),j=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||j==="switched"||j==="switched-by-title")return;j===!1||j==="not_found"?As(o,"⚠️ Session tab not found — try refreshing history"):typeof j=="string"&&j.startsWith("error:")?As(o,`⚠️ Switch error: ${j}`):As(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),As(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,o]),S=a.useCallback(async()=>{if(!(!s||d)){m(!0);try{const u=Us(s);await e(u,"new_chat",{...hs(s)}),c(h=>({...h,[s.tabKey]:Date.now()})),i(h=>({...h,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{m(!1)}}},[s,d,e,c,i]),A=a.useCallback(async()=>{var u,h;if(!(!s||f)){p(!0);try{const y=Us(s),l=async()=>e(y,"list_chats",{forceExpand:!0,...hs(s)});let j=await l(),P=(j==null?void 0:j.chats)||((u=j==null?void 0:j.result)==null?void 0:u.chats);Zr(P,s)&&(await new Promise(k=>setTimeout(k,450)),j=await l(),P=(j==null?void 0:j.chats)||((h=j==null?void 0:j.result)==null?void 0:h.chats)),j!=null&&j.success&&Array.isArray(P)&&(n(s.routeId,P),Zr(P,s)&&!Zr(r,s)&&As(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,f,e,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:x,handleSwitchSession:b,handleNewChat:S,handleRefreshHistory:A}}function Vu(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Gu(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Ka(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===e[Number(o)])}function nr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of e)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const o={};n.forEach((c,d)=>{o[c]=d}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,d]of e){if(!r.has(c)||d<=0)continue;const m=o[d];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Wa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function qu(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(o=>o<e)??s[0];return r[n]??0}function Yu(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,d)=>c+d,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function Oa(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ha(e){return Array(e).fill(100/e)}function Xu({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:m,visibleTabKeys:f}){const p=a.useRef(null),x=a.useMemo(()=>nr(e,f),[e,f]),b=x.assignments,S=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),A=S>1,u=a.useCallback((k,g)=>{s(N=>{const v=new Map(nr(N,f).assignments);return g===0?v.delete(k):v.set(k,g),v}),n(N=>({...N,[g]:k})),r(g)},[s,f,n,r]),h=a.useCallback(k=>{s(g=>{const N=nr(g,f).assignments,v=new Map;for(const[w,M]of N)M!==k&&(M>k?v.set(w,M-1):v.set(w,M));return v}),c(g=>{if(g.length<=1)return[];const N=[...g];N.splice(k,1);const v=N.reduce((w,M)=>w+M,0);return v>0?N.map(w=>w/v*100):[]}),r(0)},[s,f,c,r]),y=a.useCallback((k,g)=>{g.preventDefault();const N=p.current;if(!N)return;const v=g.clientX,w=N.offsetWidth,M=i.length===S?[...i]:Ha(S),T=E=>{const D=(E.clientX-v)/w*100,C=[...M];C[k]=Math.max(15,M[k]+D),C[k+1]=Math.max(15,M[k+1]-D),c(C)},$=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",$),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",$)},[i,S,c]),l=a.useCallback((k,g,N)=>{if(S>=4)return;const v=N==="left"?g:g+1;s(w=>{const M=nr(w,f).assignments,T=new Map;for(const $ of m){const E=M.get($.tabKey)??0,F=E>=v?E+1:E;F>0&&T.set($.tabKey,F)}return v>0&&T.set(k,v),T}),c(w=>{const M=w.length===S?[...w]:Ha(S),T=M[g]??100/S,$=Math.max(15,T/2),E=Math.max(15,T/2),F=[...M];F[g]=$,F.splice(v,0,E);const D=F.reduce((C,V)=>C+V,0);return F.map(C=>C/D*100)}),n(w=>{const M=Oa(w,v);return M[v]=k,M}),o(w=>{const M=Oa(w,v);return M[v]=[k],M}),r(v)},[S,s,f,m,c,n,o,r]);a.useEffect(()=>{Vu(e,b)||s(b)},[e,b,s]),a.useEffect(()=>{const{mapping:k,usedGroups:g}=x;n(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),o(N=>{const v=Wa(N,k);return Ka(N,v)?N:v}),r(N=>{const v=d?0:qu(N,g,k);return N===v?N:v}),c(N=>{const v=d?[]:Yu(N,g,x.groupCount);return Gu(N,v)?N:v})},[x,d,n,o,r,c]);const j=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const g of m){const N=b.get(g.tabKey)??0,v=Math.min(N,S-1);k[v].push(g)}return k},[m,b,S]),P=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:b,numGroups:S,isSplitMode:A,groupedConvs:j,moveTabToGroup:u,closeGroup:h,handleResizeStart:y,splitTabRelative:l,clearAllSplits:P}}function Ju({ides:e,sendDaemonCommand:s}){const r="0.8.53",n=a.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:ai(p,r)).sort((p,x)=>Number(Ds(x,r))-Number(Ds(p,r))),[r,e]),o=a.useMemo(()=>n.some(p=>Ds(p,r)),[r,n]),[i,c]=a.useState(!1),[d,m]=a.useState({}),f=a.useCallback(async p=>{var x,b;m(S=>({...S,[p]:"upgrading"}));try{const S=await s(p,"daemon_upgrade",{});(x=S==null?void 0:S.result)!=null&&x.upgraded||(b=S==null?void 0:S.result)!=null&&b.success?m(A=>({...A,[p]:"done"})):m(A=>({...A,[p]:"error"}))}catch{m(S=>({...S,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Ua(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Vn(e){return e instanceof Error?e.message:String(e||"")}function za(e){const s=Vn(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Fa(e,s){const r=Vn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Lr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,m]=a.useState(!1),f=a.useRef(!1),p=a.useRef(null),x=a.useCallback(async u=>{if(!s)return;const h=u.trim();if(!h||f.current)return;const y=s.tabKey,l=Date.now(),j=p.current;if(j&&j.tabKey===y&&j.message===h&&l-j.timestamp<2e3)return;f.current=!0,m(!0),p.current={tabKey:y,message:h,timestamp:l};const P=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:l,_localId:P},g=!(Ye(s)||Ve(s));g&&r(N=>({...N,[y]:[...N[y]||[],k]}));try{const N=Us(s);if(!N)return;const v=await e(N,"send_chat",{message:h,...hs(s)}),w=Ua(v);if(g&&(w!=null&&w.deduplicated||(w==null?void 0:w.sent)===!1)){r(M=>({...M,[y]:(M[y]||[]).filter(T=>T._localId!==P)}));return}if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Send failed");setTimeout(()=>{const M=Date.now()-6e4;r(T=>{const $=T[y];if(!$)return T;const E=$.filter(F=>F.timestamp>M);return E.length===$.length?T:{...T,[y]:E}})},6e4)}catch(N){const v=Vn(N);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",N),g&&r(w=>({...w,[y]:(w[y]||[]).filter(M=>M._localId!==P)}))}finally{f.current=!1,m(!1)}},[s,e,r]),b=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,e]),S=a.useCallback(async u=>{if(s)try{const y=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),P=Us(s);if(!P)return;const k=await e(P,"resolve_action",{button:u,action:j?"approve":"reject",...y>=0&&{buttonIndex:y},...hs(s)}),g=Ua(k);g.success||n(N=>[...N,{routeId:s.tabKey,text:Fa(u,g==null?void 0:g.error),timestamp:Date.now()}])}catch(h){za(h)||console.error("[ModalButton] Error:",h),n(y=>[...y,{routeId:s.tabKey,text:za(h)?Fa(u,h):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,e,n]),A=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:x,handleRelaunch:b,handleModalButton:S,handleFocusAgent:A}}const Gn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u=!0}){const h=mi(s),y=h.status||h.modalMessage||h.modalButtons?{...s,...h.status?{status:h.status}:{},...h.modalMessage!==void 0?{modalMessage:h.modalMessage}:{},...h.modalButtons!==void 0?{modalButtons:h.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Io,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ns,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:d,children:"Relaunch with CDP"})]})}):null,y.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(vd,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})})]}):t.jsx(bn,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:x,actionLogs:b,userName:S,scrollToBottomRequestNonce:A,isInputActive:u})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Zu({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:m,onOpenNativeConversation:f,onOpenMachine:p,onOpenHistory:x,onOpenRemote:b,onHideConversation:S,onStopCli:A,cliViewMode:u,onSetCliViewMode:h,handleSendChat:y,handleFocusAgent:l,handleModalButton:j,handleRelaunch:P}){const k=a.useRef(null),g=Ye(e)&&!s,N=g&&u==="terminal",v=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${v} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:st(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Do,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(e),onOpenMachine:()=>p(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[g&&u&&t.jsx(Kn,{mode:u,onChange:h,compact:!0}),g&&A&&t.jsx("button",{onClick:()=>{A(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:t.jsx(Mn,{size:14})}),!s&&!g&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:t.jsx(kt,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(vt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Gn,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:k,handleModalButton:j,handleRelaunch:P,handleSendChat:y,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Qr={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Qu(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gi(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(Qu())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Qr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Qr[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Qr[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function yi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:kt},{key:"chats",label:"Chats",icon:Kt}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:o,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:o})]},n)})})})}function ar({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function us({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Ms({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function or({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",d=s==="task_complete",{isReconnecting:m,isConnecting:f}=ks(e.conversation),p=st(e.conversation),x=is(e.conversation),b=Ho(e.conversation,{requiresAction:s==="needs_attention"}),S=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",u=c?"text-text-secondary":"text-text-primary",h=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",j="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(e.conversation),type:"button",children:[o||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(p)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:p}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:Co(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${h}`,children:[x,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${j} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):b==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:j,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),o&&!d&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function Va({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function em({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:m,onShowConversation:f,onShowAllHidden:p,onOpenNewSession:x,onOpenMachine:b,onOpenSettings:S,onSectionChange:A,wsStatus:u="connected",isStandalone:h=!1}){const y=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,j=s.length>0||r.length>0||n.length>0||o.length>0,P=e==="machines"?"Machines":"Chats",k=h?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",g=h?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:P}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(_r,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(Ar,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${g}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Ms,{icon:t.jsx(Va,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:h?"Waiting for your daemon":"Connect your machines",subtitle:h?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!h&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(gi,{})})}):t.jsx(us,{children:c.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(N.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:d(N.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:N.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:N.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[N.unread," new"]}):N.total>0?`${N.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:N.subtitle}),N.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[N.total," chat",N.total!==1?"s":"",N.unread>0?` · ${N.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},N.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Needs attention",className:"mb-0"}),t.jsx(us,{children:s.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"needs_attention",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(us,{children:r.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"task_complete",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(ar,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(us,{children:n.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"working",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&t.jsx(ar,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(us,{children:o.map((N,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(or,{item:N,type:"earlier",getAvatarText:d,onOpenConversation:m})},N.conversation.tabKey))}):j?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Ms,{icon:t.jsx(Va,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?t.jsx(Ms,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Kt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Ms,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:p,children:"Restore all"})]}),t.jsx(us,{className:"bg-bg-secondary/25",children:i.map((N,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(N),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:d(st(N))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:st(N)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:is(N)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},N.tabKey))})]})]}),e==="chats"&&x&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(yi,{section:e,onSectionChange:A})]})}function Dr(...e){const s=new Set,r=[],n=o=>{const i=typeof o=="string"?o.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const o of e){if(Array.isArray(o)){for(const i of o)n(i);continue}n(o)}return r}function tm(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),o=(r[2]||"").replace(/[\\/]+/g,"\\");return o?`${n}:\\${o}`:`${n}:\\`}return null}function Er(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=tm(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function sm(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function $r(e,s,r){const n=await e(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const o=typeof(n==null?void 0:n.path)=="string"?n.path:r,i=o.includes("\\")?"\\":"/",c=(m,f)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${f}`:m==="/"||m==="\\"?`${i}${f}`:`${m.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:c(o,m.name)})).sort((m,f)=>m.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Br({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:m,onConfirm:f}){const[p,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const b=sm(r),S=p.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!b||o||m(b)},disabled:!b||o,children:[t.jsx(Tn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:p,onChange:A=>x(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!S||o||(A.preventDefault(),m(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||o||m(S)},disabled:!S||o,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>m(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(S||r),disabled:!S&&!r||o,children:c})]})]})})}function qn({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:d="Launching…",busy:m=!1,showArgsInput:f,argsValue:p,onArgsChange:x,showModelInput:b,modelValue:S,onModelChange:A,historyProviderNode:u,onConfirm:h,onCancel:y}){const l=n==null?void 0:n.find(j=>j.key===o);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:o||"",onChange:j=>i(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:m,children:n.map(j=>t.jsx("option",{value:j.key,children:j.label},j.key))}),(l==null?void 0:l.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l.description})]}),u,r.map(j=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),b&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:S||"",onChange:j=>A(j.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]}),f&&x&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:p||"",onChange:j=>x(j.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:m})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:m,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:h,disabled:m,children:[t.jsx(_n,{size:14}),m?d:c]})]})]})})}function Ga(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ts(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=e,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${Ga(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Ga(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(f=>f.key===m))return{options:i,selectedKey:m}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function en(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function rm({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var X,ce,Ce,Re;const c=Gs(),[d,m]=a.useState(!1),f=(((X=e.detectedIdes)==null?void 0:X.length)||0)>0,p=a.useMemo(()=>(e.workspaces||[]).map(me=>({id:me.id,path:me.path,label:me.label})),[e]),x=e.defaultWorkspaceId||null,[b,S]=a.useState(x||((ce=p[0])==null?void 0:ce.id)||""),[A,u]=a.useState(""),[h,y]=a.useState(""),[l,j]=a.useState([]),[P,k]=a.useState(!1),[g,N]=a.useState(""),[v,w]=a.useState(!1),[M,T]=a.useState(en(f,s.length,r.length)),$=a.useRef(null),[E,F]=a.useState(null),D=a.useRef("__home__"),[C,V]=a.useState("__home__"),[J,I]=a.useState(""),[R,B]=a.useState(""),[z,Z]=a.useState(""),[fe,Pe]=a.useState([]),[ke,ve]=a.useState(!1),[Q,xe]=a.useState(!1),W=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ee=b==="__custom__"?A.trim():((Ce=p.find(me=>me.id===b))==null?void 0:Ce.path)||"",ne=b==="__custom__"&&!!ee&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=b!=="__custom__"&&((Re=p.find(me=>me.id===b))==null?void 0:Re.path)||"",he=a.useMemo(()=>(e.recentLaunches||[]).map(me=>me.workspace),[e]),te=a.useCallback(async me=>{k(!0),N("");try{const We=await o(me);y(We.path),u(We.path),j(We.directories)}catch(We){N(We instanceof Error?We.message:"Could not load folder")}finally{k(!1)}},[o]),de=a.useCallback(()=>{var We;S("__custom__"),w(!0);const me=Er(e.platform,Dr(A.trim(),oe,he,e.defaultWorkspacePath,(We=p.find(Be=>Be.id===x))==null?void 0:We.path,p.map(Be=>Be.path)));te(me)},[A,x,te,he,oe,e.platform,p]),se=a.useCallback(me=>{if(me!=null&&me.workspaceId){S(me.workspaceId),u("");return}if(me!=null&&me.workspacePath){S("__custom__"),u(me.workspacePath);return}S(""),u("")},[]),pe=a.useCallback(me=>{if(S(me),me==="__custom__"){de();return}u("")},[de]),ae=a.useCallback(me=>{S("__custom__"),u(me)},[]),Ne=a.useCallback((me,We)=>{$.current=We,D.current=me.selectedWorkspaceKey||"__home__",V(me.selectedWorkspaceKey||"__home__"),I(me.initialArgs||""),B(me.initialModel||""),Z(""),Pe([]),F(me),me.providerType&&i&&(ve(!0),i(me.providerType).then(Be=>Pe(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>ve(!1)))},[i]),ge=a.useCallback(()=>{$.current&&(xe(!0),$.current().finally(()=>{$.current=null,xe(!1),F(null)}))},[]),_=a.useCallback(()=>{$.current=null,F(null)},[]),ue=a.useCallback(me=>{D.current=me,V(me)},[]);return a.useEffect(()=>{var me;W.current!==e.id&&(W.current=e.id,S(x||((me=p[0])==null?void 0:me.id)||"__custom__"),u(""),y(""),j([]),N(""),w(!1),T(en(f,s.length,r.length)))},[r.length,s.length,x,f,e.id,p]),a.useEffect(()=>{var me;b!=="__custom__"&&(b&&p.some(We=>We.id===b)||S(x||((me=p[0])==null?void 0:me.id)||"__custom__"))},[x,b,p]),a.useEffect(()=>{M==="ide"&&f||M==="cli"&&s.length>0||M==="acp"&&r.length>0||T(en(f,s.length,r.length))},[M,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:p,defaultWorkspaceId:x,workspaceChoice:b,customWorkspacePath:A,browseCurrentPath:h,browseDirectories:l,browseBusy:P,browseError:g,browseDialogOpen:v,activeLauncherKind:M,launchConfirm:E,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:C,launchConfirmArgs:J,launchConfirmModel:R,launchConfirmResumeId:z,launchConfirmSavedSessions:fe,launchConfirmSessionsLoading:ke,launchConfirmBusy:Q,resolvedWorkspacePath:ee,canCreateMissingWorkspace:ne,openBrowseDialog:de,loadBrowsePath:te,handleWorkspaceChoiceChange:pe,chooseCustomWorkspacePath:ae,setCustomWorkspacePath:u,setBrowseDialogOpen:w,setActiveLauncherKind:T,openLaunchConfirm:Ne,handleConfirmLaunch:ge,closeLaunchConfirm:_,setWorkspaceSelectionFromOption:se,setLaunchConfirmWorkspaceKeyAndSync:ue,setLaunchConfirmArgs:I,setLaunchConfirmModel:B,setLaunchConfirmResumeId:Z}}function nm({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:m,section:f,showBottomNav:p,onBack:x,onSectionChange:b,onOpenConversation:S,onOpenRecent:A,onOpenMachineDetails:u,onMachineUpgrade:h,onLaunchDetectedIde:y,onAddWorkspace:l,onBrowseDirectory:j,onLaunchWorkspaceProvider:P,onListSavedSessions:k}){const g=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",N=r.slice(0,4),v=s.slice(0,3),w=rm({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:j,onListSavedSessions:k}),M=a.useMemo(()=>N.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${g(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:C.workspace});w.openLaunchConfirm({title:C.kind==="ide"?Yt("restart-ide",C.label):C.providerSessionId?qo(C.label):Yt("start-fresh",C.label),description:C.kind==="ide"?Xt("restart-ide"):C.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:C.kind==="ide"?Jt("restart-ide"):C.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:C.kind==="ide"?Zt("restart-ide"):C.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:g(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),await A({...C,workspace:(I==null?void 0:I.workspacePath)??null})})}})),[w,A,N]),T=a.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:st(C.conversation),secondary:hd(C.conversation,{timestampLabel:C.timestamp?Co(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,v]),$=w.showAllRecent?M:M.slice(0,4),E=M.length>0,F=T.length>0,D=m?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Tn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:jt(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),E&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:$.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),M.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(C=>!C),children:w.showAllRecent?"Show fewer":`Show ${M.length-4} more`})})]}),(w.hasIdeOptions||n.length>0||o.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:w.workspaceChoice,onChange:C=>w.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:w.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[w.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===w.defaultWorkspaceId?"⭐ ":"",Pr(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(gs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:w.resolvedWorkspacePath||w.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:w.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{w.resolvedWorkspacePath&&l(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:V,selectedKey:J}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:V,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const I=V.find(R=>R.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(I),y(C.type,{workspacePath:(I==null?void 0:I.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(w.activeLauncherKind==="cli"?n:o).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const V=w.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:I}=ts({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${V.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:I,details:[{label:"Mode",value:V.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:V==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const R=J.find(B=>B.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(R),P(V,C.type,{workspaceId:(R==null?void 0:R.workspaceId)??null,workspacePath:(R==null?void 0:R.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${d.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[d.message,w.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>l(w.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:h,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),w.browseDialogOpen&&t.jsx(Br,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:C=>{w.loadBrowsePath(C)},onConfirm:C=>{w.chooseCustomWorkspacePath(C),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&t.jsx(qn,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Nr(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),w.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsxs("select",{value:w.launchConfirmResumeId,onChange:C=>w.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Vo()}),w.launchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),p&&t.jsx(yi,{section:f,onSectionChange:b})]})}function vi(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function am(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:n.currentModel||n.workspace||void 0,workspace:n.workspace,currentModel:n.currentModel})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i,c,d,m,f;const o=Hs(n)?"cli":xs(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Hs(n)?n.cliName||n.type:xs(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:xs(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(m=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function om(e,s){const r=new Map;for(const n of s){const o=Ut(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return e.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((x,b)=>b.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=xn(n),m=o.filter(x=>x.unread||x.requiresAction).length,f=vi(n),p=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:jt(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?bd(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,o)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=o.latestTimestamp||o.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(o.label)})}function ir(e,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,s)}catch{}}function im({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:p,onRequestedMachineConsumed:x,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,setSelectedTabKey:A,setScreen:u,setSelectedMachineId:h,setSection:y,setMachineBackTarget:l,resetMachineAction:j}){const P=a.useRef(null),k=a.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ws(g,c),v=Math.max(Date.now(),Ht(g),N.lastUpdated||0);ir("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:st(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ht(g),readAt:v}),d(Ut(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,seenAt:v}).then(w=>{ir("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:w})}).catch(w=>{ir("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:w instanceof Error?w.message:String(w)})})},[c,d]);return a.useEffect(()=>{var N;if(!n){u("inbox"),A(((N=e[0])==null?void 0:N.tabKey)||null),P.current=null;return}if(i!=="chat"){P.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;P.current!==g&&(P.current=g,k(n))},[e,k,i,n,u,A]),a.useEffect(()=>{if(!m)return;const g=e.find(N=>N.tabKey===m);g&&(A(g.tabKey),u("chat"),f==null||f())},[e,f,m,u,A]),a.useEffect(()=>{if(!p)return;const g=s.find(N=>N.id===p);g&&(h(g.id),j(),y("machines"),l("inbox"),u("machine"),x==null||x())},[s,x,p,j,l,u,y,h]),a.useEffect(()=>{b&&(y(b),u("inbox"),S==null||S())},[S,b,u,y]),a.useEffect(()=>{const g=r.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&ir("inbox_state",{screen:i,selectedTabKey:o,items:g.map(N=>{const v=Ws(N.conversation,c);return{liveState:v,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:st(N.conversation),serverBucket:v.inboxBucket,computedBucket:N.inboxBucket,serverUnread:v.unread,computedUnread:N.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:Ht(N.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function cm(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function qa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lm(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dm({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[m,f]=a.useState(null),p=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),x=a.useCallback(async(l,j,P)=>{var k;try{i("loading"),d(`Launching ${j}…`);const g={ideType:j,enableCdp:!0};(k=P==null?void 0:P.workspacePath)!=null&&k.trim()&&(g.workspace=P.workspacePath.trim()),await e(l,"launch_ide",g),i("done"),d(`${j} launch requested`)}catch(g){i("error"),d(g instanceof Error?g.message:"Launch IDE failed"),console.error("Launch IDE failed",g)}},[e]),b=a.useCallback(async(l,j,P)=>{if(j.trim())try{i("loading"),d(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(l,"workspace_add",{path:j.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),d(k instanceof Error?k.message:"Could not save workspace")}},[e]),S=a.useCallback(async l=>{var j,P,k,g,N,v;try{i("loading"),d("Starting daemon upgrade…");const w=await e(l,"daemon_upgrade",{});if((j=w==null?void 0:w.result)!=null&&j.alreadyLatest){i("done"),d(`Already on v${((P=w==null?void 0:w.result)==null?void 0:P.version)||"latest"}.`);return}if((k=w==null?void 0:w.result)!=null&&k.upgraded||(g=w==null?void 0:w.result)!=null&&g.success){i("done"),d(`Upgrade to v${((N=w==null?void 0:w.result)==null?void 0:N.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((v=w==null?void 0:w.result)==null?void 0:v.error)||"Upgrade failed")}catch(w){i("error"),d(w instanceof Error?w.message:"Upgrade failed")}},[e]),A=a.useCallback(async(l,j,P,k)=>{var v,w,M;const g=Date.now(),N={machineId:l,kind:j,providerType:P,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:g};try{i("loading"),d(`Launching ${P}…`),f(N);const T={cliType:P};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?T.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(T.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(T.resumeSessionId=k.resumeSessionId),(w=k==null?void 0:k.args)!=null&&w.trim()&&(T.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(M=k==null?void 0:k.model)!=null&&M.trim()&&(T.initialModel=k.model.trim());const $=await e(l,"launch_cli",T),E=($==null?void 0:$.result)||$,F=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if($!=null&&$.success&&F){f(null),i("done"),d(`${P} launched`),s(`/dashboard?activeTab=${encodeURIComponent(F)}`);return}if($!=null&&$.success){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(($==null?void 0:$.error)||(E==null?void 0:E.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(T){if(lm(T)){i("loading"),d(`${P} launch requested — waiting for session…`);return}f(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${j.toUpperCase()} workspace`)}},[s,e]),u=a.useCallback(async(l,j)=>{try{const P=await e(l,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),k=(P==null?void 0:P.result)??P;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),h=a.useCallback(async(l,j)=>$r(e,l,j),[e]);a.useEffect(()=>{var k;if(!m)return;const l=qa(m.workspacePath),j=r.find(g=>{var $,E,F,D;if(!g||g.type==="adhdev-daemon"||cm(g.daemonId||g.id)!==m.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==m.kind||String(g.agentType||g.type||"")!==m.providerType)return!1;const M=String(g.providerSessionId||"");if(m.resumeSessionId&&M)return M===m.resumeSessionId;if(l){const C=qa(g.workspace||g.runtimeWorkspaceLabel);return C?C===l:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((D=(F=(E=($=g.activeChat)==null?void 0:$.messages)==null?void 0:E.at)==null?void 0:F.call(E,-1))==null?void 0:D.timestamp)||0)>=m.startedAt-5e3});if(!j)return;const P=typeof j.sessionId=="string"&&j.sessionId?j.sessionId:typeof j.instanceId=="string"&&j.instanceId?j.instanceId:(k=n.find(g=>g.routeId===j.id))==null?void 0:k.sessionId;P&&(f(null),i("done"),d(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const l=window.setTimeout(()=>{f(j=>!j||j.startedAt!==m.startedAt?j:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[m]);const y=a.useCallback(async(l,j)=>{if(j.kind==="ide"&&j.providerType){await x(l,j.providerType,{workspacePath:j.workspace||null});return}(j.kind==="cli"||j.kind==="acp")&&j.providerType&&await A(l,j.kind,j.providerType,{workspacePath:j.workspace||null,resumeSessionId:j.providerSessionId||null})},[x,A]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:x,handleAddWorkspace:b,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:A,handleListSavedSessions:u,handleBrowseDirectory:h,handleOpenRecent:y}}function um({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:m,setMachineBackTarget:f}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),x=a.useCallback(y=>{const l=e.find(j=>j.routeId===y.routeId&&j.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[e,n,c,i]),b=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((y,l="inbox")=>{d(y),o(),m("machines"),f(l),c("machine")},[o,f,c,m,d]),A=a.useCallback(y=>{const l=Ut(y);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),h=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:x,backFromConversation:b,openMachine:S,openConversationMachine:A,backFromMachine:u,changeMachineSection:h}}function mm(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function pm(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function cr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function fm({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,onOpenHistory:u,onOpenRemote:h,onStopCli:y,wsStatus:l,isConnected:j,onShowHiddenConversation:P,onShowAllHiddenConversations:k,onHideConversation:g,onOpenNewSession:N}){const[v,w]=a.useState(()=>{var X;return((X=e[0])==null?void 0:X.tabKey)||null}),[M,T]=a.useState(()=>e[0]?"chat":"inbox"),[$,E]=a.useState("chats"),[F,D]=a.useState(null),[C,V]=a.useState("inbox"),J=ws(),I="0.8.53",R=a.useMemo(()=>e.find(X=>X.tabKey===v)||e[0]||null,[e,v]),B=a.useMemo(()=>R?r.find(X=>X.id===R.routeId):void 0,[r,R]),z=a.useMemo(()=>!R||Ve(R)||!Ye(R)?null:vs(R),[R]),Z=a.useMemo(()=>r.filter(X=>X.type==="adhdev-daemon").sort(Ln),[r]),fe=a.useMemo(()=>Z.find(X=>X.id===F)||null,[Z,F]),Pe=a.useMemo(()=>Fs(r),[r]),ke=Lr({sendDaemonCommand:o,activeConv:R||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),ve=dm({sendDaemonCommand:o,navigate:J,ides:r,conversations:e}),Q=a.useMemo(()=>e.map(X=>{const ce=M==="chat"&&(R==null?void 0:R.tabKey)===X.tabKey,Ce=Os(X,Pe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ce}),Re=Ht(X),me=Oo(X);return{conversation:X,timestamp:Re,preview:me,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,Pe,M,R]),{markConversationRead:xe}=im({conversations:e,machineEntries:Z,items:Q,selectedConversation:R,selectedTabKey:v,screen:M,liveSessionInboxState:Pe,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:x,onRequestedMachineConsumed:b,requestedMobileSection:S,onRequestedMobileSectionConsumed:A,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V,resetMachineAction:ve.resetMachineAction}),W=um({conversations:e,selectedConversation:R,machineBackTarget:C,markConversationRead:xe,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:w,setScreen:T,setSelectedMachineId:D,setSection:E,setMachineBackTarget:V}),ee=a.useMemo(()=>cr(Q.filter(X=>X.requiresAction)),[Q]),ne=a.useMemo(()=>cr(Q.filter(X=>X.unread&&!X.requiresAction)),[Q]),oe=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&X.isWorking)),[Q]),he=a.useMemo(()=>cr(Q.filter(X=>!X.unread&&!X.requiresAction&&!X.isWorking)),[Q]),te=a.useMemo(()=>fe?Q.filter(X=>Ut(X.conversation)===fe.id):[],[Q,fe]),de=a.useMemo(()=>am(fe,r),[r,fe]),se=(fe==null?void 0:fe.version)||null,pe=!!fe&&!!se&&!0&&se!==I,ae=a.useMemo(()=>(fe==null?void 0:fe.availableProviders)||[],[fe]),Ne=a.useMemo(()=>ae.filter(X=>X.category==="cli"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),ge=a.useMemo(()=>ae.filter(X=>X.category==="acp"&&X.installed!==!1).map(X=>({type:X.type,displayName:X.displayName||X.type,icon:X.icon})),[ae]),_=a.useMemo(()=>om(Z,Q),[Q,Z]),ue=a.useCallback(async X=>{fe&&await ve.handleOpenRecent(fe.id,X)},[ve,fe]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&R?t.jsx(Zu,{selectedConversation:R,isAcp:Ve(R),isStandalone:d,selectedIdeEntry:B,actionLogs:n,userName:m,isSendingChat:ke.isSendingChat,isFocusingAgent:ke.isFocusingAgent,handleModalButton:ke.handleModalButton,handleRelaunch:ke.handleRelaunch,onBack:W.backFromConversation,onOpenNativeConversation:W.openNativeConversation,onOpenMachine:W.openConversationMachine,onHideConversation:g,onOpenHistory:u,onOpenRemote:h,onStopCli:y,cliViewMode:z,onSetCliViewMode:async X=>{if(R&&z!==X)try{await o(Ut(R)||R.routeId,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:wt(R),mode:X})}catch(ce){pm(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},handleSendChat:ke.handleSendChat,handleFocusAgent:ke.handleFocusAgent}):M==="machine"&&fe?t.jsx(nm,{selectedMachineEntry:fe,selectedMachineConversations:te,selectedMachineRecentLaunches:de,cliProviders:Ne,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:I,machineAction:ve.machineAction,isStandalone:d,section:$,showBottomNav:C==="inbox",onBack:W.backFromMachine,onSectionChange:W.changeMachineSection,onOpenConversation:W.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>J(`/machines/${fe.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(fe.id),onLaunchDetectedIde:(X,ce)=>ve.handleLaunchDetectedIde(fe.id,X,ce),onAddWorkspace:(X,ce)=>ve.handleAddWorkspace(fe.id,X,ce),onBrowseDirectory:X=>ve.handleBrowseDirectory(fe.id,X),onLaunchWorkspaceProvider:(X,ce,Ce)=>ve.handleLaunchWorkspaceProvider(fe.id,X,ce,Ce),onListSavedSessions:X=>ve.handleListSavedSessions(fe.id,X)}):t.jsx(em,{section:$,attentionItems:ee,unreadItems:ne,workingItems:oe,completedItems:he,hiddenConversations:s,machineCards:_,getAvatarText:mm,onOpenConversation:W.openConversation,onShowConversation:P,onShowAllHidden:k,onOpenNewSession:N,onOpenMachine:W.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:E,wsStatus:l,isConnected:j,isStandalone:d})})}function tn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function xm({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,m]=a.useState(!1),[f,p]=a.useState(null),x=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const b=a.useCallback(h=>{h.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=a.useCallback(h=>{if(!h.dataTransfer.types.includes("text/tab-key"))return;if(h.preventDefault(),!tn(s,r)){p("merge");return}const y=h.currentTarget.getBoundingClientRect(),l=h.clientX-y.left,j=y.width/3;l<j?p("split-left"):l>j*2?p("split-right"):p("merge")},[s,r]),A=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),u=a.useCallback(h=>{c.current=0,m(!1);const y=h.dataTransfer.getData("text/tab-key"),l=y?e.some(P=>P.tabKey===y):!1,j=f;if(p(null),i(),!!y){if(h.preventDefault(),j==="split-left"&&tn(s,r)){r==null||r(y,"split-left");return}if(j==="split-right"&&tn(s,r)){r==null||r(y,"split-right");return}if(l){o(y);return}n==null||n(y)}},[e,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:x,handleDragEnter:b,handleDragOver:S,handleDragLeave:A,handleDrop:u}}function hm(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),o=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function bm({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,m]=a.useState(r??[]),[f,p]=a.useState(null),x=a.useRef(null),b=a.useRef(null),S=a.useRef(n),A=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{A.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(N=>{const v=hm(N,e);return v.length===N.length&&v.every((w,M)=>w===N[M])?N:v})},[e]);const u=a.useMemo(()=>{const N=f??d;if(N.length===0)return e;const v=new Map(N.map((w,M)=>[w,M]));return[...e].sort((w,M)=>{const T=v.get(w.tabKey)??999,$=v.get(M.tabKey)??999;return T-$})},[e,f,d]);a.useEffect(()=>{var v,w;if(u.length===0){i!==null&&(c(null),(v=S.current)==null||v.call(S,null));return}if(i&&u.some(M=>M.tabKey===i))return;const N=u[0].tabKey;N!==i&&(c(N),(w=S.current)==null||w.call(S,N))},[u,i]);const h=a.useMemo(()=>u.find(N=>N.tabKey===i),[u,i]),y=a.useCallback(N=>{var v;c(N),(v=S.current)==null||v.call(S,N)},[]),l=a.useCallback((N,v,w)=>{m(M=>{var F;const T=M.filter(D=>D!==N),$=T.indexOf(v);if($<0)return M;const E=w==="left"?$:$+1;return T.splice(E,0,N),(F=A.current)==null||F.call(A,T),T}),p(null)},[]),j=a.useCallback((N,v,w)=>{const T=(d.length>0?d:e.map(F=>F.tabKey)).filter(F=>F!==N),$=T.indexOf(v);if($<0)return;const E=w==="left"?$:$+1;T.splice(E,0,N),x.current=T,p(T)},[d,e]),P=a.useCallback(()=>{var v;const N=x.current;N&&(m(N),(v=A.current)==null||v.call(A,N))},[]),k=a.useCallback(()=>{x.current=null,p(null)},[]),g=a.useCallback(N=>{m(v=>{var M;const w=v.filter(T=>T!==N);return w.push(N),(M=A.current)==null||M.call(A,w),w})},[]);return{activeTabId:i,activeConv:h,sortedConversations:u,previewOrderRef:x,draggingTabRef:b,selectTab:y,handleTabReorder:l,updatePreviewOrder:j,commitPreviewOrder:P,clearPreviewOrder:k,moveTabToEnd:g,setDraggingTabKey:N=>{b.current=N}}}function gm({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Yn({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:o=!1}){if(o)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",d=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),i&&t.jsx(gi,{}),i&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const wi="adhdev-tab-shortcuts";function ji(){try{return JSON.parse(localStorage.getItem(wi)||"{}")}catch{return{}}}function ki({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>ji()),[d,m]=a.useState(null),f=a.useCallback(x=>{const b=[];return x.metaKey&&b.push(o?"⌘":"Meta"),x.ctrlKey&&b.push("Ctrl"),x.altKey&&b.push(o?"⌥":"Alt"),x.shiftKey&&b.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(b.push(x.key.length===1?x.key.toUpperCase():x.key),b.join("+"))},[o]),p=a.useCallback(x=>{c(x);try{localStorage.setItem(wi,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!e||!d)return;const x=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){m(null);return}const S=f(b);if(!S)return;const A={...i};for(const[u,h]of Object.entries(A))h===S&&delete A[u];A[d]=S,p(A),m(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,d,i,p,f]),a.useEffect(()=>{if(!e)return;const x=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[S,A]of Object.entries(i))if(s.includes(S)&&f(b)===A){b.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:m,saveShortcuts:p}}const ym=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:m,onSelectTab:f,onConversationActivated:p,onPreviewReorder:x,onReorderTab:b,onCommitPreviewOrder:S,onClearPreviewOrder:A,onDragStateReset:u,onDragTabKeyChange:h,onReceiveTab:y,onOpenContextMenu:l,longPressTimer:j,isGroupActive:P}){const k=ks(s),g=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",N=k.isReconnecting,v=a.useCallback(V=>{d.current=s.tabKey,h(s.tabKey),V.dataTransfer.setData("text/tab-key",s.tabKey),V.dataTransfer.effectAllowed="move"},[s.tabKey,d,h]),w=a.useCallback(()=>{d.current=null,h(null),S(),A(),u()},[d,h,S,A,u]),M=a.useCallback(V=>{const J=d.current;if(!(!J||J===s.tabKey)&&V.dataTransfer.types.includes("text/tab-key")){V.preventDefault(),V.stopPropagation();const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";x(J,s.tabKey,R)}},[s.tabKey,d,x]),T=a.useCallback(V=>{V.preventDefault(),V.stopPropagation();const J=V.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const I=V.currentTarget.getBoundingClientRect(),R=V.clientX<I.left+I.width/2?"left":"right";c.includes(J)?b(J,s.tabKey,R):y&&y(J)}A()},[s.tabKey,c,b,y,A]),$=a.useCallback(V=>{V.stopPropagation(),m(),f(s.tabKey),p(s)},[s,p,m,f]),E=a.useCallback(V=>{V.preventDefault(),l(V.clientX,V.clientY,s.tabKey)},[s.tabKey,l]),F=a.useCallback(V=>{const J=V.touches[0];j.current=setTimeout(()=>{l(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,j,l]),D=a.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),C=["adhdev-dockview-tab",g,r&&"is-active",P&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:w,onDragOver:M,onDrop:T,onClick:$,onContextMenu:E,onTouchStart:F,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:st(s),children:st(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:N?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[qt(s),t.jsx("span",{className:"connecting-dots"})]}):qt(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function vm({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onHideTab:u,isGroupActive:h,allowTabShortcuts:y=!0}){const[l,j]=a.useState(null),P=a.useRef(null),k=a.useRef(null),g=a.useMemo(()=>e.map(E=>E.tabKey),[e]);zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:N,tabShortcuts:v,shortcutListening:w,setShortcutListening:M,saveShortcuts:T}=ki({enabled:y,sortedTabKeys:e.map(E=>E.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const E=F=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(F.target)||j(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[l]),a.useEffect(()=>{const E=k.current;if(!E)return;const F=D=>{Math.abs(D.deltaY)>Math.abs(D.deltaX)&&(D.preventDefault(),E.scrollLeft+=D.deltaY)};return E.addEventListener("wheel",F,{passive:!1}),()=>E.removeEventListener("wheel",F)},[]);const $=a.useCallback((E,F,D)=>{j({x:E,y:F,tabKey:D})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[e.map(E=>t.jsx(ym,{conv:E,isActive:s===E.tabKey,isDraggedTab:o.current===E.tabKey,isTaskCompleteUnread:n.has(E.tabKey),shortcut:y?v[E.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:x,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:A,onOpenContextMenu:$,longPressTimer:P,isGroupActive:h},E.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:l.x,top:l.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:E=>{E.stopPropagation(),M(l.tabKey),j(null)},children:["⌨ ",v[l.tabKey]?`Change shortcut (${v[l.tabKey]})`:"Set shortcut"]}),v[l.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const E={...v};delete E[l.tabKey],T(E),j(null)},children:"✕ Remove shortcut"})]}),u&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(l.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&w&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>M(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function wm({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:p,onFocus:x,isSplitMode:b,numGroups:S,onMoveTab:A,onReceiveTab:u,style:h,onActiveTabChange:y,initialActiveTabId:l,initialTabOrder:j,onTabOrderChange:P,onHideTab:k,isFocused:g,allowTabShortcuts:N=!0}){const{sendCommand:v}=Ct(),w=a.useRef(null),{activeTabId:M,activeConv:T,sortedConversations:$,draggingTabRef:E,selectTab:F,handleTabReorder:D,updatePreviewOrder:C,commitPreviewOrder:V,clearPreviewOrder:J,moveTabToEnd:I,setDraggingTabKey:R}=bm({conversations:e,initialActiveTabId:l,initialTabOrder:j,onActiveTabChange:y,onTabOrderChange:P}),B=Lr({sendDaemonCommand:o,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:z,dropAction:Z,resetDragState:fe,handleDragEnter:Pe,handleDragOver:ke,handleDragLeave:ve,handleDrop:Q}=xm({conversations:e,numGroups:S,onMoveTab:A,onReceiveTab:u,onOwnTabDrop:I,onClearPreviewOrder:J}),xe=T&&!Ve(T)&&vs(T)==="terminal",W=a.useMemo(()=>T?s.find(te=>te.id===T.routeId):void 0,[s,T]),ee=a.useMemo(()=>T?n.filter(te=>te.routeId===T.tabKey):[],[n,T]),ne=a.useMemo(()=>Fs(s),[s]),oe=a.useMemo(()=>new Set($.filter(te=>ol(te,ne,{isOpenConversation:te.tabKey===M})).map(te=>te.tabKey)),[M,ne,$]);zs("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:M,dragOver:z});const he=a.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&v(te.routeId,"focus_session",{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[v]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...h,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(vm,{conversations:$,activeTabId:M,groupIndex:p,numGroups:S,unreadTabKeys:oe,draggingTabRef:E,onFocus:x,onSelectTab:F,onConversationActivated:he,onPreviewReorder:C,onReorderTab:D,onCommitPreviewOrder:V,onClearPreviewOrder:J,onDragStateReset:fe,onDragTabKeyChange:R,onMoveTab:A,onReceiveTab:u,onHideTab:k,isGroupActive:g??!1,allowTabShortcuts:N}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Pe,onDragOver:ke,onDragLeave:ve,onDrop:Q,children:[z&&t.jsx(gm,{dropAction:Z,canSplit:!!(S<4&&A)}),T?t.jsx(Gn,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!xe,ideEntry:W,terminalRef:w,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ee,userName:f,isInputActive:!b||!!g}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:e.length,isSplitMode:b,isStandalone:d,hasRegisteredMachines:m})})]})]})}function jm({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,focusedGroup:A,setFocusedGroup:u,moveTabToGroup:h,splitTabRelative:y,closeGroup:l,handleResizeStart:j,groupActiveTabIds:P,setGroupActiveTabIds:k,groupTabOrders:g,setGroupTabOrders:N,toggleHiddenTab:v,allowTabShortcuts:w=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,T)=>{const $=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(rt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:E=>j(T-1,E),onDoubleClick:()=>l(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(wm,{style:s?{flexBasis:$??`${100/r}%`,flexGrow:$?0:1,flexShrink:$?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:x,hasRegisteredMachines:b,userName:S,groupIndex:T,isFocused:s&&A===T,onFocus:()=>u(T),isSplitMode:s,numGroups:r,onMoveTab:(E,F)=>{F==="left"&&T>0?h(E,T-1):F==="right"&&T<r-1?h(E,T+1):F==="split-left"&&r<4?y(E,T,"left"):F==="split-right"&&r<4&&y(E,T,"right")},onReceiveTab:E=>h(E,T),onActiveTabChange:E=>k(F=>(F[T]??null)===(E??null)?F:{...F,[T]:E}),initialActiveTabId:P[T],initialTabOrder:g[T],onTabOrderChange:E=>N(F=>{const D=F[T]||[];return D.length===E.length&&D.every((C,V)=>C===E[V])?F:{...F,[T]:E}}),onHideTab:v,allowTabShortcuts:w})]},T)})})}function Ni({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>e?at.onScreenshot("ide-page",(p,x)=>{if(p!==e)return;const b=new FileReader;b.onload=()=>i(b.result),b.readAsDataURL(x)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return e?((p=at.onStatus)==null?void 0:p.call(at,(x,b)=>{x===e&&b!=null&&b.screenshotUsage&&d(b.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const f=e?at.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const m=a.useCallback(async(f,p)=>{const x=e?at.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,p,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Si="adhdev-dashboard-action-shortcuts",km=1200,Nm={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Sm(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ci(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:Je("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:Je("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:Je("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",e)}]}function kn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Ir(e){const s=Object.fromEntries(Ci(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Si)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Nm))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Ii(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Cm({enabled:e=!0,onTrigger:s}){const r=Sm(),[n,o]=a.useState(()=>Ir(r)),[i,c]=a.useState(null),[d,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),p=a.useCallback(u=>{const h=[];return u.metaKey&&h.push(r?"⌘":"Meta"),u.ctrlKey&&h.push("Ctrl"),u.altKey&&h.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(h.push(Ii(u.key)),h.join("+"))},[r]),x=a.useCallback(u=>{o(u);try{localStorage.setItem(Si,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=Ir(r),h=Object.entries(n),y=Object.entries(u);h.length===y.length&&h.every(([l,j])=>u[l]===j)||x(u)},[n,r,x]);const b=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),S=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},km))},[]);a.useEffect(()=>{if(!i)return;const u=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){c(null),m([]);return}const y=p(h);if(!y)return;const j=!(h.metaKey||h.ctrlKey||h.altKey)&&/^[A-Z0-9]$/.test(y);if(d.length===0&&j){m([y]);return}const k=[...d,y].slice(0,2).join(" "),g={...n};for(const[N,v]of Object.entries(g))v===k&&delete g[N];g[i]=k,x(g),c(null),m([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,p,x,i,d]),a.useEffect(()=>{if(!e||i)return;const u=h=>{if(h.defaultPrevented)return;const y=p(h);if(!y)return;const l=h.metaKey||h.ctrlKey||h.altKey;if(kn(h.target)&&!l)return;const j=f.current.parts,P=l?[y]:[...j.slice(-1),y].slice(-2),k=P.join(" "),g=P[P.length-1],N=Object.entries(n).filter(([,$])=>!!$),v=N.find(([,$])=>$===k);if(v){h.preventDefault(),b(),s(v[0]);return}if(N.some(([,$])=>$.startsWith(`${k} `))){h.preventDefault(),f.current.parts=P,S();return}const M=N.find(([,$])=>$===g);if(M){h.preventDefault(),b(),s(M[0]);return}if(N.some(([,$])=>$.startsWith(`${g} `))){h.preventDefault(),f.current.parts=[g],S();return}b()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,e,p,s,b,i]),a.useEffect(()=>()=>b(),[b]);const A=a.useMemo(()=>Ci(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:x}}const Ti=a.createContext(null);function Kr(){const e=a.useContext(Ti);if(!e)throw new Error("DashboardDockviewContext missing");return e}function br(e){return st(e)||e.tabKey}function Im(e){return`remote:${e}`}function Wt(e){return e.startsWith("remote:")}function Ya(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function sn(e){var r,n,o,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=e==null?void 0:e.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,m;try{s.focus(),(m=(d=e==null?void 0:e.body)==null?void 0:d.focus)==null||m.call(d)}catch{}})}catch{}}function lr(e,s){e.classList.remove(mn.className,pn.className),e.classList.add(s==="light"?mn.className:pn.className)}function Xa(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Tm(e){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[e.api,e.containerApi])}function Am(e,s,r){var d;const n=[s];let o;for(const m of n){let f;for(const p of m){const x=e.addPanel({id:p.tabKey,component:"conversation",title:br(p),params:{kind:"conversation",tabKey:p.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=x.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function Ja(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Wt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const o=e.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==br(n)&&o.api.setTitle(br(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:br(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Za(e,s,r){var m,f;const n=r?Im(r):null;for(const p of[...e.panels])Wt(p.id)&&(!n||p.id!==n)&&e.removePanel(p);if(!r||!n)return;const o=Lt(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=zo(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((f=e.panels.find(p=>!Wt(p.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function Mm({params:e,api:s}){var x;const r=Kr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),d=Lr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const b=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of b)S.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(b=>b.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(b=>b.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const p=!Ve(c)&&vs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Gn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function _m({params:e}){var m;const s=Kr(),r=a.useMemo(()=>Lt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),o=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=Ni({doId:o,targetSessionId:r?Bn(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(So,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):t.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function Pm(){const e=Kr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Yn,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Rm(e){var S,A;Tm(e);const s=Kr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const u=Lt([...s.conversationsByTabKey.values()],e.params.routeId),h=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const o=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=Os(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,p=c.isWaiting,x=c.unread,b=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:st(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var h;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((h=u.target)==null?void 0:h.ownerDocument)??document})},children:[x&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):p?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:st(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:qt(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:qt(n)}):t.jsx("span",{children:qt(n)})})]}),b&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function Lm({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:f,userName:p,toggleHiddenTab:x,actionShortcuts:b,registerActionHandlers:S,onActiveTabChange:A,requestedActiveTabKey:u,requestedRemoteIdeId:h,onRequestedActiveTabConsumed:y,scrollToBottomRequest:l}){var Te,Ae,Qe;const{theme:j}=Un(),{sendCommand:P}=Ct(),k=a.useRef(null),g=a.useRef(null),N=a.useRef(!1),v=a.useRef(!1),w=a.useRef(!1),M=a.useRef(null),T=a.useRef([]),[$,E]=a.useState(null),[F,D]=a.useState(!1),[C,V]=a.useState(!1),[J,I]=a.useState(0),R=a.useRef(null),B=a.useMemo(()=>fi(typeof window<"u"?window.innerWidth:1280),[]),z=a.useRef(typeof window>"u"?{}:Ku(B)),Z=a.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),fe=a.useMemo(()=>Fs(r),[r]),Pe=a.useMemo(()=>{const K=k.current;return K?K.groups.some(O=>{try{const G=O.model.location.type;return G!=="floating"&&G!=="popout"?!1:O.panels.some(H=>Z.has(H.id))}catch{return!1}}):!1},[Z,J,e]),ke=a.useCallback(()=>{var K;(K=k.current)==null||K.focus()},[]),ve=a.useCallback(K=>{const O=document,G=K.document;for(const le of O.querySelectorAll('link[rel="stylesheet"]')){const $e=G.createElement("link");$e.rel="stylesheet",$e.href=le.href,le.crossOrigin&&($e.crossOrigin=le.crossOrigin),G.head.appendChild($e)}for(const le of O.querySelectorAll("style")){const $e=G.createElement("style");$e.textContent=le.textContent,G.head.appendChild($e)}const H=[];for(const le of O.styleSheets)try{for(const $e of le.cssRules)$e instanceof CSSStyleRule&&($e.selectorText===":root"||$e.selectorText==="html")&&H.push($e.cssText)}catch{}if(H.length>0){const le=G.createElement("style");le.textContent=H.join(`
|
|
43
|
+
`),G.head.appendChild(le)}const ie=O.documentElement.getAttribute("data-theme");ie&&G.documentElement.setAttribute("data-theme",ie),G.documentElement.style.colorScheme=ie==="light"?"light":"dark",G.body.className=O.body.className;const Se=O.documentElement.getAttribute("style");Se&&G.documentElement.setAttribute("style",Se);const Y=G.getElementById("dv-popout-window");Y instanceof HTMLElement&&(Y.classList.add("adhdev-dockview"),lr(Y,j))},[j]),Q=a.useCallback(()=>{var O;const K=k.current;if(K)for(const G of K.groups)try{const H=(O=G.element)==null?void 0:O.ownerDocument;if(!H||H===document)continue;const ie=H.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),lr(ie,j));const Se=document.documentElement.getAttribute("data-theme");Se&&H.documentElement.setAttribute("data-theme",Se),H.documentElement.style.colorScheme=Se==="light"?"light":"dark",H.body.className=document.body.className;const Y=document.documentElement.getAttribute("style");Y?H.documentElement.setAttribute("style",Y):H.documentElement.removeAttribute("style")}catch{}},[j]),xe=a.useCallback(()=>{var O;const K=k.current;if(K)for(const G of K.groups)try{const H=(O=G.element)==null?void 0:O.ownerDocument;if(!H||H===document)continue;const ie=H.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),lr(ie,j),ie.classList.toggle("is-showing-dockview-overlay",C),ie.classList.toggle("is-dragging-dockview",F)}catch{}},[F,C,j]),W=a.useCallback(K=>{const O=k.current;if(!O)return;const G=O.getPanel(K);G&&O.addPopoutGroup(G,{popoutUrl:"/popout.html",onDidOpen:({window:H})=>{ve(H),ae();const ie=Z.get(K);H.document.title=ie?`${st(ie)} — ADHDev`:"ADHDev — Popout"}})},[Z,ve]),ee=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);if(!O||!G)return;const H=O.groups.filter(ie=>{var Se;try{return((Se=ie.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});H.length>0?G.api.moveTo({group:H[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),ne=a.useCallback(K=>{var H;const O=k.current;if(!O)return!1;const G=O.getPanel(K);if(!G)return!1;try{return((H=G.group.element)==null?void 0:H.ownerDocument)!==document}catch{return!1}},[]),oe=a.useCallback(K=>{ne(K)&&ee(K),x(K)},[ne,ee,x]),he=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);!O||!G||O.addFloatingGroup(G,{width:600,height:500})},[]),te=a.useCallback(K=>{var G;const O=(G=k.current)==null?void 0:G.getPanel(K);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),de=a.useCallback(()=>{var O,G;const K=(G=(O=k.current)==null?void 0:O.activePanel)==null?void 0:G.id;return!K||Wt(K)?null:Z.has(K)?K:null},[Z]),se=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.getPanel(K);if(!O||!G)return;const H=O.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});H.length>0?G.api.moveTo({group:H[0],position:"center"}):G.api.moveTo({position:"center"}),G.api.setActive()},[]),pe=a.useCallback(()=>{var Se;const K=k.current;if(!K)return;const G=K.groups.filter(Y=>{var le;try{return((le=Y.element)==null?void 0:le.ownerDocument)===document&&Y.model.location.type==="grid"}catch{return!1}})[0]||null,H=[...K.panels];for(const Y of H){const le=(Se=Y.group.element)==null?void 0:Se.ownerDocument,$e=Y.group.model.location.type;le===document&&$e==="grid"||(G&&G.id!==Y.group.id?Y.api.moveTo({group:G,position:"center"}):Y.api.moveTo({position:"center"}))}const ie=K.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),sn(document)},[]),ae=a.useCallback(()=>{var O,G;const K=k.current;if(K)for(const H of K.groups){const ie=(O=H.element)==null?void 0:O.ownerDocument;if(!ie||ie===document)continue;const Se=ie.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Y=null,le=ie.title||"ADHDev",$e="Popout workspace";const Le=H.activePanel;if(Le)if(Y=Le.id,Wt(Le.id)){const U=((G=Le.params)==null?void 0:G.routeId)||Le.id.slice(7),re=Lt([...Z.values()],U);le=zo(re),$e=re!=null&&re.machineName?`Remote view · ${re.machineName}`:"Remote view"}else{const U=Z.get(Le.id);le=U?st(U):Le.title||Le.id,$e=U?qt(U):"Dockview panel"}ie.title=`${le} — ADHDev`;let Oe=ie.getElementById("adhdev-popout-header");Oe instanceof HTMLElement||(Oe=ie.createElement("div"),Oe.id="adhdev-popout-header",ie.body.appendChild(Oe)),Oe.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Oe.innerHTML=`
|
|
44
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
46
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ya(le)}</div>
|
|
47
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ya($e)}</div>
|
|
48
|
+
</div>
|
|
49
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
51
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
52
|
+
</div>
|
|
53
|
+
`,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const Fe=Oe.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const L=Oe.querySelector("[data-adhdev-popout-dock]");L&&(L.disabled=!Y,L.style.opacity=Y?"1":"0.5",L.style.cursor=Y?"pointer":"default",L.onclick=()=>{var U;Y&&ee(Y),(U=ie.defaultView)==null||U.focus()})}},[Z,ee]),Ne=a.useCallback(K=>{var H;const O=k.current,G=O==null?void 0:O.getPanel(K);if(!(!O||!G)){G.group.model.openPanel(G),G.api.setActive();try{const ie=G.group.model.location;ie.type==="popout"?ie.getWindow().focus():sn((H=G.group.element)==null?void 0:H.ownerDocument)}catch{}}},[]),ge=a.useCallback(K=>{const O=k.current,G=O==null?void 0:O.activePanel,H=(O==null?void 0:O.activeGroup)||(G==null?void 0:G.group);if(!O||!G||!H)return;const ie=H.panels||[];if(ie.length<=1)return;const Se=ie.findIndex($e=>$e.id===G.id);if(Se<0)return;const Y=(Se+K+ie.length)%ie.length,le=ie[Y];le&&(le.group.model.openPanel(le),le.api.setActive())},[]),_=a.useCallback(K=>{var L;const O=k.current,G=(O==null?void 0:O.activeGroup)||((L=O==null?void 0:O.activePanel)==null?void 0:L.group);if(!O||!G)return;const H=O.groups||[],ie=H.find(U=>U.id===G.id);if(!ie)return;const Se=ie.element.getBoundingClientRect(),Y=Se.left+Se.width/2,le=Se.top+Se.height/2,$e=(U,re,ye,_e)=>Math.max(0,Math.min(re,_e)-Math.max(U,ye)),Le=U=>{const re=U.element.getBoundingClientRect(),ye=re.left+re.width/2,_e=re.top+re.height/2;let Ie=0,ze=0,qe=0,nt=!1;if(K==="left"?(nt=ye<Y,Ie=Math.max(0,Se.left-re.right),ze=Math.abs(_e-le),qe=$e(Se.top,Se.bottom,re.top,re.bottom)):K==="right"?(nt=ye>Y,Ie=Math.max(0,re.left-Se.right),ze=Math.abs(_e-le),qe=$e(Se.top,Se.bottom,re.top,re.bottom)):K==="above"?(nt=_e<le,Ie=Math.max(0,Se.top-re.bottom),ze=Math.abs(ye-Y),qe=$e(Se.left,Se.right,re.left,re.right)):(nt=_e>le,Ie=Math.max(0,re.top-Se.bottom),ze=Math.abs(ye-Y),qe=$e(Se.left,Se.right,re.left,re.right)),!nt)return Number.POSITIVE_INFINITY;const De=qe>0?0:120;return Ie*3+ze+De};let Oe=null,Fe=Number.POSITIVE_INFINITY;for(const U of H){if(U.id===ie.id)continue;const re=Le(U);Number.isFinite(re)&&(re>=Fe||(Fe=re,Oe=U))}return Oe||void 0},[]),ue=a.useCallback(K=>{var H;const O=_(K);if(!O)return;const G=O.activePanel||O.panels[0];G&&(O.model.openPanel(G),G.api.setActive(),sn((H=O.element)==null?void 0:H.ownerDocument))},[_]),X=a.useCallback((K,O)=>{const G=k.current,H=G==null?void 0:G.activePanel,ie=(G==null?void 0:G.activeGroup)||(H==null?void 0:H.group);if(!G||!H||!ie)return;let Se=_(K);!Se&&(O!=null&&O.createGroupIfMissing)&&(Se=G.addGroup({referenceGroup:ie,direction:K})),Se&&(H.api.moveTo({group:Se,position:"center"}),H.group.model.openPanel(H),H.api.setActive())},[_]),{isMac:ce,tabShortcuts:Ce,shortcutListening:Re,setShortcutListening:me,saveShortcuts:We}=ki({sortedTabKeys:e.map(K=>K.tabKey),onFocus:ke,onSelectTab:Ne}),Be=a.useCallback(()=>{var G;const K=k.current;if(!K)return;const O=K.activePanel;if(O){if(Wt(O.id)){const H=((G=O.params)==null?void 0:G.routeId)||O.id.slice(7),ie=Lt(e,H);ie!=null&&ie.tabKey&&me(ie.tabKey);return}Z.has(O.id)&&me(O.id)}},[Z,Ne,me,e]),Ze=a.useCallback(K=>{const O=[];return K.metaKey&&O.push(ce?"⌘":"Meta"),K.ctrlKey&&O.push("Ctrl"),K.altKey&&O.push(ce?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&O.push(ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(O.push(Ii(K.key)),O.join("+"))},[ce]),Ge=a.useCallback(K=>{var O,G;switch(K){case"splitActiveTabRight":X("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":X("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const H=de();H&&he(H);return}case"popoutActiveTab":{const H=de();H&&W(H);return}case"dockActiveTab":{const H=de();if(!H)return;ne(H)?ee(H):te(H)&&se(H);return}case"focusLeftPane":ue("left");return;case"focusRightPane":ue("right");return;case"focusUpPane":ue("above");return;case"focusDownPane":ue("below");return;case"moveActiveTabToLeftPane":X("left");return;case"moveActiveTabToRightPane":X("right");return;case"moveActiveTabToUpPane":X("above");return;case"moveActiveTabToDownPane":X("below");return;case"selectPreviousGroupTab":ge(-1);return;case"selectNextGroupTab":ge(1);return;case"setActiveTabShortcut":Be();return;case"hideCurrentTab":{const H=(G=(O=k.current)==null?void 0:O.activePanel)==null?void 0:G.id;H&&!Wt(H)&&oe(H);return}default:return}},[ge,se,ue,he,de,oe,te,ne,ee,X,W,Be]);a.useEffect(()=>{if(!$)return;const K=$.sourceDocument,O=K.defaultView??window,G=H=>{const ie=K.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(H.target)||E(null)};return O.addEventListener("mousedown",G,!0),O!==window&&window.addEventListener("mousedown",()=>E(null),!0),()=>{O.removeEventListener("mousedown",G,!0),O!==window&&window.removeEventListener("mousedown",()=>E(null),!0)}},[$]);const gt=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:Z,hasDetachedConversationPanels:Pe,ides:r,isStandalone:d,hasRegisteredMachines:m,liveSessionInboxState:fe,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:oe,userName:p,scrollToBottomRequest:l,tabShortcuts:Ce,openTabContextMenu:({x:K,y:O,tabKey:G,sourceDocument:H})=>E({x:K,y:O,tabKey:G,sourceDocument:H??document}),popoutTab:W,moveTabBackToMain:ee,isTabInPopout:ne,floatTab:he,isTabFloating:te}),[n,s,Z,Pe,r,d,m,fe,o,c,i,oe,p,l,Ce,W,ee,ne,he,te]),Xe=a.useCallback(K=>{if(!K)return!1;const O=k.current;if(!O)return!1;const G=O.getPanel(K);return G?(G.group.model.openPanel(G),G.api.setActive(),y==null||y(),!0):!1},[y]),ot=a.useCallback(()=>{if(w.current)return!1;const K=Xe(M.current);return K&&(w.current=!0),K},[Xe]),ut=a.useCallback(()=>{var O;const K=k.current;K&&Bu(B,{activeTabId:((O=K.activePanel)==null?void 0:O.id)??null,layout:K.toJSON()})},[B]),Ue=a.useCallback(()=>{Wu(B,z.current)},[B]),He=a.useCallback(K=>{var H,ie,Se,Y;const O=k.current;if(!O)return{kind:"grid"};const G=O.toJSON();for(const le of G.floatingGroups||[])if((ie=(H=le.data)==null?void 0:H.views)!=null&&ie.includes(K)&&le.position)return{kind:"floating",position:le.position};for(const le of G.popoutGroups||[])if((Y=(Se=le.data)==null?void 0:Se.views)!=null&&Y.includes(K))return{kind:"popout",position:le.position,popoutUrl:le.url};return{kind:"grid"}},[]),It=a.useCallback(K=>{const O=k.current;if(!O)return;const G=O.getPanel(K),H=z.current[K];if(!G||!H||H.kind==="grid")return;if(G.group.model.location.type===H.kind){delete z.current[K],Ue();return}if(H.kind==="floating"){O.addFloatingGroup(G,{x:H.position.left??24,y:H.position.top??24,width:H.position.width,height:H.position.height}),delete z.current[K],Ue();return}delete z.current[K],Ue()},[Ue]);a.useEffect(()=>(S==null||S({setShortcutForActiveTab:Be,restoreHiddenTabToSavedLocation:It,resetAllPanelsToMain:pe,activatePreviousTabInGroup:()=>ge(-1),activateNextTabInGroup:()=>ge(1),floatActiveTab:()=>{const K=de();K&&he(K)},popoutActiveTab:()=>{const K=de();K&&W(K)},dockActiveTab:()=>{const K=de();K&&(ne(K)?ee(K):te(K)&&se(K))},splitActiveTabRight:()=>X("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>X("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ue("left"),focusRightPane:()=>ue("right"),focusUpPane:()=>ue("above"),focusDownPane:()=>ue("below"),moveActiveTabToLeftPane:()=>X("left"),moveActiveTabToRightPane:()=>X("right"),moveActiveTabToUpPane:()=>X("above"),moveActiveTabToDownPane:()=>X("below")}),()=>S==null?void 0:S(null)),[ge,se,he,ue,de,te,ne,X,ee,W,S,pe,It,Be]);const ct=a.useCallback(()=>{const K=g.current;if(!K)return;const O=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const G of O)G.setAttribute("data-adhdev-force-hidden","true")},[]),pt=a.useCallback(()=>{const K=g.current;if(!K)return;const O=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const G of O)G.removeAttribute("data-adhdev-force-hidden")},[]),ft=a.useCallback(()=>{const K=g.current;if(!K)return;const O=K.querySelectorAll(".dv-drop-target-container");for(const ie of O)ie.remove();const G=K.querySelectorAll(".dv-drop-target-dropzone");for(const ie of G)ie.remove();const H=K.querySelectorAll(".dv-drop-target");for(const ie of H)ie.classList.remove("dv-drop-target")},[]),dt=a.useCallback(()=>{D(!1),V(!1),pt(),ct(),ft(),!(typeof window>"u")&&(R.current!=null&&window.clearTimeout(R.current),window.requestAnimationFrame(()=>{ct(),ft()}),R.current=window.setTimeout(()=>{ct(),ft(),R.current=null},80))},[pt,ct,ft]),Tt=a.useCallback(K=>{var G;k.current=K.api;const O=$u(B);M.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&K.api.fromJSON(O.layout,{reuseExistingPanels:!1}),v.current=!!(O!=null&&O.layout)&&!f&&e.length===0,v.current||(Ja(K.api,e),Za(K.api,e,h)),K.api.totalPanels===0&&e.length>0?Am(K.api,e,u):!v.current&&!Xe(u)&&ot(),N.current=!0,K.api.onDidActivePanelChange(H=>{var Se;if(M.current=(H==null?void 0:H.id)??null,w.current=!0,ae(),H&&Wt(H.id)){const Y=((Se=H.params)==null?void 0:Se.routeId)||H.id.slice(7),le=Lt(e,Y);A((le==null?void 0:le.tabKey)??null),ut();return}if(A((H==null?void 0:H.id)??null),ut(),!H)return;const ie=Z.get(H.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&P(ie.routeId,"focus_session",{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{ut(),ae(),I(H=>H+1)}),K.api.onWillDragPanel(()=>{D(!0),V(!1),ct()}),K.api.onWillDragGroup(()=>{D(!0),V(!1),ct()}),K.api.onWillShowOverlay(()=>{pt(),V(!0)}),K.api.onDidMovePanel(dt),K.api.onDidDrop(dt),K.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var ie,Se;try{const Y=(ie=H.element)==null?void 0:ie.ownerDocument;if(!Y||Y===document)return;(Se=Y.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const le=document.documentElement.getAttribute("data-theme");le&&Y.documentElement.setAttribute("data-theme",le),Y.body.className=document.body.className;const $e=document.documentElement.getAttribute("style");$e&&Y.documentElement.setAttribute("style",$e)}catch{}ae(),I(Y=>Y+1)})}),A(((G=K.api.activePanel)==null?void 0:G.id)??null)},[Xe,dt,pt,Z,f,B,ct,ft,A,ut,u,h,P,ae,e]);a.useLayoutEffect(()=>{const K=k.current;if(!K||!N.current||v.current&&!f)return;v.current&&(v.current=!1);const O=T.current,G=new Set(O),H=e.map(Le=>Le.tabKey),ie=new Set(H);let Se=!1;for(const Le of O)ie.has(Le)||(z.current[Le]=He(Le),Se=!0);Se&&Ue(),Ja(K,e),Za(K,e,h);const Y=H.filter(Le=>!G.has(Le));let le=!1;for(const Le of Y){const Oe=K.getPanel(Le),Fe=z.current[Le];if(!Oe||!Fe||Fe.kind==="grid")continue;if(Oe.group.model.location.type===Fe.kind){delete z.current[Le],le=!0;continue}if(Fe.kind==="floating"){K.addFloatingGroup(Oe,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete z.current[Le],le=!0;continue}}if(le&&Ue(),T.current=H,u&&Xe(u))return;!K.activePanel&&K.panels[0]&&(K.panels[0].group.model.openPanel(K.panels[0]),K.panels[0].api.setActive()),!!(K.activePanel&&K.getPanel(K.activePanel.id))||ot()},[Xe,ot,f,Ue,He,u,h,e]),a.useEffect(()=>{N.current&&Xe(u)},[Xe,u]),a.useEffect(()=>{if(!F||typeof window>"u")return;const K=()=>dt();return window.addEventListener("pointerup",K),window.addEventListener("mouseup",K),window.addEventListener("dragend",K),()=>{window.removeEventListener("pointerup",K),window.removeEventListener("mouseup",K),window.removeEventListener("dragend",K)}},[dt,F]),a.useEffect(()=>()=>{typeof window>"u"||R.current!=null&&window.clearTimeout(R.current)},[]),a.useEffect(()=>{const K=G=>{const H=G.target;if(!H)return;const ie=H.querySelector("[data-tab-key]")||H.closest("[data-tab-key]");if(ie){const Se=ie.getAttribute("data-tab-key");if(Se&&G.dataTransfer){const Y=H.closest(".dv-tab")||ie.closest(".dv-tab")||ie;G.dataTransfer.effectAllowed="move",G.dataTransfer.setData("text/tab-key",Se),Y instanceof HTMLElement&&G.dataTransfer.setDragImage(Y,Math.max(12,Math.round(Y.clientWidth/2)),Math.max(10,Math.round(Y.clientHeight/2)))}}};window.addEventListener("dragstart",K);const O=Xa(k.current);for(const G of O)G.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const G of O)G.removeEventListener("dragstart",K)}},[J]),a.useEffect(()=>{var O;const K=(O=g.current)==null?void 0:O.querySelector(".adhdev-dockview");K instanceof HTMLElement&&lr(K,j),Q(),ae(),xe()},[ae,xe,Q,j]),a.useEffect(()=>{ae(),xe()},[ae,xe]),a.useEffect(()=>{const K=O=>{if(O.defaultPrevented||Re)return;const G=Ze(O);if(!G)return;const H=O.metaKey||O.ctrlKey||O.altKey;kn(O.target)&&!H||Ir(ce).setActiveTabShortcut!==G||(O.preventDefault(),O.stopPropagation(),Be())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[Ze,ce,Re,Be]),a.useEffect(()=>{const K=Xa(k.current);if(K.length===0)return;const O=K.map(G=>{let H=[],ie=null;const Se=()=>{ie!=null&&G.clearTimeout(ie),ie=null,H=[]},Y=()=>{ie!=null&&G.clearTimeout(ie),ie=G.setTimeout(()=>{ie=null,H=[]},1200)},le=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const Oe=Ze(Le);if(!Oe)return;const Fe=ji();for(const[L,U]of Object.entries(Fe))if(e.some(re=>re.tabKey===L)&&U===Oe){Le.preventDefault(),Ne(L);return}},$e=Le=>{if(Le.defaultPrevented||Re)return;const Oe=Ze(Le);if(!Oe)return;const Fe=Le.metaKey||Le.ctrlKey||Le.altKey;if(kn(Le.target)&&!Fe)return;const L=Ir(ce),U=Object.entries(L).filter(([De,Pt])=>!!Pt&&(De==="splitActiveTabRight"||De==="splitActiveTabDown"||De==="floatActiveTab"||De==="popoutActiveTab"||De==="dockActiveTab"||De==="focusLeftPane"||De==="focusRightPane"||De==="focusUpPane"||De==="focusDownPane"||De==="moveActiveTabToLeftPane"||De==="moveActiveTabToRightPane"||De==="moveActiveTabToUpPane"||De==="moveActiveTabToDownPane"||De==="selectPreviousGroupTab"||De==="selectNextGroupTab"||De==="setActiveTabShortcut"||De==="hideCurrentTab")),re=Fe?[Oe]:[...H.slice(-1),Oe].slice(-2),ye=re.join(" "),_e=re[re.length-1],Ie=U.find(([,De])=>De===ye);if(Ie){Le.preventDefault(),Se(),Ge(Ie[0]);return}if(U.some(([,De])=>De.startsWith(`${ye} `))){Le.preventDefault(),H=re,Y();return}const qe=U.find(([,De])=>De===_e);if(qe){Le.preventDefault(),Se(),Ge(qe[0]);return}if(U.some(([,De])=>De.startsWith(`${_e} `))){Le.preventDefault(),H=[_e],Y();return}Se()};return G.addEventListener("keydown",le),G.addEventListener("keydown",$e),()=>{Se(),G.removeEventListener("keydown",le),G.removeEventListener("keydown",$e)}});return()=>{for(const G of O)G()}},[Ze,ce,J,Ne,Re,Ge,e]);const it=j==="light"?mn:pn,q=((Qe=(Ae=(Te=k.current)==null?void 0:Te.activePanel)==null?void 0:Ae.group.element)==null?void 0:Qe.ownerDocument)??document;return t.jsxs(Ti.Provider,{value:gt,children:[t.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(oc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${F?" is-dragging-dockview":""}${C?" is-showing-dockview-overlay":""}`,components:{conversation:Mm,remote:_m},defaultTabComponent:Rm,watermarkComponent:Pm,onReady:Tt,singleTabMode:"default",tabAnimation:"smooth",theme:it,popoutUrl:"/popout.html"})}),$&&Bs.createPortal(t.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[180px]",style:{left:$.x,top:$.y},children:[ne($.tabKey)?t.jsxs(t.Fragment,{children:[te($.tabKey)&&t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{se($.tabKey),E(null)},children:[t.jsx(la,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Dock in window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:b.dockActiveTab||""})]}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{ee($.tabKey),E(null)},children:[t.jsx(Hc,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Move back to main window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:b.dockActiveTab||""})]})]}):te($.tabKey)?t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{se($.tabKey),E(null)},children:[t.jsx(la,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Dock back to grid"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:b.dockActiveTab||""})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{he($.tabKey),E(null)},children:[t.jsx(zc,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Float as panel"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:b.floatActiveTab||""})]}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{W($.tabKey),E(null)},children:[t.jsx(Oc,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Open in new window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:b.popoutActiveTab||""})]})]}),t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:K=>{K.stopPropagation(),me($.tabKey),E(null)},children:[t.jsx(Uc,{size:13,className:"shrink-0 opacity-70"})," ",Ce[$.tabKey]?`Change shortcut (${Ce[$.tabKey]})`:"Set shortcut"]}),Ce[$.tabKey]&&t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{const K={...Ce};delete K[$.tabKey],We(K),E(null)},children:[t.jsx(vt,{size:13,className:"shrink-0 opacity-70"})," Remove shortcut"]}),t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{oe($.tabKey),E(null)},children:[t.jsx(vo,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),$.sourceDocument.body),Re&&Bs.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>me(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ce?"⌘+1":"Ctrl+1",", ",ce?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),q.body)]})}const Ai="adhdev-recent-launch-args-v1",Dm=8;function Em(e){return String(e||"").trim().replace(/\s+/g," ")}function Mi(e,s){return`${e.trim()}::${s.trim()}`}function _i(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ai)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function $m(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ai,JSON.stringify(e))}catch{}}function Pi(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=_i().byKey[Mi(r,n)])==null?void 0:i.items)||[]}function Ri(e,s,r){var p;const n=String(e||"").trim(),o=String(s||"").trim(),i=Em(r);if(!n||!o||!i)return;const c=_i(),d=Mi(n,o),m=((p=c.byKey[d])==null?void 0:p.items)||[],f=[i,...m.filter(x=>x!==i)].slice(0,Dm);c.byKey[d]={items:f},$m(c)}function Xn(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function Li(e){var o;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),d=Xn((i==null?void 0:i.meta)||void 0),m=((o=i==null?void 0:i.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(m||d)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Di(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function bs(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function rn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Bm(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Qa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function eo(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function Km(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Wm(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function Om(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Hm({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var J;const[d,m]=a.useState(n||((J=e[0])==null?void 0:J.id)||null),[f,p]=a.useState(""),[x,b]=a.useState(null),[S,A]=a.useState(!1);a.useEffect(()=>{var I;m(n||((I=e[0])==null?void 0:I.id)||null)},[n,e]);const u=a.useMemo(()=>e.find(I=>I.id===d)||e[0]||null,[d,e]),h=a.useMemo(()=>r.filter(I=>{if(I.type==="adhdev-daemon"||I.transport!=="pty")return!1;const R=Bm(I.daemonId||I.id);return!!(u!=null&&u.id)&&R===u.id}),[u==null?void 0:u.id,r]),y=ui(u==null?void 0:u.id,{enabled:!!(u!=null&&u.id),includeSessions:!0,limit:6,intervalMs:1e4}),l=y.diagnostics,j=y.loading,P=y.applyDiagnostics,k=a.useMemo(()=>{const I=new Map;for(const R of h){const B=s.find(z=>z.sessionId===R.sessionId||z.routeId===R.id);R.sessionId&&B&&I.set(R.sessionId,B)}return I},[h,s]),g=a.useCallback(async()=>{if(u!=null&&u.id){A(!0);try{const I=await o(u.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),R=rn(I);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Could not load hosted runtime diagnostics");P(R.diagnostics||R.result||null),p("")}catch(I){const R=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";p(R)}finally{A(!1)}}},[u==null?void 0:u.id,P,o]);a.useEffect(()=>{!(u!=null&&u.id)||l||j||S||g()},[u==null?void 0:u.id,l,j,g,S]);const N=a.useCallback(async(I,R)=>{if(!(u!=null&&u.id)||I==="session_host_stop_session"&&!window.confirm(`Stop ${R.displayName}?
|
|
54
|
+
This will terminate the hosted runtime.`))return;const B=`${I}:${R.sessionId}`;b(B);try{const z=await o(u.id,I,{sessionId:R.sessionId}),Z=rn(z);if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Session host action failed");const fe=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${fe}: ${R.displayName}`,"success"),await g()}catch(z){const Z=z instanceof Error?z.message:"Session host action failed";p(Z),tt.showToast(Z,"warning")}finally{b(z=>z===B?null:z)}},[u==null?void 0:u.id,g,o]),v=a.useCallback(async()=>{if(!(!(u!=null&&u.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
55
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){b("session_host_prune_duplicate_sessions");try{const R=await o(u.id,"session_host_prune_duplicate_sessions",{}),B=rn(R);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Duplicate prune failed");const z=B.result||{},Z=Array.isArray(z.prunedSessionIds)?z.prunedSessionIds.length:0,fe=typeof z.duplicateGroupCount=="number"?z.duplicateGroupCount:0;tt.showToast(`Pruned ${Z} duplicate runtime(s) across ${fe} group(s)`,"success"),await g()}catch(R){const B=R instanceof Error?R.message:"Duplicate prune failed";p(B),tt.showToast(B,"warning")}finally{b(R=>R==="session_host_prune_duplicate_sessions"?null:R)}}},[u==null?void 0:u.id,g,o]),w=a.useMemo(()=>[...(l==null?void 0:l.sessions)||[]].sort((I,R)=>(R.lastActivityAt||0)-(I.lastActivityAt||0)),[l==null?void 0:l.sessions]),M=a.useMemo(()=>l!=null&&l.liveRuntimes||l!=null&&l.recoverySnapshots||l!=null&&l.inactiveRecords?{liveRuntimes:(l==null?void 0:l.liveRuntimes)||[],recoverySnapshots:(l==null?void 0:l.recoverySnapshots)||[],inactiveRecords:(l==null?void 0:l.inactiveRecords)||[]}:Li(w),[l==null?void 0:l.inactiveRecords,l==null?void 0:l.liveRuntimes,l==null?void 0:l.recoverySnapshots,w]),T=M.liveRuntimes,$=M.recoverySnapshots,E=M.inactiveRecords,F=a.useMemo(()=>Om(T),[T]),D=a.useMemo(()=>[...(l==null?void 0:l.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[l==null?void 0:l.recentLogs]),C=a.useMemo(()=>[...(l==null?void 0:l.recentTransitions)||[]].slice(-3).reverse(),[l==null?void 0:l.recentTransitions]),V=(I,R)=>{var W,ee;const B=k.get(I.sessionId),z=h.find(ne=>ne.sessionId===I.sessionId),Z=x===`session_host_resume_session:${I.sessionId}`,fe=x===`session_host_restart_session:${I.sessionId}`,Pe=x===`session_host_stop_session:${I.sessionId}`,ke=Xn(I.meta),ve=typeof((W=I.meta)==null?void 0:W.runtimeRecoveryError)=="string"?String(I.meta.runtimeRecoveryError):"",Q=R==="recovery"?"Recover":"Resume",xe=Di(R);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:I.displayName||(z==null?void 0:z.runtimeDisplayName)||(z==null?void 0:z.cliName)||I.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Wm(I.lifecycle)}`,children:I.lifecycle}),ke&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:ke})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:I.workspaceLabel||(z==null?void 0:z.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ee=I.writeOwner)==null?void 0:ee.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Km(I.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(An,{size:11})," ",I.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",eo(I.lastActivityAt),I.osPid?` · pid ${I.osPid}`:"",` · Next: ${xe}`]}),ve&&t.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:ve})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[B&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(B),c()},children:"Open chat"}),R==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{N("session_host_resume_session",I)},children:Z?`${Q}ing…`:Q}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{N("session_host_restart_session",I)},children:fe?"Restarting…":"Restart"}),R==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!x,onClick:()=>{N("session_host_stop_session",I)},children:Pe?"Stopping…":"Stop"})]})]},I.sessionId)};return t.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:I=>I.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Bt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(u==null?void 0:u.label)||"No machine selected"}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Live runtime status, next actions, and explicit recover/restart controls."})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:()=>{g()},disabled:j||S,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(js,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(vt,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(I=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${I.id===(u==null?void 0:u.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>m(I.id),children:I.label},I.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[f&&!l&&t.jsx("div",{className:"rounded-2xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-4 py-3 text-[12px] text-amber-100",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ns,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime recovery unavailable"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:f})]})]})}),l&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Live"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:l.runtimeCount})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:$.length})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),t.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:eo(l.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Qa(l.hostStartedAt)})]})]}),D&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ns,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:D.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Mr,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[F>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:x==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:x==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${F}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[h.length," dashboard session",h.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:bs("live")}),T.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:T.map(I=>V(I,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:bs("recovery")}),$.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:$.map(I=>V(I,"recovery"))})]}),E.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:bs("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:E.map(I=>V(I,"inactive"))})]}),C.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:C.map(I=>{const R=w.find(B=>B.sessionId===I.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(R==null?void 0:R.displayName)||I.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Qa(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]})]})]})]})})}function nn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(o=>o.category==="cli"&&o.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(o=>o.category==="acp"&&o.installed!==!1)?"acp":null}function dr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Um({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:d,onListSavedSessions:m,sendDaemonCommand:f,onOpenConversation:p}){var Tt,it;const x=Gs(),b=a.useMemo(()=>[...e].sort(Ln),[e]),[S,A]=a.useState(((Tt=b[0])==null?void 0:Tt.id)||""),u=a.useMemo(()=>b.find(q=>q.id===S)||b[0],[S,b]),h=a.useMemo(()=>((u==null?void 0:u.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[u]),y=(u==null?void 0:u.defaultWorkspaceId)||null,[l,j]=a.useState(""),[P,k]=a.useState(""),[g,N]=a.useState(nn(b[0])),[v,w]=a.useState(""),[M,T]=a.useState(""),[$,E]=a.useState([]),[F,D]=a.useState(""),[C,V]=a.useState([]),[J,I]=a.useState(!1),[R,B]=a.useState(""),[z,Z]=a.useState(!1),[fe,Pe]=a.useState(!1),[ke,ve]=a.useState(null),[Q,xe]=a.useState(!1),[W,ee]=a.useState(""),[ne,oe]=a.useState(!1),[he,te]=a.useState(""),[de,se]=a.useState([]),[pe,ae]=a.useState(!1),[Ne,ge]=a.useState(""),[_,ue]=a.useState(!1),X=a.useRef(null),ce=a.useRef(0);a.useEffect(()=>{var q;!S&&((q=b[0])!=null&&q.id)&&A(b[0].id)},[S,b]),a.useEffect(()=>{!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||x(u.id,{minFreshMs:3e4}).catch(()=>{})},[x,u]);const Ce=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[u]),Re=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[u]),me=a.useMemo(()=>((u==null?void 0:u.detectedIdes)||[]).map(q=>({id:q.type,label:q.name||q.type,meta:q.running?"Detected locally":"Available to open"})),[u]),We=a.useMemo(()=>g==="cli"?Ce.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):g==="acp"?Re.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):me,[Re,g,Ce,me]);a.useEffect(()=>{var Te;if(!u)return;if(X.current!==u.id){X.current=u.id,j(y||((Te=h[0])==null?void 0:Te.id)||"__home__"),k(""),N(nn(u)),w(""),T(""),D(""),V([]),B(""),ee("");return}j(Ae=>{var Qe;return Ae==="__custom__"||Ae==="__home__"||h.some(K=>K.id===Ae)?Ae:y||((Qe=h[0])==null?void 0:Qe.id)||"__home__"}),N(Ae=>Ae==="ide"&&me.length>0||Ae==="cli"&&Ce.length>0||Ae==="acp"&&Re.length>0?Ae:nn(u))},[Re.length,Ce.length,y,me.length,u,h]),a.useEffect(()=>{var q;g&&(We.some(Te=>Te.id===v)||w(((q=We[0])==null?void 0:q.id)||""))},[g,We,v]);const Be=a.useCallback(async(q,Te)=>{const Ae=ce.current+1;return ce.current=Ae,I(!0),B(""),m(q,Te).then(Qe=>{ce.current===Ae&&V(Qe)}).catch(Qe=>{ce.current===Ae&&(V([]),B(Qe instanceof Error?Qe.message:"Could not load saved sessions"))}).finally(()=>{ce.current===Ae&&I(!1)})},[m]),Ze=a.useCallback((q,Te)=>{E(Pi(q,Te))},[]);a.useEffect(()=>{if(D(""),!u||!v||g==="ide"?E([]):Ze(u.id,v),g!=="cli"){V([]),B(""),I(!1);return}if(!u||!v){V([]),B(""),I(!1);return}Be(u.id,v)},[g,Ze,Be,u,v]),a.useEffect(()=>{if(!F)return;const q=C.find(Te=>Te.providerSessionId===F);q!=null&&q.canResume||D("")},[C,F]);const Ge=l==="__custom__"?P.trim():l==="__home__"?"":((it=h.find(q=>q.id===l))==null?void 0:it.path)||"",gt=a.useMemo(()=>u?r.filter(q=>q.id!==u.id&&q.daemonId===u.id).map(q=>q.workspace):[],[r,u]),Xe=a.useMemo(()=>((u==null?void 0:u.recentLaunches)||[]).map(q=>q.workspace),[u]),ot=a.useCallback(q=>{const Te=String(q.workspace||"").trim();if(!Te)return;const Ae=h.find(Qe=>dr(Qe.path)===dr(Te));if(Ae){j(Ae.id),k("");return}j("__custom__"),k(Te)},[h]),ut=a.useCallback(q=>{const Te=String(q.workspace||"").trim();if(!Te)return{workspaceId:null,workspacePath:null};const Ae=h.find(Qe=>dr(Qe.path)===dr(Te));return Ae?{workspaceId:Ae.id,workspacePath:null}:{workspaceId:null,workspacePath:Te}},[h]),Ue=a.useMemo(()=>{var Te;if(g!=="cli"||!u||!v)return null;const q=((Te=Ce.find(Ae=>Ae.type===v))==null?void 0:Te.displayName)||v;return{routeId:u.id,daemonId:u.id,providerSessionId:F||void 0,transport:"pty",mode:"chat",agentName:q,agentType:v,status:"idle",title:q,messages:[],ideType:v,workspaceName:Ge,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${u.id}:${v}`,machineName:jt(u,{fallbackId:u.id})}},[g,Ce,Ge,u,F,v]),He=a.useCallback(()=>{var Te;if(!u)return;j("__custom__"),oe(!0),ge("");const q=Er(u.platform,Dr(P.trim(),Ge,gt,Xe,u.defaultWorkspacePath,(Te=h.find(Ae=>Ae.id===y))==null?void 0:Te.path,h.map(Ae=>Ae.path)));ae(!0),o(u.id,q).then(Ae=>{te(Ae.path),k(Ae.path),se(Ae.directories)}).catch(Ae=>{ge(Ae instanceof Error?Ae.message:"Could not load folder")}).finally(()=>ae(!1))},[P,y,Xe,gt,o,Ge,u,h]),It=a.useCallback(q=>{u&&(ae(!0),ge(""),o(u.id,q).then(Te=>{te(Te.path),k(Te.path),se(Te.directories)}).catch(Te=>{ge(Te instanceof Error?Te.message:"Could not load folder")}).finally(()=>ae(!1)))},[o,u]),ct=a.useCallback(async()=>{if(!u||!Ge)return;ue(!0),ee("");const q=await i(u.id,Ge);if(ue(!1),!q.ok){ee(q.error||"Could not save workspace");return}ee("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Ge,u]),pt=a.useCallback(async()=>{if(!u||!g||!v)return;xe(!0),ee("");const q=M.trim()?M.trim().split(/\s+/).filter(Boolean):[],Te=g==="ide"?await c(u.id,v,{workspacePath:Ge||null}):await d(u.id,g,v,{workspaceId:l!=="__home__"&&l!=="__custom__"?l:null,workspacePath:l==="__custom__"&&Ge||null,resumeSessionId:g==="cli"&&F?F:null,cliArgs:q});if(xe(!1),!Te.ok){ee(Te.error||"Could not start session");return}g!=="ide"&&M.trim()&&(Ri(u.id,v,M),Ze(u.id,v)),n()},[g,M,Ze,n,c,d,Ge,u,F,v,l]),ft=g==="cli"?Nr(!!F):g==="ide"?"Start IDE":g==="acp"?"Start ACP session":"Start",dt=g==="cli"?Wn(!!F):"Starting…";return u?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[min(88vh,860px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start or recover session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh, resume saved history, or recover a hosted runtime."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:n,"aria-label":"Close new session dialog",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Machine"}),t.jsx("select",{value:u.id,onChange:q=>A(q.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:b.map(q=>t.jsx("option",{value:q.id,children:jt(q,{fallbackId:q.id})},q.id))})]}),g==="cli"&&t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Hosted runtimes"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow."})]}),t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:Q||!u,onClick:()=>Pe(!0),children:[t.jsx(Bt,{size:14}),Id()]})]})}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Workspace"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Saved workspace is preferred. Home and custom folders are still available."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:He,disabled:Q,children:"Browse…"})]}),t.jsxs("select",{value:l,onChange:q=>{const Te=q.target.value;j(Te),Te==="__custom__"?He():ee("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),h.map(q=>t.jsxs("option",{value:q.id,children:[q.id===y?"⭐ ":"",Pr(q.path,q.label)||q.path]},q.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l==="__home__"?"Launch without a workspace.":Ge||"Select a workspace folder."}),l==="__custom__"&&Ge&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:He,disabled:Q,children:[t.jsx(gs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ct,disabled:Q||_,children:_?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ce.length>0},{id:"ide",label:"IDE",enabled:me.length>0},{id:"acp",label:"ACP",enabled:Re.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${g===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>N(q.id),disabled:!q.enabled||Q,children:q.label},q.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:g==="ide"?"Choose IDE":g==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[We.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>w(q.id),disabled:Q,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:q.meta})]},q.id)),We.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),g!=="ide"&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Startup arguments"}),t.jsx("input",{type:"text",value:M,onChange:q=>T(q.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q}),$.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:$.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>T(q),disabled:Q,title:q,children:q},q))})]}),g==="cli"&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Pick a saved CLI session when you want continuity. Leave this empty to start fresh."})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:Q||!u||!v||J,onClick:()=>{!u||!v||Be(u.id,v)},children:J?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:Q||!u||!v,onClick:()=>{!u||!v||(Z(!0),Be(u.id,v))},children:Go()})]})]}),t.jsx("div",{className:"mt-2",children:t.jsxs("select",{value:F,onChange:q=>{const Te=q.target.value;if(D(Te),!Te)return;const Ae=C.find(Qe=>Qe.providerSessionId===Te);!Ae||!Ae.canResume||ot(Ae)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q||J,children:[t.jsx("option",{value:"",children:Vo()}),C.map(q=>t.jsxs("option",{value:q.providerSessionId,disabled:!q.canResume,children:[q.title||q.providerSessionId,q.canResume?"":" (workspace missing)"]},q.providerSessionId))]})}),F&&(()=>{const q=C.find(Te=>Te.providerSessionId===F);return q?t.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-mono break-all",children:q.providerSessionId}),t.jsxs("div",{className:"mt-1",children:[q.workspace||"Workspace unknown",q.currentModel?` · ${q.currentModel}`:""]})]}):null})(),R&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:R}),!J&&!R&&C.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history found for this provider yet."})]}),W&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${W.includes("saved")||W.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:W})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:Q,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:pt,disabled:Q||!g||!v||l==="__custom__"&&!Ge,children:[t.jsx(_n,{size:14}),Q?dt:ft]})]})]})}),ne&&t.jsx(Br,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:he,directories:de,busy:pe,error:Ne,onClose:()=>oe(!1),onNavigate:It,onConfirm:q=>{k(q),te(q),j("__custom__"),oe(!1)}}),z&&Ue&&t.jsx(On,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:J,savedSessions:C,isSavedSessionsLoading:J,isResumingSavedSessionId:ke,onClose:()=>Z(!1),onNewChat:()=>{D(""),Z(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!u||!v||Be(u.id,v)},onResumeSavedSession:q=>{if(!u||!v||ke||!q.canResume)return;const Te=ut(q);D(q.providerSessionId),ot(q),ve(q.providerSessionId),Z(!1),xe(!0),ee(""),d(u.id,"cli",v,{workspaceId:Te.workspaceId,workspacePath:Te.workspacePath,resumeSessionId:q.providerSessionId}).then(Ae=>{if(!Ae.ok){ee(Ae.error||"Could not resume session");return}n()}).finally(()=>{xe(!1),ve(Ae=>Ae===q.providerSessionId?null:Ae)})}}),fe&&u&&t.jsx(Hm,{machineCards:[{id:u.id,label:jt(u,{fallbackId:u.id}),subtitle:[u.platform||"machine",vi(u)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:u.id,sendDaemonCommand:f,onOpenConversation:q=>{Pe(!1),n(),p(q)},onClose:()=>Pe(!1)})]}):null}function zm(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function Fm(e){return e instanceof Error?e.message:String(e||"")}function Vm(e){const s=Fm(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Gm({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:d,onStopCli:m,activeCliViewMode:f,onSetActiveCliViewMode:p,mobileChatConversations:x,hiddenConversations:b,ides:S,actionLogs:A,sendDaemonCommand:u,setLocalUserMessages:h,setActionLogs:y,isStandalone:l,initialDataLoaded:j,userName:P,requestedMobileTabKey:k,onRequestedMobileTabConsumed:g,requestedMachineId:N,onRequestedMachineConsumed:v,requestedMobileSection:w,onRequestedMobileSectionConsumed:M,containerRef:T,isSplitMode:$,numGroups:E,groupSizes:F,groupedConvs:D,clearedTabs:C,focusedGroup:V,setFocusedGroup:J,moveTabToGroup:I,splitTabRelative:R,closeGroup:B,handleResizeStart:z,groupActiveTabIds:Z,setGroupActiveTabIds:fe,groupTabOrders:Pe,setGroupTabOrders:ke,toggleHiddenTab:ve,visibleConversations:Q,requestedDesktopTabKey:xe,onRequestedDesktopTabConsumed:W,onDesktopActiveTabChange:ee,onHideConversation:ne,onShowHiddenConversation:oe,onShowAllHiddenConversations:he,scrollToBottomRequest:te,machineEntries:de,onBrowseMachineDirectory:se,onSaveMachineWorkspace:pe,onLaunchMachineIde:ae,onLaunchMachineProvider:Ne,onListMachineSavedSessions:ge}){const _=rt.useRef(null),[ue,X]=rt.useState(!1),[ce,Ce]=rt.useState(!1),[Re,me]=rt.useState(!1),[We,Be]=rt.useState(!1),Ze=rt.useCallback(Y=>{var le;Bs.flushSync(()=>{oe(Y)}),(le=_.current)==null||le.restoreHiddenTabToSavedLocation(Y.tabKey)},[oe]),[Ge,gt]=rt.useState(!1),[Xe,ot]=rt.useState("quickstart"),[ut,Ue]=rt.useState("workspace"),He=!e&&!s,It=rt.useCallback(Y=>{X(Y),Y&&Ce(!1)},[]),ct=rt.useCallback(Y=>{Ce(Y),Y&&X(!1)},[]),pt=rt.useCallback(()=>{var le;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((le=_.current)==null||le.resetAllPanelsToMain(),Ce(!1))},[]),ft=rt.useCallback(()=>{ot(Q.length===0?"quickstart":"shortcuts"),Ue("workspace"),me(!0),X(!1),Ce(!1)},[Q.length]),dt=rt.useCallback(async Y=>{var Fe;if(!r)return;const le=(Fe=r.modalButtons)==null?void 0:Fe[Y];if(!le)return;const $e=Us(r);if(!$e)return;const Le=le.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Oe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Le);try{await u($e,"resolve_action",{button:le,action:Oe?"approve":"reject",buttonIndex:Y,...hs(r)})}catch(L){Vm(L)||console.error("[Shortcut approval] Failed:",L)}},[r,u]),{isMac:Tt,actionDefinitions:it,actionShortcuts:q,shortcutListening:Te,shortcutListeningDraft:Ae,setShortcutListening:Qe,setShortcutListeningDraft:K,saveShortcuts:O}=Cm({enabled:He&&!Re,onTrigger:Y=>{var le,$e,Le,Oe,Fe,L,U,re,ye,_e,Ie,ze,qe,nt,De,Pt;if(Y==="openShortcutHelp"){ft();return}if(Y==="hideCurrentTab"){r&&ne(r);return}if(Y==="toggleHiddenTabs"){ct(!ce);return}if(Y==="openHistoryForActiveTab"){r&&!Ve(r)&&c(r);return}if(Y==="openRemoteForActiveTab"){r&&!Ye(r)&&!Ve(r)&&d(r);return}if(Y==="splitActiveTabRight"){(le=_.current)==null||le.splitActiveTabRight();return}if(Y==="splitActiveTabDown"){($e=_.current)==null||$e.splitActiveTabDown();return}if(Y==="floatActiveTab"){(Le=_.current)==null||Le.floatActiveTab();return}if(Y==="popoutActiveTab"){(Oe=_.current)==null||Oe.popoutActiveTab();return}if(Y==="dockActiveTab"){(Fe=_.current)==null||Fe.dockActiveTab();return}if(Y==="focusLeftPane"){(L=_.current)==null||L.focusLeftPane();return}if(Y==="focusRightPane"){(U=_.current)==null||U.focusRightPane();return}if(Y==="focusUpPane"){(re=_.current)==null||re.focusUpPane();return}if(Y==="focusDownPane"){(ye=_.current)==null||ye.focusDownPane();return}if(Y==="moveActiveTabToLeftPane"){(_e=_.current)==null||_e.moveActiveTabToLeftPane();return}if(Y==="moveActiveTabToRightPane"){(Ie=_.current)==null||Ie.moveActiveTabToRightPane();return}if(Y==="moveActiveTabToUpPane"){(ze=_.current)==null||ze.moveActiveTabToUpPane();return}if(Y==="moveActiveTabToDownPane"){(qe=_.current)==null||qe.moveActiveTabToDownPane();return}if(Y==="triggerPrimaryApprovalAction"){dt(0);return}if(Y==="triggerSecondaryApprovalAction"){dt(1);return}if(Y==="triggerTertiaryApprovalAction"){dt(2);return}if(Y==="setActiveTabShortcut"){(nt=_.current)==null||nt.setShortcutForActiveTab();return}if(Y==="selectPreviousGroupTab"){(De=_.current)==null||De.activatePreviousTabInGroup();return}if(Y==="selectNextGroupTab"){(Pt=_.current)==null||Pt.activateNextTabInGroup();return}!r||!Ye(r)||Ve(r)||Y==="toggleCliView"&&p(f==="chat"?"terminal":"chat")}}),G=rt.useCallback(()=>{me(!1),Qe(null),K([])},[Qe,K]),H=rt.useMemo(()=>ut==="all"?it:it.filter(Y=>zm(Y)===ut),[it,ut]),ie=rt.useCallback(()=>{const Y=Object.fromEntries(it.map(le=>[le.id,""]));O(Y)},[it,O]),Se=rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Y=Object.fromEntries(it.map(le=>[le.id,le.defaultShortcut]));O(Y)},[it,O]);return rt.useEffect(()=>{const Y=le=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?le.metaKey&&le.key.toLowerCase()==="w":le.ctrlKey&&le.key.toLowerCase()==="w")&&(le.preventDefault(),r&&ne&&ne(r))};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[r,ne]),rt.useEffect(()=>{if(!Re||Te)return;const Y=le=>{le.key==="Escape"&&(le.preventDefault(),G())};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[G,Re,Te]),rt.useEffect(()=>{if(!He){gt(!1);return}gt(!0);const Y=window.setTimeout(()=>{gt(!1)},1e4);return()=>window.clearTimeout(Y)},[He]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Cd,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:Q,hiddenConversations:b,onOpenHistory:c,onOpenConversation:Ze,onHideConversation:ne,onShowConversation:Ze,onShowAllHidden:he,onResetPanelsToMain:pt,inboxOpen:ue,onInboxOpenChange:It,hiddenOpen:ce,onHiddenOpenChange:ct,onOpenNewSession:s?void 0:()=>Be(!0),actionShortcuts:q,onOpenRemote:()=>{!r||Ye(r)||Ve(r)||d(r)},onStopCli:m,activeCliViewMode:f,onSetCliViewMode:p}),e?t.jsx(fm,{conversations:x,hiddenConversations:b,ides:S,actionLogs:A,sendDaemonCommand:u,setLocalUserMessages:h,setActionLogs:y,isStandalone:l,userName:P,requestedActiveTabKey:k,onRequestedActiveTabConsumed:g,requestedMachineId:N,onRequestedMachineConsumed:v,requestedMobileSection:w,onRequestedMobileSectionConsumed:M,onOpenHistory:c,onOpenRemote:d,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:Ze,onShowAllHiddenConversations:he,onOpenNewSession:()=>Be(!0)}):s?t.jsx(jm,{containerRef:T,isSplitMode:$,numGroups:E,groupSizes:F,groupedConvs:D,clearedTabs:C,ides:S,actionLogs:A,sendDaemonCommand:u,setLocalUserMessages:h,setActionLogs:y,isStandalone:l,hasRegisteredMachines:de.length>0,userName:P,focusedGroup:V,setFocusedGroup:J,moveTabToGroup:I,splitTabRelative:R,closeGroup:B,handleResizeStart:z,groupActiveTabIds:Z,setGroupActiveTabIds:fe,groupTabOrders:Pe,setGroupTabOrders:ke,toggleHiddenTab:ve,allowTabShortcuts:!1}):t.jsx(Lm,{visibleConversations:Q,clearedTabs:C,ides:S,actionLogs:A,sendDaemonCommand:u,setLocalUserMessages:h,setActionLogs:y,isStandalone:l,hasRegisteredMachines:de.length>0,initialDataLoaded:j,userName:P,toggleHiddenTab:ve,actionShortcuts:q,registerActionHandlers:Y=>{_.current=Y},onActiveTabChange:ee,requestedActiveTabKey:xe,onRequestedActiveTabConsumed:W,scrollToBottomRequest:te}),We&&t.jsx(Um,{machines:de,conversations:x,ides:S,onClose:()=>Be(!1),onBrowseDirectory:se,onSaveWorkspace:pe,onLaunchIde:ae,onLaunchProvider:Ne,onListSavedSessions:ge,sendDaemonCommand:u,onOpenConversation:Y=>{Be(!1),oe(Y),ee(Y.tabKey)}}),Re&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:G,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Y=>Y.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:G,"aria-label":"Close dashboard guide",children:t.jsx(vt,{size:14})})]}),t.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Y=>t.jsx("button",{type:"button",className:`btn btn-sm ${Xe===Y.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(Y.id),children:Y.label},Y.id))}),Xe==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Tt?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Xe==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),Xe==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Y=>t.jsx("button",{type:"button",className:`btn btn-sm ${ut===Y.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(Y.id),children:Y.label},Y.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ie,children:"Disable all"}),t.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Se,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:H.map(Y=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${Te===Y.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Y.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Y.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Y.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Te===Y.id?Ae.length>0?`${Ae.join(" ")} ...`:"Listening...":q[Y.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Qe(Y.id),K([])},children:Te===Y.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const le={...q};le[Y.id]="",O(le)},children:"Disable"})]})]})},Y.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Tt?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:ft,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${Ge?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),Ge&&t.jsx("span",{children:"Guide"})]})]})}const an=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function qm({onClose:e}){const[s,r]=a.useState(0),n=an[s],o=s===an.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.target===i.currentTarget&&e()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(vt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:an.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),o&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsxs("div",{className:"flex justify-between items-center mt-6",children:[t.jsx("button",{onClick:e,className:"btn btn-secondary border-none",children:"Skip"}),t.jsx("button",{onClick:()=>o?e():r(i=>i+1),className:"btn btn-primary",children:o?"Get Started →":"Next →"})]})]}),t.jsx("style",{children:`
|
|
56
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
57
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
58
|
+
`})]})}function Ym({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:o}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:s}),n.map(i=>{const c=r===i.tabKey,d=i.status==="waiting_approval",m=i.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:d?"var(--status-warning)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"0 0 6px var(--accent-primary)":"none"}}),i.title,d&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Xm({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,d]=a.useState(()=>i||"native"),m=a.useMemo(()=>Jo(s),[s]),f=a.useMemo(()=>e?Hn(e,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,m,r]),p=a.useMemo(()=>f.find(h=>h.streamSource==="native"),[f]),x=a.useMemo(()=>f.filter(h=>h.streamSource==="agent-stream"),[f]),b=a.useMemo(()=>e?Lt(f,e.id):null,[f,e]);a.useEffect(()=>{i&&d(i)},[i]),a.useEffect(()=>{if(i||!b)return;const h=b.streamSource==="native"?"native":b.tabKey;!h||c===h||c==="native"&&d(h)},[c,b,i]),a.useEffect(()=>{var h;c!=="native"&&(x.some(y=>y.tabKey===c)||d(((h=x[0])==null?void 0:h.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(p||x[0]&&d(x[0].tabKey))},[c,p,x]);const S=a.useMemo(()=>c==="native"&&p?p:x.find(h=>h.tabKey===c)||b||p||x[0],[c,p,b,x]),A=a.useMemo(()=>x.map(h=>({tabKey:h.tabKey,title:Uo(h)||o,status:h.status})),[x,o]),u=a.useCallback(h=>{if(h)return f.find(y=>y.sessionId===h||y.routeId===h||y.tabKey===h)},[f]);return{activeChatTab:c,setActiveChatTab:d,activeConv:S,conversations:f,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:u}}function Jm({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:m,isStandalone:f,userName:p,onOpenHistory:x,onConversationChange:b,onClose:S}){const[A,u]=a.useState("split"),[h,y]=a.useState(()=>$t(e)?"native":e.tabKey),l=a.useRef(null),j=a.useMemo(()=>s||r.find(I=>I.id===e.routeId),[e.routeId,s,r]),P=a.useMemo(()=>et((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:k,extensionTabs:g,hasExtensions:N}=Xm({ideData:j,allIdes:r,connectionStates:n,localUserMessages:i,ideName:P||"IDE",preferredTabKey:$t(e)?void 0:e.tabKey}),v=a.useMemo(()=>j?Lt(k,j.id):null,[j,k]);a.useEffect(()=>{const I=l.current,R={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(l.current=R,!(I&&I.routeId===R.routeId&&I.tabKey===R.tabKey&&I.streamSource===R.streamSource)){if($t(e)){y("native");return}y(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),a.useEffect(()=>{if(h==="native"){if(k.some(I=>I.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!k.some(I=>I.tabKey===h)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[k,h,v]);const w=a.useMemo(()=>h==="native"?k.find(I=>I.streamSource==="native")||e:k.find(I=>I.tabKey===h)||e,[e,k,h]),M=mi(w),T=a.useMemo(()=>M.status||M.modalMessage||M.modalButtons?{...w,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:w,[w,M]),$=wr(T),E=Lr({sendDaemonCommand:c,activeConv:T,setLocalUserMessages:d,setActionLogs:m,isStandalone:f}),{connScreenshot:F,screenshotUsage:D,handleRemoteAction:C}=Ni({doId:$,targetSessionId:Bn(T),connState:T.connectionState||"new",viewMode:A}),V=a.useMemo(()=>o.filter(I=>I.routeId===T.tabKey),[o,T.tabKey]);a.useEffect(()=>{b==null||b(T)},[T,b]),a.useEffect(()=>{const I=R=>{R.key==="Escape"&&S()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[S]);const J=a.useCallback(I=>{I.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:S,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:J,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(kt,{size:16})}),t.jsx("span",{className:"truncate",children:Rr(w)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:S,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const R=A===I;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${R?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>u(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?t.jsx(Tc,{size:15}):t.jsx(kt,{size:15})},I)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>x(w),title:"Chat History",children:[t.jsx(Mn,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:S,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${A==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[A!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${A==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Ym,{hasExtensions:N,ideName:P||"IDE",activeChatTab:h,extensionTabs:g,onSelectTab:y}),t.jsx(Io,{activeConv:T,onModalButton:E.handleModalButton}),t.jsx(bn,{activeConv:T,ideEntry:j,showMetaChips:!1,handleSendChat:E.handleSendChat,isSendingChat:E.isSendingChat,handleFocusAgent:E.handleFocusAgent,isFocusingAgent:E.isFocusingAgent,actionLogs:V,userName:p})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${A==="split"?"order-1 md:order-2":""}`,children:t.jsx(So,{addLog:()=>{},connState:T.connectionState||"new",connScreenshot:F,screenshotUsage:D,transportType:T.transport,onAction:C})})]})]})})}function Zm({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=yd(e);return t.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-center justify-center p-4",children:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] flex flex-col overflow-hidden rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Qm({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:m,onNewHistoryChat:f,onSwitchHistorySession:p,onRefreshHistory:x,onResumeSavedHistorySession:b,remoteDialogConv:S,remoteDialogIdeEntry:A,connectionStates:u,actionLogs:h,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:j,setActionLogs:P,isStandalone:k,userName:g,onOpenRemoteHistory:N,onRemoteConversationChange:v,onCloseRemoteDialog:w,cliStopDialogOpen:M,cliStopTargetConv:T,onCancelCliStop:$,onStopCliNow:E,onSaveCliAndStop:F,toasts:D,onDismissToast:C,onClickToast:V,showOnboarding:J,onCloseOnboarding:I}){var R;return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(On,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:m,onNewChat:f,onSwitchSession:p,onRefreshHistory:x,onResumeSavedSession:b}),S&&t.jsx(Jm,{activeConv:S,ideEntry:A,ides:r,connectionStates:u,actionLogs:h,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:j,setActionLogs:P,isStandalone:k,userName:g,onOpenHistory:N,onConversationChange:v,onClose:w}),M&&T&&(Ye(T)||Ve(T))&&t.jsx(Zm,{activeConv:T,canSaveAndStop:Ye(T)&&!Ve(T)&&!!((R=T.resume)!=null&&R.supported),onCancel:$,onStopNow:E,onSaveAndStop:F}),t.jsx(Xo,{toasts:D,onDismiss:C,onClickToast:V}),J&&t.jsx(qm,{onClose:I})]})}function ep({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:o,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(js,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const d=jt(c,{fallbackId:c.id}),m=n[c.id],f=c.version||c.daemonVersion||"unknown",p=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:d}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),p&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),m==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:p?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):m==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):m==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:p?"var(--status-danger)":"var(--status-warning)",background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:p?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(vt,{size:16})})]})}function tp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function to(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function rp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function np(){var ta,sa,ra,na,aa;const{sendCommand:e}=Ct(),s=Gs(),r=In(),n=ws(),[o,i]=ic(),c=o.get("activeTab"),d=((ta=r.state)==null?void 0:ta.openRemoteForTabKey)||null,m=((sa=r.state)==null?void 0:sa.openMachineId)||null,f=((ra=r.state)==null?void 0:ra.mobileSection)||null,p=Ko(),x=p.ides||[],b=p.initialLoaded??!0,{updateRouteChats:S,setToasts:A}=p,[u,h]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=p.toasts||[],l=p.wsStatus||"connected",j=p.isConnected??!0,P=p.connectionStates||{},k=p.showReconnected||!1,{groupAssignments:g,setGroupAssignments:N,focusedGroup:v,setFocusedGroup:w,groupActiveTabIds:M,setGroupActiveTabIds:T,groupTabOrders:$,setGroupTabOrders:E,groupSizes:F,setGroupSizes:D,isMobile:C,hasHydratedStoredLayout:V,hydrateStoredLayout:J}=Hu(),[I,R]=a.useState(!1),[B,z]=a.useState(!1),[Z,fe]=a.useState(null),[Pe,ke]=a.useState([]),[ve,Q]=a.useState(!1),[xe,W]=a.useState(null),[ee]=a.useState(()=>di()),[ne,oe]=a.useState([]),[he,te]=a.useState({}),[de,se]=a.useState({}),[pe,ae]=a.useState(null),[Ne,ge]=a.useState(null),[_,ue]=a.useState(null),X=a.useRef(null);zs("Dashboard",{ideCount:x.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(g).length,localMessageTabs:Object.keys(he).length,actionLogCount:ne.length});const ce=x.find(be=>be.type==="adhdev-daemon"),Ce=a.useMemo(()=>x.filter(be=>be.type==="adhdev-daemon").sort(Ln),[x]),Re=!!ce;a.useEffect(()=>{!ce||!(!ce.detectedIdes||!ce.availableProviders||!ce.recentLaunches||!ce.workspaces)||s(ce.id,{minFreshMs:3e4}).catch(()=>{})},[ce,s]);const me=(ce==null?void 0:ce.terminalBackend)||null,We=ce?jt(ce,{fallbackId:ce.id}):null,Be=(ce==null?void 0:ce.id)||null,{hiddenTabs:Ze,hideTab:Ge,toggleTab:gt,showTab:Xe,showAllTabs:ot}=wu(),{chatIdes:ut,conversations:Ue,visibleConversations:He,visibleTabKeys:It,resolveConversationBySessionId:ct,resolveConversationByTarget:pt}=Au({ides:x,connectionStates:P,localUserMessages:he,clearedTabs:de,hiddenTabs:Ze}),ft=a.useMemo(()=>Fs(x),[x]),dt=a.useRef(null),{containerRef:Tt,normalizedGroupAssignments:it,numGroups:q,isSplitMode:Te,groupedConvs:Ae,moveTabToGroup:Qe,closeGroup:K,handleResizeStart:O,splitTabRelative:G}=Xu({groupAssignments:g,setGroupAssignments:N,setFocusedGroup:w,setGroupActiveTabIds:T,setGroupTabOrders:E,groupSizes:F,setGroupSizes:D,isMobile:C,visibleConversations:He,visibleTabKeys:It}),H=a.useMemo(()=>{var Me,je;if(!C){if(pe){const we=Ue.find(Ke=>Ke.tabKey===pe);if(we)return we}return He[0]}const be=M[v];if(be){const we=Ue.find(Ke=>Ke.tabKey===be);if(we)return we}return((Me=Ae[v])==null?void 0:Me[0])||((je=Ae[0])==null?void 0:je[0])},[pe,C,M,v,Ue,Ae,He]);a.useEffect(()=>{if(C){dt.current=null;return}if(!(H!=null&&H.sessionId)){dt.current=null;return}const be=`${H.tabKey}:${H.sessionId}`;if(dt.current===be)return;const Me=()=>{if(document.visibilityState!=="visible"||dt.current===be)return;dt.current=be;const je=Ws(H,ft),we=Math.max(Date.now(),Ht(H),je.lastUpdated||0);e(H.daemonId||H.routeId,"mark_session_seen",{sessionId:H.sessionId,seenAt:we}).catch(()=>{})};if(document.visibilityState==="visible"){const je=setTimeout(Me,1500),we=()=>{document.visibilityState!=="visible"&&clearTimeout(je)};return document.addEventListener("visibilitychange",we),()=>{clearTimeout(je),document.removeEventListener("visibilitychange",we)}}else{const je=()=>{document.visibilityState==="visible"&&(setTimeout(Me,800),document.removeEventListener("visibilitychange",je))};return document.addEventListener("visibilitychange",je),()=>{document.removeEventListener("visibilitychange",je)}}},[H,C,ft,e]);const{requestedDesktopTabKey:ie,requestedMobileTabKey:Se,consumeRequestedActiveTab:Y}=Mu({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:ct,setSearchParams:i}),{remoteDialogConv:le,remoteDialogIdeEntry:$e,remoteDialogActiveConv:Le,setRemoteDialogActiveConv:Oe,openRemoteDialog:Fe,closeRemoteDialog:L}=Fu({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:d,requestedDesktopTabKey:ie,conversations:Ue,ides:x,resolveConversationByTarget:pt}),U=Le||le||H,re=!!U&&Ye(U)&&!Ve(U),ye=a.useMemo(()=>{if(!U||!re)return null;const be=U.daemonId||U.routeId||"",Me=wt(U);return`${be}:${Me}`},[U,re]),_e=a.useMemo(()=>He,[He]),Ie=C&&ee==="chat",ze=a.useMemo(()=>Ue.filter(be=>Ze.has(be.tabKey)),[Ue,Ze]),qe=a.useCallback(be=>{const Me=new URLSearchParams(o);Me.set("activeTab",be),i(Me,{replace:!0})},[o,i]),nt=a.useCallback(async(be,Me)=>$r(e,be,Me),[e]),De=a.useCallback(async(be,Me)=>{if(!Me.trim())return{ok:!1,error:"Choose a workspace path first."};try{const je=await e(be,"workspace_add",{path:Me.trim()});return je!=null&&je.success?{ok:!0}:{ok:!1,error:(je==null?void 0:je.error)||"Could not save workspace"}}catch(je){return{ok:!1,error:je instanceof Error?je.message:"Could not save workspace"}}},[e]),Pt=a.useCallback(async(be,Me,je)=>{var we;try{const Ke={ideType:Me,enableCdp:!0};(we=je==null?void 0:je.workspacePath)!=null&&we.trim()&&(Ke.workspace=je.workspacePath.trim());const mt=await e(be,"launch_ide",Ke);return!(mt!=null&&mt.success)&&(mt==null?void 0:mt.success)!==void 0?{ok:!1,error:(mt==null?void 0:mt.error)||"Could not launch IDE"}:(ue({machineId:be,kind:"ide",providerType:Me,workspacePath:(je==null?void 0:je.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Ke){return{ok:!1,error:Ke instanceof Error?Ke.message:"Could not launch IDE"}}},[e]),Ei=a.useCallback(async(be,Me,je,we)=>{var mt,Ns,ls;const Ke=Date.now();try{const At={cliType:je};(mt=we==null?void 0:we.workspacePath)!=null&&mt.trim()?At.dir=we.workspacePath.trim():we!=null&&we.workspaceId&&(At.workspaceId=we.workspaceId),(Ns=we==null?void 0:we.resumeSessionId)!=null&&Ns.trim()&&(At.resumeSessionId=we.resumeSessionId.trim()),Array.isArray(we==null?void 0:we.cliArgs)&&we.cliArgs.length>0&&(At.cliArgs=we.cliArgs),(ls=we==null?void 0:we.initialModel)!=null&&ls.trim()&&(At.initialModel=we.initialModel.trim());const xt=await e(be,"launch_cli",At),yt=(xt==null?void 0:xt.result)||xt,Ss=(yt==null?void 0:yt.sessionId)||(yt==null?void 0:yt.id);return xt!=null&&xt.success&&Ss?(qe(Ss),{ok:!0}):xt!=null&&xt.success?(ue({machineId:be,kind:Me,providerType:je,workspacePath:(we==null?void 0:we.workspacePath)||null,resumeSessionId:(we==null?void 0:we.resumeSessionId)||null,startedAt:Ke}),{ok:!0}):{ok:!1,error:(xt==null?void 0:xt.error)||(yt==null?void 0:yt.error)||`Could not launch ${Me.toUpperCase()} session`}}catch(At){return sp(At)?(ue({machineId:be,kind:Me,providerType:je,workspacePath:(we==null?void 0:we.workspacePath)||null,resumeSessionId:(we==null?void 0:we.resumeSessionId)||null,startedAt:Ke}),{ok:!0}):{ok:!1,error:At instanceof Error?At.message:`Could not launch ${Me.toUpperCase()} session`}}},[qe,e]),$i=a.useCallback(async(be,Me)=>{if(!be||!Me)return[];try{const je=await e(be,"list_saved_sessions",{providerType:Me,kind:"cli",limit:30}),we=(je==null?void 0:je.result)??je;return Array.isArray(we==null?void 0:we.sessions)?we.sessions:[]}catch(je){return console.error("List saved sessions failed",je),[]}},[e]);a.useEffect(()=>{var we;if(!_)return;const be=to(_.workspacePath),Me=x.find(Ke=>{var xt,yt,Ss,oa;if(!Ke||Ke.type==="adhdev-daemon"||tp(Ke.daemonId||Ke.id)!==_.machineId||(Hs(Ke)?"cli":xs(Ke)?"acp":"ide")!==_.kind||String(Ke.agentType||Ke.type||"")!==_.providerType)return!1;if(_.resumeSessionId)return String(Ke.providerSessionId||"")===_.resumeSessionId;if(be){const Or=to(Ke.workspace||Ke.runtimeWorkspaceLabel);return Or?Or===be:!1}return Number(Ke.lastUpdated||Ke._lastUpdate||Ke.timestamp||((oa=(Ss=(yt=(xt=Ke.activeChat)==null?void 0:xt.messages)==null?void 0:yt.at)==null?void 0:Ss.call(yt,-1))==null?void 0:oa.timestamp)||0)>=_.startedAt-5e3});if(!Me)return;const je=typeof Me.sessionId=="string"&&Me.sessionId?Me.sessionId:typeof Me.instanceId=="string"&&Me.instanceId?Me.instanceId:(we=Ue.find(Ke=>Ke.routeId===Me.id))==null?void 0:we.sessionId;je&&(ue(null),qe(je))},[Ue,qe,x,_]),a.useEffect(()=>{if(!_)return;const be=window.setTimeout(()=>{ue(Me=>!Me||Me.startedAt!==_.startedAt?Me:null)},45e3);return()=>window.clearTimeout(be)},[_]),ju({visibleConversations:He,clearedTabs:de,setClearedTabs:se,setActionLogs:oe}),_u({ides:x,sendDaemonCommand:e,setToasts:A,setLocalUserMessages:te,resolveConversationByTarget:pt});const{isRefreshingHistory:Bi,handleRefreshHistory:Ki}=Ba({sendDaemonCommand:e,activeConv:H,chats:(na=x.find(be=>be.id===(H==null?void 0:H.routeId)))==null?void 0:na.chats,updateRouteChats:S,setToasts:A,setLocalUserMessages:te,setClearedTabs:se}),{isCreatingChat:Wi,isRefreshingHistory:Oi,handleSwitchSession:Hi,handleNewChat:Ui,handleRefreshHistory:zi}=Ba({sendDaemonCommand:e,activeConv:U,chats:(aa=x.find(be=>be.id===(U==null?void 0:U.routeId)))==null?void 0:aa.chats,updateRouteChats:S,setToasts:A,setLocalUserMessages:te,setClearedTabs:se}),Wr=a.useCallback(async()=>{if(!(!U||!re||ve)){Q(!0);try{const be=U.daemonId||U.routeId,Me=wt(U),je=await e(be,"list_saved_sessions",{agentType:Me,providerType:Me,kind:"cli",limit:50}),we=(je==null?void 0:je.result)??je;ke(Array.isArray(we==null?void 0:we.sessions)?we.sessions:[])}catch(be){console.error("Refresh saved sessions failed",be),ke([])}finally{Q(!1)}}},[U,ve,re,e]);a.useEffect(()=>{if(!I){X.current=null;return}if(!re){X.current=null,ke([]),Q(!1);return}!ye||ve||X.current!==ye&&(X.current=ye,Wr())},[Wr,I,ve,re,ye]);const Fi=a.useCallback(async be=>{if(!U||!re||!be.providerSessionId||!be.workspace)return;const Me=U.daemonId||U.routeId,je=wt(U);try{W(be.providerSessionId);const we=await e(Me,"launch_cli",{cliType:je,dir:be.workspace,resumeSessionId:be.providerSessionId,initialModel:be.currentModel}),Ke=(we==null?void 0:we.result)??we,mt=typeof(Ke==null?void 0:Ke.sessionId)=="string"?Ke.sessionId:typeof(Ke==null?void 0:Ke.id)=="string"?Ke.id:"";mt&&i(Ns=>{const ls=new URLSearchParams(Ns);return ls.set("activeTab",mt),ls},{replace:!0}),R(!1)}catch(we){console.error("Resume saved session failed",we)}finally{W(null)}},[U,re,e,i]);zu({urlActiveTab:C&&!Ie?c:null,conversations:Ue,resolveConversationBySessionId:ct,normalizedGroupAssignments:it,hasHydratedStoredLayout:C&&!Ie?V:!0,hydrateStoredLayout:C&&!Ie?J:()=>{},setGroupActiveTabIds:T,setFocusedGroup:w,setSearchParams:i,historyModalOpen:I,activeConv:H,isRefreshingHistory:Bi,ides:x,handleRefreshHistory:Ki});const Jn=a.useCallback(async(be,Me)=>{const je=Me||Z||H;if(!je||!Ye(je)&&!Ve(je))return;const we=wt(je),Ke=je.routeId||je.daemonId||"";try{await e(Ke,"stop_cli",{cliType:we,targetSessionId:je.sessionId,mode:be})}catch(mt){console.error("Stop CLI failed:",mt)}},[H,Z,e]),Vi=a.useCallback(async be=>{const Me=be||H;!Me||!Ye(Me)&&!Ve(Me)||(fe(Me),z(!0))},[H]),Gi=a.useMemo(()=>!H||!Ye(H)||Ve(H)?null:vs(H),[H]),qi=a.useCallback(async be=>{if(!(!H||!Ye(H)||Ve(H)||vs(H)===be))try{await e(Ut(H)||H.routeId,"set_cli_view_mode",{targetSessionId:H.sessionId,cliType:wt(H),mode:be})}catch(je){rp(je)?console.warn("Skipped CLI view mode switch:",je instanceof Error?je.message:String(je)):console.error("Failed to switch CLI view mode:",je)}},[H,e]),{versionMismatchDaemons:Yi,hasRequiredVersionDaemons:Zn,appVersion:Xi,versionBannerDismissed:Ji,setVersionBannerDismissed:Zi,upgradingDaemons:Qi,handleBannerUpgrade:ec}=Ju({ides:x,sendDaemonCommand:e}),Qn=a.useCallback(be=>{ae(be.tabKey),i(Me=>{const je=new URLSearchParams(Me),we=ql(be);return we?je.set("activeTab",we):je.delete("activeTab"),je},{replace:!0})},[i]),ea=a.useCallback(be=>{Xe(be.tabKey),Qn(be)},[Qn,Xe]),tc=a.useCallback(be=>{Ge(be.tabKey)},[Ge]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(wd,{wsStatus:l,showReconnected:k}),t.jsx(jd,{terminalBackend:me,isStandalone:Re,machineLabel:We,machineKey:Be}),(!Ji||Zn)&&t.jsx(ep,{daemons:Yi,targetVersion:Xi,required:Zn,upgradingDaemons:Qi,onUpgrade:ec,onDismiss:()=>Zi(!0)}),t.jsx(Gm,{showMobileChatMode:Ie,isMobile:C,activeConv:H,chatIdes:ut,wsStatus:l,isConnected:j,onOpenHistory:be=>{be&&Oe(be),R(!0)},onOpenRemote:Fe,onStopCli:Vi,activeCliViewMode:Gi,onSetActiveCliViewMode:qi,mobileChatConversations:_e,ides:x,actionLogs:ne,sendDaemonCommand:e,setLocalUserMessages:te,setActionLogs:oe,isStandalone:Re,initialDataLoaded:b,userName:p.userName,requestedMobileTabKey:Se,onRequestedMobileTabConsumed:Y,requestedMachineId:m,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:f,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:Tt,isSplitMode:Te,numGroups:q,groupSizes:F,groupedConvs:Ae,clearedTabs:de,focusedGroup:v,setFocusedGroup:w,moveTabToGroup:Qe,splitTabRelative:G,closeGroup:K,handleResizeStart:O,groupActiveTabIds:M,setGroupActiveTabIds:T,groupTabOrders:$,setGroupTabOrders:E,toggleHiddenTab:gt,visibleConversations:He,hiddenConversations:ze,requestedDesktopTabKey:ie,onRequestedDesktopTabConsumed:Y,onDesktopActiveTabChange:ae,onHideConversation:tc,onShowHiddenConversation:ea,onShowAllHiddenConversations:ot,scrollToBottomRequest:Ne,machineEntries:Ce,onBrowseMachineDirectory:nt,onSaveMachineWorkspace:De,onLaunchMachineIde:Pt,onLaunchMachineProvider:Ei,onListMachineSavedSessions:$i}),t.jsx("style",{children:`
|
|
59
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
60
|
+
`}),t.jsx(Qm,{historyModalOpen:I,historyTargetConv:U,ides:x,isHistoryCreatingChat:Wi,isHistoryRefreshingHistory:re?!1:Oi,savedHistorySessions:Pe,isSavedHistoryLoading:ve,isResumingSavedHistorySessionId:xe,onCloseHistory:()=>R(!1),onNewHistoryChat:Ui,onSwitchHistorySession:Hi,onRefreshHistory:re?Wr:zi,onResumeSavedHistorySession:Fi,remoteDialogConv:le,remoteDialogIdeEntry:$e,connectionStates:P,actionLogs:ne,localUserMessages:he,sendDaemonCommand:e,setLocalUserMessages:te,setActionLogs:oe,isStandalone:Re,userName:p.userName,onOpenRemoteHistory:be=>{be&&Oe(be),R(!0)},onRemoteConversationChange:Oe,onCloseRemoteDialog:L,cliStopDialogOpen:B,cliStopTargetConv:Z,onCancelCliStop:()=>{z(!1),fe(null)},onStopCliNow:async()=>{z(!1),await Jn("hard",Z),fe(null)},onSaveCliAndStop:async()=>{z(!1),await Jn("save",Z),fe(null)},toasts:y,onDismissToast:be=>A(Me=>Me.filter(je=>je.id!==be)),onClickToast:be=>{if(be.targetKey){const Me=pt(be.targetKey);Me&&(w(it.get(Me.tabKey)??0),ea(Me),ge({tabKey:Me.tabKey,nonce:Date.now()}))}},showOnboarding:u,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}h(!1)}})]})}function ap({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[d,m]=a.useState(null),[f,p]=a.useState(null),[x,b]=a.useState(!1),[S,A]=a.useState(null),[u,h]=a.useState(!1),[y,l]=a.useState(""),j=a.useRef(null),P=a.useCallback(I=>{j.current=I},[]),k=a.useCallback((I,R,B=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:I,message:R}]),setTimeout(()=>{var z;return(z=o.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),B&&tt.showToast(R,I==="error"||I==="warn"?"warning":"success")},[o]),g=a.useCallback(I=>{const R=I instanceof Error?I.message:String(I||"");return R.includes("P2P command timeout")||R.includes("P2P not connected")||R.includes("P2P not available")},[]),N=a.useCallback(async(I,R)=>{var B;if(!e||d)return!1;m(I),k("info",`Launching ${et(I)}${R!=null&&R.workspace?` in ${R.workspace}`:""}...`);try{const z={ideType:I,enableCdp:!0};(B=R==null?void 0:R.workspace)!=null&&B.trim()?z.workspace=R.workspace.trim():R!=null&&R.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const Z=await r(e,"launch_ide",z);return k(Z!=null&&Z.success?"info":"error",Z!=null&&Z.success?`${et(I)} launched`:`Failed: ${Z==null?void 0:Z.error}`,!0),!!(Z!=null&&Z.success)}catch(z){return k("error",`Launch error: ${z.message}`,!0),!1}finally{m(null)}},[e,d,k,r]),v=a.useCallback(async I=>{if(!e)return{success:!1};const{cliType:R,dir:B,workspaceId:z,useDefaultWorkspace:Z,useHome:fe,argsStr:Pe,model:ke,resumeSessionId:ve}=I;if(!R)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const Q=Pe?Pe.split(/\s+/).filter(Boolean):void 0,xe=(B==null?void 0:B.trim())||(z?"(saved id)":Z?"(default workspace)":fe?"(home)":"");k("info",`Launching ${R}${xe?` in ${xe}`:""}${ke?` (model: ${ke})`:""}...`),p(R);try{const W={cliType:R,cliArgs:Q,initialModel:ke||void 0};B!=null&&B.trim()?W.dir=B.trim():z?W.workspaceId=z:Z?W.useDefaultWorkspace=!0:fe&&(W.useHome=!0),ve&&(W.resumeSessionId=ve);const ee=await r(e,"launch_cli",W),ne=(ee==null?void 0:ee.result)||ee;return ee!=null&&ee.success?(k("info",`${R} launched`,!0),(ne==null?void 0:ne.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(ne==null?void 0:ne.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ne==null?void 0:ne.sessionId}):(k("error",`Failed: ${(ee==null?void 0:ee.error)||(ne==null?void 0:ne.error)}`,!0),(ee==null?void 0:ee.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&A({cliType:R,argsStr:Pe,model:ke}),{success:!1,sessionId:ne==null?void 0:ne.sessionId})}catch(W){return g(W)?(k("warn",`${R} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${W.message}`,!0),{success:!1})}finally{p(null)}},[e,k,g,r]),w=a.useCallback(async(I,R,B,z)=>e?I?R.trim()?v({cliType:I,dir:R,argsStr:B,model:z}):(A({cliType:I,argsStr:B,model:z}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,v]),M=a.useCallback(async(I,R,B)=>{if(e&&window.confirm(`Stop ${I}?
|
|
61
|
+
This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:I,dir:R,targetSessionId:B});z!=null&&z.success?k("info",`${I} stopped`,!0):k("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){k("error",`Stop failed: ${z.message}`,!0)}},[e,k,r]),T=a.useCallback(async I=>{try{await r(I.daemonId,"restart_ide",{ideType:I.type}),k("info",`${et(I.type)} restart initiated`,!0)}catch(R){k("error",`Restart failed: ${R.message}`,!0)}},[k,r]),$=a.useCallback(async I=>{if(window.confirm(`Stop ${et(I.type)}?
|
|
62
|
+
This will disconnect CDP and optionally kill the process.`))try{const R=await r(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});R!=null&&R.success?k("info",`${et(I.type)} stopped`,!0):k("error",`Stop failed: ${(R==null?void 0:R.error)||"Unknown error"}`,!0)}catch(R){k("error",`Stop failed: ${R.message}`,!0)}},[k,r]),E=a.useCallback(async()=>{if(e)try{const I=await r(e,"detect_ides",{});k("info",`Found ${((I==null?void 0:I.result)||[]).length} IDE(s)`,!0)}catch(I){k("error",`Detection failed: ${I.message}`,!0)}},[e,k,r]),F=a.useCallback(async I=>{if(!e||!I.trim())return!1;b(!0);try{const R=await r(e,"workspace_add",{path:I.trim()});return R!=null&&R.success?(k("info",`Workspace added: ${I.trim()}`),!0):(k("error",(R==null?void 0:R.error)||"workspace_add failed"),!1)}catch(R){return k("error",R.message),!1}finally{b(!1)}},[e,k,r]),D=a.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const R=await r(e,"workspace_remove",{id:I});R!=null&&R.success?k("info","Workspace removed",!0):k("error",(R==null?void 0:R.error)||"workspace_remove failed",!0)}catch(R){k("error",R.message,!0)}finally{b(!1)}}},[e,k,r]),C=a.useCallback(async I=>{var R;if(e){b(!0);try{const B=await r(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(B!=null&&B.success){k("info",I?"Default workspace updated":"Default workspace cleared",!0);const z=typeof B.defaultWorkspacePath=="string"?B.defaultWorkspacePath:"";z&&((R=j.current)==null||R.call(j,z))}else k("error",(B==null?void 0:B.error)||"workspace_set_default failed",!0)}catch(B){k("error",B.message,!0)}finally{b(!1)}}},[e,k,r]),V=a.useCallback(async I=>{var B;if(!e||!I.trim())return;const R=I.trim();b(!0);try{const z=await r(e,"workspace_set_default",{path:R});z!=null&&z.success?(k("info","Default workspace set from history"),(B=j.current)==null||B.call(j,R)):k("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){k("error",z.message)}finally{b(!1)}},[e,k,r]),J=a.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(I){k("warn",`Live nickname updated, but account sync failed: ${I.message}`)}k("info",`Nickname set to "${y||"(cleared)"}"`),h(!1)}catch(I){k("error",`Failed: ${I.message}`)}},[e,y,s,k,n,r]);return{logs:i,launchingIde:d,launchingAgentType:f,workspaceBusy:x,launchPick:S,setLaunchPick:A,editingNickname:u,setEditingNickname:h,nicknameInput:y,setNicknameInput:l,addLog:k,handleLaunchIde:N,runLaunchCliCore:v,handleLaunchCli:w,handleStopCli:M,handleRestartIde:T,handleStopIde:$,handleDetectIdes:E,handleWorkspaceAdd:F,handleWorkspaceRemove:D,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:V,handleSaveNickname:J,setOnDefaultWorkspaceChanged:P}}function op({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var T;const{workspaceBusy:d,handleWorkspaceAdd:m,handleWorkspaceRemove:f,handleWorkspaceSetDefault:p}=i,[x,b]=a.useState(!1),[S,A]=a.useState(""),[u,h]=a.useState([]),[y,l]=a.useState(!1),[j,P]=a.useState(""),k=a.useCallback(async $=>{l(!0),P("");try{const E=await $r(c,e,$);A(E.path),h(E.directories)}catch(E){P(E instanceof Error?E.message:"Could not load folder")}finally{l(!1)}},[e,c]),g=a.useCallback(()=>{b(!0);const $=[...r.map(F=>F.workspace),...n.map(F=>F.workspace),...o.map(F=>F.workspace)],E=Er(s.platform,Dr($,s.defaultWorkspacePath,(s.workspaces||[]).map(F=>F.path)));k(E)},[o,n,r,k,s.defaultWorkspacePath,s.platform,s.workspaces]),N=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,w=N&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,M=((T=s.loadavg)==null?void 0:T[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Js,{icon:t.jsx(wo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?dl(s.uptime):"Waiting…"}),t.jsx(Js,{icon:t.jsx(kt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Js,{icon:t.jsx(Mr,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Js,{icon:t.jsx(_c,{size:16}),label:"ACPs",value:`${o.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(xa,{value:N?Math.min(Math.round(M/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:N?`${M.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(xa,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:N?`${Fr(s.totalMem-v)} / ${Fr(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Fr(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(gs,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:d,value:s.defaultWorkspaceId||"",onChange:$=>void p($.target.value===""?null:$.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map($=>t.jsx("option",{value:$.id,children:$.label||$.path},$.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:d,onClick:g,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map($=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[$.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Pr($.path,$.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:$.path,children:$.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:d,onClick:()=>void f($.id),children:"Remove"})]},$.id))})]}),x&&t.jsx(Br,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:u,busy:y,error:j,confirmLabel:"Add workspace",onClose:()=>b(!1),onNavigate:$=>{k($)},onConfirm:$=>{(async()=>{if(!$)return;await m($)&&b(!1)})()}})]})}function ip(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function cp(e,s,r){const n=[];for(const[o,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const d=s.find(m=>m.type===o);n.push({type:o,displayName:(d==null?void 0:d.displayName)||o,icon:(d==null?void 0:d.icon)||"",category:(d==null?void 0:d.category)||"unknown",schema:c,values:e.values[o]||{}})}return n}const so=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],lp=[{value:"codex-cli",label:"Codex CLI",desc:"OpenAI o3/gpt-5.4",color:"#22c55e"},{value:"claude-cli",label:"Claude Code",desc:"Anthropic Claude",color:"#a855f7"},{value:"gemini-cli",label:"Gemini CLI",desc:"Google Gemini",color:"#3b82f6"}];function dp({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,d]=a.useState("codex-cli"),[m,f]=a.useState([]),[p,x]=a.useState(""),[b,S]=a.useState([]),[A,u]=a.useState(""),h=a.useRef(null),y=a.useRef(null),l=v=>{f(w=>w.includes(v)?w.filter(M=>M!==v):[...w,v])},j=()=>f([...so]),P=()=>f([]);a.useEffect(()=>{var v;(v=h.current)==null||v.scrollIntoView({behavior:"smooth"})},[b]),a.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const k=a.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&o==="running"&&(i("done"),S(w=>[...w,`
|
|
63
|
+
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,o]),g=async()=>{if(m.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,p?`💬 Comment: ${p}`:"",""]),u("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...p?{comment:p}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(S(w=>[...w,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),u((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),u((v==null?void 0:v.message)||"Connection failed")}}},N=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),S(v=>[...v,`
|
|
64
|
+
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[85vh] overflow-hidden rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:lp.map(v=>t.jsxs("button",{onClick:()=>d(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:j,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:so.map(v=>t.jsxs("button",{onClick:()=>l(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(v)?"☑ ":"☐ ",v]},v))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:p,onChange:v=>x(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(o==="running"||o==="done"||o==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[b.map((v,w)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},w)),o==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:h})]}),A&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&m.length>0&&`${m.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[o==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:g,disabled:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&t.jsx("button",{onClick:N,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),S([]),u("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function up({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var k;const i=s.filter(g=>g.category==="ide"),[c,d]=a.useState(((k=i[0])==null?void 0:k.type)||""),[m,f]=a.useState(""),[p,x]=a.useState(""),[b,S]=a.useState(!1),[A,u]=a.useState(""),[h,y]=a.useState(!1),l=g=>{const N=g.toLowerCase().replace(/[^a-z0-9-]/g,"");f(N),(!p||p===j(m))&&x(j(N))},j=g=>g.split("-").map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join(" "),P=async()=>{if(!(!m||!p||!c)){S(!0),u("");try{const g=await r(e,"provider_clone",{type:m,name:p,category:"ide",location:"user",cloneFrom:c});g!=null&&g.success||g!=null&&g.created?(y(!0),o==null||o(m)):u((g==null?void 0:g.error)||"Failed to create provider")}catch(g){u((g==null?void 0:g.message)||"Connection failed")}S(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:h?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:m})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(g=>t.jsxs("button",{onClick:()=>d(g.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===g.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===g.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:g.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===g.type?"#a78bfa":"var(--text-secondary)"},children:g.displayName})]},g.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:m,onChange:g=>l(g.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",m||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:p,onChange:g=>x(g.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),A&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})}),t.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:h?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:P,disabled:!m||!p||b,className:"machine-btn",style:{background:m&&p?"rgba(34,197,94,0.12)":void 0,borderColor:m&&p?"rgba(34,197,94,0.3)":void 0,color:m&&p?"#86efac":void 0,opacity:!m||!p||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function mp({machineId:e,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[d,m]=a.useState(null),[f,p]=a.useState("all"),[x,b]=a.useState(null),[S,A]=a.useState(!1),u=a.useCallback(async()=>{if(e){c(!0);try{const y=await r(e,"get_provider_settings",{}),l=ip(y);if(l){const j=cp(l,s);j.sort((P,k)=>P.category.localeCompare(k.category)||P.displayName.localeCompare(k.displayName)),o(j)}}catch{}c(!1)}},[e,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const h=async(y,l,j)=>{m(`${y}.${l}`),o(P=>P.map(k=>k.type===y?{...k,values:{...k.values,[l]:j}}:k));try{const P=await r(e,"set_provider_setting",{providerType:y,key:l,value:j});P!=null&&P.success||u()}catch{u()}m(null)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(y=>t.jsx("button",{onClick:()=>p(y),className:`machine-btn text-[10px] px-2 py-0.5 ${f===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>A(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:u,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(y=>y.category===f).length>1&&(()=>{const y=n.filter(k=>k.category===f),l=new Map;for(const k of y)for(const g of k.schema){if(g.type!=="boolean")continue;const N=l.get(g.key),v=!!(k.values[g.key]??g.default);N?(N.onCount+=v?1:0,N.total+=1):l.set(g.key,{label:g.label||g.key,onCount:v?1:0,total:1})}const j=[...l.entries()].filter(([,k])=>k.total===y.length);if(j.length===0)return null;const P=async(k,g)=>{for(const N of y)await h(N.type,k,g)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",y.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(([k,g])=>{const N=g.onCount===g.total,v=g.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:g.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",g.onCount,"/",g.total,")"]}),t.jsx("button",{onClick:()=>void P(k,!0),disabled:N,className:`machine-btn text-[9px] px-1.5 py-px ${N?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void P(k,!1),disabled:v,className:`machine-btn text-[9px] px-1.5 py-px ${v?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},k)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(y=>f==="all"||y.category===f).map(y=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:y.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:y.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:y.category==="acp"?"rgba(139,92,246,0.08)":y.category==="cli"?"rgba(59,130,246,0.08)":y.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:y.category==="acp"?"#a78bfa":y.category==="cli"?"#60a5fa":y.category==="ide"?"#86efac":"var(--status-warning)"},children:y.category}),y.category==="ide"&&t.jsx("button",{onClick:()=>b(s.find(l=>l.type===y.type)||{type:y.type,name:y.displayName,displayName:y.displayName,icon:y.icon,category:y.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:y.schema.map(l=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[l.label||l.key,d===`${y.type}.${l.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),l.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:l.description})]}),t.jsx("div",{className:"shrink-0",children:l.type==="boolean"?t.jsx("button",{onClick:()=>h(y.type,l.key,!(y.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:y.values[l.key]??l.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:y.values[l.key]??l.default?21:3}})}):l.type==="number"?t.jsx("input",{type:"number",value:Number(y.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:j=>{const P=parseInt(j.target.value)||0;l.min!==void 0&&P<l.min||l.max!==void 0&&P>l.max||h(y.type,l.key,P)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?t.jsx("select",{value:String(y.values[l.key]??l.default??""),onChange:j=>h(y.type,l.key,j.target.value),className:"machine-input text-[11px]",children:l.options.map(j=>t.jsx("option",{value:j,children:j},j))}):t.jsx("input",{type:"text",value:String(y.values[l.key]??l.default??""),onBlur:j=>h(y.type,l.key,j.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},y.type))}),x&&t.jsx(dp,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>b(null)}),S&&t.jsx(up,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),u()}})]})}function ro(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function pp({machineId:e,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,d]=a.useState([]),[m,f]=a.useState(0),[p,x]=a.useState(0),[b,S]=a.useState(!0),[A,u]=a.useState("debug"),h=a.useRef(null),y=a.useRef(!1);return a.useEffect(()=>{if(!e||!b)return;const l=async()=>{try{const[P,k]=await Promise.all([s(e,"get_logs",{count:200,minLevel:A,since:m}),s(e,"get_debug_trace",{count:120,since:p})]),g=(P==null?void 0:P.result)||P;if(P!=null&&P.success&&Array.isArray(g==null?void 0:g.logs)&&g.logs.length>0){n(w=>[...w,...g.logs.map(T=>({timestamp:T.ts,level:T.level,message:`[${T.category}] ${T.message}`}))].slice(-300));const v=Math.max(...g.logs.map(w=>w.ts));f(v)}const N=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(N==null?void 0:N.trace)){i(N.trace.slice(-120));const v=N.trace.reduce((w,M)=>Math.max(w,Number(M.ts||0)),p);v>p&&x(v)}}catch{}d(ss.list({limit:120}))};l();const j=setInterval(l,3e3);return()=>clearInterval(j)},[e,b,m,p,A,s]),a.useEffect(()=>{if(b&&(r.length>0||o.length>0||c.length>0)){const l=y.current?"smooth":"instant";setTimeout(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:l}),y.current=!0},50)}},[r.length,o.length,c.length,b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(l=>t.jsx("button",{onClick:()=>{u(l),n([]),f(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===l?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:l.toUpperCase()},l))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",o.length," web=",c.length]}),t.jsx("button",{onClick:()=>S(!b),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),d([]),f(0),x(0),ss.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((l,j)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:l.level==="error"?"#ef4444":l.level==="warn"?"var(--status-warning)":l.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(l.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:l.level==="error"?"ERR":l.level==="warn"?"WRN":l.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:l.message})]},`log-${j}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Structured daemon trace"}),o.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No trace entries yet. Run daemon with --dev or --trace."}),o.map(l=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),t.jsx("span",{children:l.level.toUpperCase()}),t.jsxs("span",{children:[l.category,".",l.stage]}),l.interactionId&&t.jsxs("span",{children:["ix=",l.interactionId]})]}),t.jsx("div",{children:ro(l.payload)})]},l.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(l=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),t.jsx("span",{children:l.kind}),l.topic&&t.jsxs("span",{children:["topic=",l.topic]}),l.interactionId&&t.jsxs("span",{children:["ix=",l.interactionId]})]}),t.jsx("div",{children:ro(l.payload)})]},l.id))]})]}),t.jsx("div",{ref:h})]})}function on(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function cn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function no(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function fp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function xp(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function hp(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function bp({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[d,m]=a.useState(!1),f=ui(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),p=f.diagnostics,x=f.loading,b=f.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(M=>[M.sessionId||M.id,M])),[s]),A=a.useCallback(async()=>{if(e){m(!0);try{const M=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),T=on(M);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");b(T.diagnostics||T.result||null),o("")}catch(M){const T=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";o(T)}finally{m(!1)}}},[b,e,r]);a.useEffect(()=>{!e||p||x||d||A()},[p,x,e,A,d]);const u=a.useCallback(async(M,T)=>{const $=`${M}:${T.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
65
|
+
This will terminate the hosted runtime.`))){c($);try{const E=await r(e,M,{sessionId:T.sessionId}),F=on(E);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Session host action failed");const D=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${D}: ${T.displayName}`,"success"),await A()}catch(E){const F=E instanceof Error?E.message:"Session host action failed";tt.showToast(F,"warning"),o(F)}finally{c(E=>E===$?null:E)}}},[e,A,r]),h=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
66
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),$=on(T);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Duplicate prune failed");const E=$.result||{},F=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,D=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;tt.showToast(`Pruned ${F} duplicate runtime(s) across ${D} group(s)`,"success"),await A()}catch(T){const $=T instanceof Error?T.message:"Duplicate prune failed";tt.showToast($,"warning"),o($)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,A,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((M,T)=>(T.lastActivityAt||0)-(M.lastActivityAt||0)),[p==null?void 0:p.sessions]),l=a.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:Li(y),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,y]),j=l.liveRuntimes,P=l.recoverySnapshots,k=l.inactiveRecords,g=a.useMemo(()=>hp(j),[j]),N=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),v=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[p==null?void 0:p.recentLogs]),w=(M,T)=>{var R;const $=i===`session_host_resume_session:${M.sessionId}`,E=i===`session_host_restart_session:${M.sessionId}`,F=i===`session_host_stop_session:${M.sessionId}`,D=Xn(M.meta),C=S.get(M.sessionId),V=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,J=T==="recovery"?"Recover":"Resume",I=Di(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(C==null?void 0:C.cliName)||M.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${xp(M.lifecycle)}`,children:M.lifecycle}),D&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:D})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((R=M.writeOwner)==null?void 0:R.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:fp(M.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(An,{size:11})," ",V]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",no(M.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",M)},children:$?`${J}ing…`:J}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",M)},children:E?"Restarting…":"Restart"}),T==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{u("session_host_stop_session",M)},children:F?"Stopping…":"Stop"})]})]})},M.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Live runtime status, next actions, and explicit recover/restart controls for hosted CLI sessions."})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[g>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{h()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${g})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{A()},disabled:x||d,children:[t.jsx(js,{size:13}),x||d?"Refreshing…":"Refresh"]})]})]}),n&&!p&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ns,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics unavailable"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),p&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:P.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:no(p.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:cn(p.hostStartedAt)})]})]}),v&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(ns,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[cn(v.timestamp),v.sessionId?` · ${v.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Mr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("live")}),j.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:j.map(M=>w(M,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Bt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("recovery")}),P.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:P.map(M=>w(M,"recovery"))})]}),k.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bs("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:k.map(M=>w(M,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(M=>{var $;const T=y.find(E=>E.sessionId===M.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||(($=S.get(M.sessionId))==null?void 0:$.cliName)||M.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:cn(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:p.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function gp({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/55 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function ln({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function dn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function yp({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),m=r.slice(0,4),p=Ds(e,"0.8.53"),x=b=>b==="ide"?"IDE":b==="cli"?"CLI":"ACP";return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(Kt,{size:13}),children:"Current Chats"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const S=gn(b);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(b),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:st(b)}),S>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Rn(S)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:is(b)})]},b.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(wo,{size:13}),children:"Recent Launches"}),t.jsx(dn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(b=>t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(b),children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:b.label}),t.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[x(b.kind),b.subtitle?` · ${b.subtitle}`:""]})]},b.id))})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ln,{icon:t.jsx(ns,{size:13}),children:"Daemon Update"}),t.jsx(dn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:p?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[t.jsx(js,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function vp(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const wp={ide:{label:"IDE",plural:"IDEs",accent:"border-blue-500/[0.12]"},cli:{label:"CLI",plural:"CLIs",accent:"border-violet-500/[0.12]"},acp:{label:"ACP Agent",plural:"ACP agents",accent:"border-emerald-500/[0.12]"}};function ur(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function jp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function un({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:m,initialWorkspacePath:f}){const p=ws(),{handleLaunchIde:x,handleStopCli:b,handleRestartIde:S,handleStopIde:A,handleDetectIdes:u,launchingIde:h,launchingAgentType:y,addLog:l}=c,[j,P]=a.useState(null),k=a.useCallback(L=>{L&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(L)}`})},[p]),g=wp[e],N=e==="ide",v=e==="acp",w=a.useMemo(()=>n.filter(L=>L.category===e&&(e==="ide"||L.installed!==!1)),[e,n]),M=a.useMemo(()=>new Map(w.map(L=>[L.type,L.displayName||L.type])),[w]),[T,$]=a.useState(""),[E,F]=a.useState(""),[D,C]=a.useState([]),[V,J]=a.useState(""),[I,R]=a.useState(""),[B,z]=a.useState([]),[Z,fe]=a.useState(!1),[Pe,ke]=a.useState(""),[ve,Q]=a.useState(!1),[xe,W]=a.useState(null),[ee,ne]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[oe,he]=a.useState(f||""),[te,de]=a.useState([]),[se,pe]=a.useState(!1),[ae,Ne]=a.useState(""),[ge,_]=a.useState([]),[ue,X]=a.useState(!1),[ce,Ce]=a.useState(""),Re=a.useRef(null),[me,We]=a.useState(null),Be=a.useRef("__home__"),[Ze,Ge]=a.useState("__home__"),[gt,Xe]=a.useState(!1),ot=a.useRef(0),ut=te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")),Ue=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ee&&ne(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){ne("__custom__"),he(f);return}m&&(ne(m),he(""))},[m,f]),a.useEffect(()=>{N||T&&(w.some(L=>L.type===T)||($(""),R("")))},[w,N,T]);const He=(()=>{if(ee==="__custom__")return oe.trim();if(!ee)return"";const L=(s.workspaces||[]).find(U=>U.id===ee);return(L==null?void 0:L.path)||""})(),It=a.useCallback(L=>{const U=Ue.current[L];U&&(clearTimeout(U),delete Ue.current[L]),de(re=>re.includes(L)?re.filter(ye=>ye!==L):re)},[]),ct=a.useRef(new Set),pt=a.useCallback(async L=>{if(d){X(!0),Ce("");try{const U=await $r(d,r,L);Ne(U.path),he(U.path),_(U.directories)}catch(U){Ce(U instanceof Error?U.message:"Could not load folder")}finally{X(!1)}}},[r,d]),ft=a.useCallback(()=>{if(!d)return;ne("__custom__"),pe(!0);const L=o.map(re=>re.workspace),U=Er(s.platform,Dr(oe.trim(),He,f,L,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));pt(U)},[oe,f,pt,s.defaultWorkspacePath,s.platform,s.workspaces,o,He,d]),dt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return;const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));if(re){ne(re.id),he("");return}ne("__custom__"),he(U)},[s.workspaces]),Tt=a.useCallback(L=>{const U=String(L.workspace||"").trim();if(!U)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ye=>ur(ye.path)===ur(U));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:U,useHome:!1}},[s.workspaces]),it=a.useCallback(async L=>{if(!d||!L||e!=="cli"){z([]),fe(!1),ke("");return}const U=ot.current+1;ot.current=U,fe(!0),ke("");try{const re=await d(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(ot.current!==U)return;const ye=(re==null?void 0:re.result)??re;z(Array.isArray(ye==null?void 0:ye.sessions)?ye.sessions:[])}catch(re){if(ot.current!==U)return;z([]),ke(re instanceof Error?re.message:"Could not load saved sessions")}finally{ot.current===U&&fe(!1)}},[e,r,d]),q=a.useMemo(()=>{if(e!=="cli"||!T)return null;const L=M.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:I||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:He,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,M,He,I,T]),Te=a.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(Pi(r,L))},[e,r]);a.useEffect(()=>{if(R(""),Te(T),e!=="cli"||!T){z([]),ke(""),fe(!1);return}it(T)},[e,Te,it,T]),a.useEffect(()=>{if(!I)return;const L=B.find(U=>U.providerSessionId===I);L!=null&&L.canResume||R("")},[B,I]);const Ae=a.useCallback((L,U)=>{Re.current=U,Be.current=L.selectedWorkspaceKey||"__home__",Ge(L.selectedWorkspaceKey||"__home__"),We(L)},[]),Qe=a.useCallback(()=>{Re.current&&(Xe(!0),Re.current().finally(()=>{Re.current=null,Xe(!1),We(null)}))},[]),K=a.useCallback(L=>{if(!L)return;de(re=>re.includes(L)?re:[...re,L]);const U=Ue.current[L];U&&clearTimeout(U),Ue.current[L]=setTimeout(()=>{de(re=>re.includes(L)?re.filter(ye=>ye!==L):re),delete Ue.current[L]},2e4)},[]);a.useEffect(()=>{for(const U of o)bt(U.status)!=="stopped"&&(te.includes(U.type)&&!ct.current.has(U.type)&&(ct.current.add(U.type),l("info",`${M.get(U.type)||U.type} launched`,!0)),It(U.type));const L=new Set(o.filter(U=>bt(U.status)!=="stopped").map(U=>U.type));ct.current.forEach(U=>{!te.includes(U)&&!L.has(U)&&ct.current.delete(U)})},[l,It,o,te,M]),a.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[O,G]=a.useState({}),[H,ie]=a.useState(null);a.useEffect(()=>{if(!N||!r||!d)return;(async()=>{try{const U=await d(r,"get_ide_extensions",{}),re=(U==null?void 0:U.result)||U;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&G(re.ideExtensions)}catch{}})()},[N,r,d]);const Se=L=>N?et(L.type):e==="cli"?L.cliName:L.acpName,Y=N?s.detectedIdes||[]:[],le=a.useCallback(async L=>{const U=(L==null?void 0:L.type)||T,re=(L==null?void 0:L.workspacePath)??He;if(N){await x(U,re?{workspace:re}:void 0)&&K(U);return}const ye=await c.runLaunchCliCore({cliType:U,dir:L!=null&&L.workspaceId?void 0:re||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!re,argsStr:(L==null?void 0:L.argsStr)??(E||void 0),model:(L==null?void 0:L.model)??(v&&V||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!v&&e==="cli"&&U===T&&I||void 0});if(ye.success||ye.pending){const _e=(L==null?void 0:L.argsStr)??E;!N&&(_e!=null&&_e.trim())&&(Ri(r,U,_e),Te(U)),K(U),ye.success&&ye.sessionId&&k(ye.sessionId)}},[c,x,v,N,E,V,Te,K,r,k,He,I,T]),$e=()=>{var ye;const L=N?et(T):M.get(T)||T,{options:U,selectedKey:re}=ts({machine:s,currentWorkspaceId:ee&&ee!=="__custom__"?ee:null,currentWorkspacePath:He});Ae({title:Yt("start-fresh",L),description:Xt("start-fresh"),confirmLabel:Jt("start-fresh"),busyLabel:Zt("start-fresh"),workspaceOptions:U,selectedWorkspaceKey:re,details:[{label:"Mode",value:g.label},{label:"Provider",value:L},...!N&&e==="cli"&&I?[{label:"Resume",value:((ye=B.find(_e=>_e.providerSessionId===I))==null?void 0:ye.title)||I}]:[],...!N&&E.trim()?[{label:"Arguments",value:E.trim()}]:[],...v&&V.trim()?[{label:"Model",value:V.trim()}]:[]]},async()=>{const _e=U.find(Ie=>Ie.key===Be.current);_e!=null&&_e.workspaceId?(ne(_e.workspaceId),he("")):_e!=null&&_e.workspacePath?(ne("__custom__"),he(_e.workspacePath)):(ne(""),he("")),await le({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Le=L=>{N?A(L):b(L.type,L.workspace,L.id)},Oe=a.useCallback(async(L,U,re=!1)=>{if(L.mode===U){re&&L.sessionId&&k(L.sessionId);return}if(!d||!L.sessionId){re&&L.sessionId&&k(L.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:U}),re&&k(L.sessionId)}catch(ye){jp(ye)?console.warn("Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},[r,k,d]),Fe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ee,onChange:L=>{const U=L.target.value;if(ne(U),U==="__custom__"&&d){ft();return}U!=="__custom__"&&he("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(L=>t.jsxs("option",{value:L.id,children:[L.id===s.defaultWorkspaceId?"⭐ ":"",Pr(L.path,L.label)]},L.id)),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ee==="__custom__"&&(d?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:ft,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:oe,onChange:L=>he(L.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ee==="__custom__"?He?t.jsx("span",{className:"font-mono truncate block",title:He,children:He}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":He?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ee===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:He,children:He})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${g.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",g.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:N?Y.length>0?Y.map(L=>{const U=o.find(ze=>(ze.type||"").toLowerCase()===(L.type||"").toLowerCase()&&bt(ze.status)!=="stopped"),re=L.running||!!U,ye=!!U&&U.cdpConnected,_e=te.includes(L.type||L.id||""),Ie=T===(L.type||"");return t.jsxs("button",{onClick:()=>{if(ye&&U){const ze=U.sessionId;ze?p(`/dashboard?activeTab=${encodeURIComponent(ze)}`,{state:{openRemoteForTabKey:ze}}):p("/dashboard",{state:{openRemoteForTabKey:U.id}});return}_e||$(ze=>ze===(L.type||"")?"":L.type||"")},disabled:!!h||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ye?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ie?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:h&&h!==L.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(L.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ye?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||et(L.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-green-400":_e?"text-orange-400":Ie?"text-accent-primary":"text-text-muted"}`,children:ye?"Open Session":_e?"Starting...":Ie?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Cc,{size:14})," Scan System"]})]}):w.length>0?w.map(L=>{const U=T===L.type,re=te.includes(L.type),_e=!!o.find(Ie=>Ie.type===L.type&&bt(Ie.status)!=="stopped");return t.jsxs("button",{onClick:()=>$(Ie=>Ie===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${U?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),_e&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":U?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":U?"Configure":"Select"})]})]},L.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(N?Y.find(L=>L.type===T):w.find(L=>L.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:N?et(T):M.get(T)||T})]}),Fe,!N&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume saved history"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void it(T),disabled:!T||Z,children:Z?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{T&&(Q(!0),it(T))},disabled:!T,children:Go()})]})]}),I?(()=>{const L=B.find(U=>U.providerSessionId===I);return L?t.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:L.title||L.providerSessionId}),t.jsx("div",{className:"font-mono break-all",children:L.providerSessionId}),t.jsx("div",{children:L.workspace||"Workspace unknown"})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>R(""),children:"Clear"})]})}):null})():t.jsx("div",{className:"text-[10px] text-text-muted",children:"Start fresh, or choose saved history when you want continuity."}),Pe&&t.jsx("div",{className:"text-[10px] text-red-400",children:Pe})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:V,onChange:L=>J(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:E,onChange:L=>F(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),D.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:D.map(L=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(L),title:L,children:L},L))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:$e,disabled:!!y||!!h||te.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===T||h===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+te.filter(L=>!o.some(U=>U.type===L&&bt(U.status)!=="stopped")).length,")"]}),o.length===0&&ut.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",g.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ut.map(L=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:N?et(L):M.get(L)||L}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===L?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${L}`)),o.map(L=>{const U=N?L:null,re=v?L:null,ye=!N&&!v?L:null,_e=bt(L.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(L.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Se(L),(U==null?void 0:U.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",U.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:L.workspace||"—"}),(re==null?void 0:re.currentModel)&&t.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&t.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ye==null?void 0:ye.mode)&&t.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ye.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ye.runtimeKey}`),P(ye.runtimeKey||null),window.setTimeout(()=>{P(ze=>ze===ye.runtimeKey?null:ze)},1200)},children:j===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&t.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:vp(ye.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),N&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ie=L.sessionId;if(Ie){p(`/dashboard?activeTab=${encodeURIComponent(Ie)}`,{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:L.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(kt,{size:13})}),t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",{options:ze,selectedKey:qe}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-ide",et(L.type)),description:Xt("restart-ide"),confirmLabel:Jt("restart-ide"),busyLabel:Zt("restart-ide"),workspaceOptions:ze,selectedWorkspaceKey:qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:et(L.type)}]},async()=>{const nt=ze.find(Pt=>Pt.key===Be.current),De=(nt==null?void 0:nt.workspacePath)??"";if(De&&De!==Ie){await le({type:L.type,workspacePath:De});return}await S(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(js,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:t.jsx(Kt,{size:14})}),ye&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[ye.mode&&t.jsx(Kn,{mode:ye.mode,onChange:Ie=>void Oe(ye,Ie,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&k(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ye.mode==="chat"?t.jsx(Kt,{size:14}):t.jsx(kt,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Ie=L.workspace||"",ze=N?et(L.type):Se(L),{options:qe,selectedKey:nt}=ts({machine:s,currentWorkspacePath:Ie});Ae({title:Yt("restart-stopped",ze),description:Xt("restart-stopped"),confirmLabel:Jt("restart-stopped"),busyLabel:Zt("restart-stopped"),workspaceOptions:qe,selectedWorkspaceKey:nt,details:[{label:"Mode",value:g.label},{label:"Provider",value:ze}]},async()=>{const De=qe.find(Pt=>Pt.key===Be.current);await le({type:L.type,workspaceId:(De==null?void 0:De.workspaceId)??null,workspacePath:(De==null?void 0:De.workspacePath)??"",useHome:!(De!=null&&De.workspaceId)&&!(De!=null&&De.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:te.includes(L.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:te.includes(L.type)?"⏳":t.jsx(_n,{size:14})}):t.jsx("button",{onClick:()=>Le(L),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(vt,{size:14})})]})]}),U&&U.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:U.aiAgents.map(Ie=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${To(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",bt(Ie.status)]},Ie.id))}),U&&(O[U.type]||[]).length>0&&d&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(O[U.type]||[]).map(Ie=>t.jsxs("button",{disabled:H===`${U.type}.${Ie.type}`,onClick:async()=>{const ze=`${U.type}.${Ie.type}`;ie(ze);try{await d(r,"set_ide_extension",{ideType:U.type,extensionType:Ie.type,enabled:!Ie.enabled}),G(qe=>({...qe,[U.type]:(qe[U.type]||[]).map(nt=>nt.type===Ie.type?{...nt,enabled:!nt.enabled}:nt)}))}catch(qe){console.error("Extension toggle failed:",qe)}finally{ie(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Ie.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},L.id)})]}),se&&d&&t.jsx(Br,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ae,directories:ge,busy:ue,error:ce,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:L=>{pt(L)},onConfirm:L=>{he(L),ne("__custom__"),pe(!1)}}),me&&t.jsx(qn,{title:me.title,description:me.description,details:me.details,workspaceOptions:me.workspaceOptions,selectedWorkspaceKey:Ze,onWorkspaceChange:L=>{Be.current=L,Ge(L)},confirmLabel:me.confirmLabel,busyLabel:me.busyLabel,busy:gt,onConfirm:Qe,onCancel:()=>{Re.current=null,We(null)}}),ve&&q&&t.jsx(On,{activeConv:q,ides:[],isCreatingChat:!1,isRefreshingHistory:Z,savedSessions:B,isSavedSessionsLoading:Z,isResumingSavedSessionId:xe,onClose:()=>Q(!1),onNewChat:()=>{R(""),Q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{it(T)},onResumeSavedSession:L=>{if(!L.canResume||xe)return;const U=Tt(L);R(L.providerSessionId),dt(L),W(L.providerSessionId),Q(!1),le({type:L.providerType,workspaceId:U.workspaceId,workspacePath:U.workspacePath,useHome:U.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{W(re=>re===L.providerSessionId?null:re)})}})]})}const ao=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function kp({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:p,sendDaemonCommand:x}){var u;const[b,S]=a.useState(m);a.useEffect(()=>{S(m)},[m]);const A=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:ao.map(h=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${b===h.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(h.id),children:[t.jsx("span",{children:h.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${b===h.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[h.id]})]},h.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(u=ao.find(h=>h.id===b))==null?void 0:u.helper})]}),b==="ide"&&t.jsx(un,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="cli"&&t.jsx(un,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p}),b==="acp"&&t.jsx(un,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:p})]})}function Np({onNicknameSynced:e}={}){var oe,he,te,de,se,pe,ae,Ne,ge;const{id:s}=cc(),r=ws(),n=In(),{sendCommand:o}=Ct(),i=Gs(),c=Ko(),d=c.ides||[],m=c.initialLoaded??!0,f=d.find(_=>_.id===s&&_.type==="adhdev-daemon"),p=d.some(_=>_.type==="adhdev-daemon"),[x,b]=a.useState("workspace"),[S,A]=a.useState("ide"),u=a.useRef(null),[h,y]=a.useState(null),l=a.useRef("__home__"),[j,P]=a.useState("__home__"),[k,g]=a.useState(!1),N=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),bu(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},w=ap({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:N});a.useEffect(()=>tt.onToast(ue=>{c.setToasts(ce=>{if(ce.some(me=>me.message===ue.message&&ue.timestamp-me.timestamp<3e3))return ce;const Re={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...ce.slice(-4),Re]});const X=ue.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(Ce=>Ce.id!==ue.id)),X)}),[c]);const M=(f==null?void 0:f.availableProviders)||[],T={};for(const _ of M)T[_.type]=_.icon;const $=_=>T[_]||"",E=f?{id:f.id,hostname:Ao(f,{fallbackId:f.id}),platform:((oe=f.machine)==null?void 0:oe.platform)||"unknown",arch:((he=f.machine)==null?void 0:he.arch)||"",cpus:((te=f.machine)==null?void 0:te.cpus)||0,totalMem:((de=f.machine)==null?void 0:de.totalMem)||0,freeMem:(se=f.machine)==null?void 0:se.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ae=f.machine)==null?void 0:ae.loadavg,uptime:(Ne=f.machine)==null?void 0:Ne.uptime,release:((ge=f.machine)==null?void 0:ge.release)||"",cdpConnected:!!f.cdpConnected,machineNickname:f.machineNickname||null,p2p:f.p2p?{screenshotActive:!1,...f.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:f.detectedIdes||[],workspaces:f.workspaces||[],defaultWorkspaceId:f.defaultWorkspaceId??f.activeWorkspaceId??null,defaultWorkspacePath:f.defaultWorkspacePath??f.activeWorkspacePath??null}:null,F=d.filter(_=>_.daemonId===s&&_.type!=="adhdev-daemon").filter(_=>!Hs(_)&&!xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:hl(_.aiAgents||(_.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:s})),D=d.filter(_=>_.daemonId===s&&Hs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:s})),C=d.filter(_=>_.daemonId===s&&xs(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,currentModel:_.currentModel,currentPlan:_.currentPlan,daemonId:s})),V=f?jt(f,{fallbackId:s}):"",J="workspace",I=n.state,R=I==null?void 0:I.initialMachineTab,B=I==null?void 0:I.initialWorkspaceCategory,z=I==null?void 0:I.initialWorkspaceId,Z=I==null?void 0:I.initialWorkspacePath,fe=R==="ides"||R==="clis"||R==="acps"?"workspace":R||J,Pe=R==="ides"?"ide":R==="clis"?"cli":R==="acps"?"acp":B,ke=[...F.map(_=>{var ue,X,ce,Ce,Re;return{id:`ide:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...D.map(_=>{var ue,X,ce,Ce,Re;return{id:`cli:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}}),...C.map(_=>{var ue,X,ce,Ce,Re;return{id:`acp:${_.type}:${_.workspace||""}`,label:((ue=_.activeChat)==null?void 0:ue.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace||void 0,currentModel:_.currentModel,timestamp:((Re=(Ce=(ce=(X=_.activeChat)==null?void 0:X.messages)==null?void 0:ce.at)==null?void 0:Ce.call(ce,-1))==null?void 0:Re.timestamp)||0}})].sort((_,ue)=>ue.timestamp-_.timestamp).map(({timestamp:_,...ue})=>ue),ve=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:_.currentModel||_.workspace||void 0,workspace:_.workspace,currentModel:_.currentModel})):ke,Q=a.useMemo(()=>{var ue;const _=((ue=c.connectionStates)==null?void 0:ue[s||""])||void 0;return d.filter(X=>X.daemonId===s&&X.type!=="adhdev-daemon").flatMap(X=>Hn(X,{},{connectionStates:s&&_?{[s]:_}:void 0,defaultConnectionState:_})).filter(X=>!(X.transport==="pty"&&X.mode==="terminal")).sort((X,ce)=>gn(ce)-gn(X))},[d,c.connectionStates,s]),xe=a.useCallback(_=>{const ue=_.sessionId||_.tabKey;ue&&r(`/dashboard?activeTab=${encodeURIComponent(ue)}`)},[r]),W=a.useCallback(()=>{u.current&&(g(!0),u.current().finally(()=>{u.current=null,g(!1),y(null)}))},[]),ee=a.useCallback(_=>{if(!E)return;const{options:ue,selectedKey:X}=ts({machine:E,currentWorkspacePath:_.workspace}),ce=async()=>{A(_.kind),b("workspace")};u.current=async()=>{const Ce=ue.find(We=>We.key===l.current),Re=(Ce==null?void 0:Ce.workspacePath)??null,me=(Ce==null?void 0:Ce.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await w.handleLaunchIde(_.providerType,Re?{workspace:Re}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await w.runLaunchCliCore({cliType:_.providerType,dir:me?void 0:Re||"",workspaceId:me||void 0,model:_.kind==="acp"?_.currentModel:void 0,resumeSessionId:_.providerSessionId});return}await ce()},l.current=X,P(X),y({title:_.kind==="ide"?Yt("restart-ide",_.label):_.providerSessionId?qo(_.label):Yt("start-fresh",_.label),description:_.kind==="ide"?Xt("restart-ide"):_.providerSessionId?Yo():Xt("start-fresh"),confirmLabel:_.kind==="ide"?Jt("restart-ide"):_.providerSessionId?Nr(!0):Jt("start-fresh"),busyLabel:_.kind==="ide"?Zt("restart-ide"):_.providerSessionId?Wn(!0):Zt("start-fresh"),workspaceOptions:ue,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[w,E]);if(a.useEffect(()=>{b(fe)},[J,fe,s]),a.useEffect(()=>{Pe&&A(Pe)},[Pe,s]),!E)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const ne=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kt,{size:14})," Workspace"]}),count:F.length+D.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ar,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ic,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Nc,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:v,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[w.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:w.nicknameInput,onChange:_=>w.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&w.handleSaveNickname(),_.key==="Escape"&&w.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:w.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>w.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{w.setEditingNickname(!0),w.setNicknameInput(E.machineNickname||"")},title:"Click to set nickname",children:V}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),t.jsxs("span",{children:[E.cpus," cores"]}),(f==null?void 0:f.version)&&t.jsxs("span",{children:["v",f.version]}),E.p2p.available&&t.jsxs("span",{children:["P2P ",E.p2p.state==="connected"?"connected":E.p2p.state]}),E.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ne.map(_=>t.jsxs("button",{onClick:()=>b(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[x==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(yp,{machineEntry:f,providers:M,recentLaunches:ve,currentConversations:Q,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ee,onOpenConversation:xe}),t.jsx(kp,{machine:E,machineId:s,providers:M,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,getIcon:$,initialCategory:S,initialWorkspaceId:z,initialWorkspacePath:Z,sendDaemonCommand:o})]}),x==="providers"&&t.jsx(mp,{machineId:s,providers:M,sendDaemonCommand:o}),x==="overview"&&t.jsx(op,{machineId:s,machine:E,ideSessions:F,cliSessions:D,acpSessions:C,actions:w,sendDaemonCommand:o}),x==="session-host"&&t.jsx(bp,{machineId:s,cliSessions:D,sendDaemonCommand:o}),x==="logs"&&t.jsx(pp,{machineId:s,sendDaemonCommand:o})]})})}),w.launchPick&&E&&t.jsx(gp,{machine:E,launchPick:w.launchPick,actions:w}),h&&t.jsx(qn,{title:h.title,description:h.description,details:h.details,workspaceOptions:h.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:_=>{l.current=_,P(_)},confirmLabel:h.confirmLabel,busyLabel:h.busyLabel,busy:k,onConfirm:W,onCancel:()=>{u.current=null,y(null)}}),t.jsx(Xo,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(ue=>ue.filter(X=>X.id!==_)),onClickToast:_=>{_.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(_.targetKey)}`)}}),t.jsx("style",{children:`
|
|
67
|
+
@keyframes toast-in {
|
|
68
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
69
|
+
to { opacity: 1; transform: translateX(0); }
|
|
70
|
+
}
|
|
71
|
+
`})]})}class Sp{constructor(){lt(this,"adapters",new Map);lt(this,"states",new Map);lt(this,"runtimeListeners",new Map);lt(this,"screenshotCallbacks",new Map);lt(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,o=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:o})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const o=this.runtimeListeners.get(s);o&&(o.delete(r),o.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const o=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(o=>o(r))}}const Dt=new Sp;function Cp(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const mr=Cp(),oo=3e3,Ip=3e4;let Rt=null,Tp=0;const Tr=new Map;let Vt=null,$s=null;function io(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function _s(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Ap(e){return e==="connected"?"connected":e}async function gr(e,s,r){const n=Bd(e,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++Tp}_${Date.now()}`;return new Promise((c,d)=>{const m=setTimeout(()=>{Tr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);Tr.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),d(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Nn(e,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Mp{constructor(s){lt(this,"daemonId");lt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return gr(this.daemonId,s,r)}async sendInput(s,r){return gr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Vt&&(clearInterval(Vt),Vt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await gr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Dt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Vt=setInterval(r,2e3)}stopScreenshots(s){Vt&&(clearInterval(Vt),Vt=null)}}let St=null;function _p(e){return(!St||St.daemonId!==e)&&(St=new Mp(e)),St}function Pp({children:e}){const s=a.useRef(vr()),r=vr();s.current=r;const{setUserName:n}=rs(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),m=a.useCallback((u,h)=>{d(u),$s==null||$s(u,h)},[]),f=a.useRef(null),p=a.useRef(),x=a.useRef(oo),b=a.useRef(!0),S=a.useRef(!1),A=a.useRef("initial_connect");return a.useEffect(()=>{b.current=!0,S.current=!1;function u(){var l,j;if(!b.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((j=f.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${mr}...`),_s("connect_attempt",{url:mr,reason:A.current,delayMs:x.current});let y;try{y=new WebSocket(mr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),h();return}f.current=y,y.onopen=()=>{if(!b.current){y.close();return}m("connected"),x.current=oo,_s("open",{url:mr,reason:A.current}),Ot.resubscribeAll({sendData:Nn}),console.log("[Standalone WS] Connected")},Rt=y,y.onmessage=P=>{var k,g;try{const N=JSON.parse(P.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const v=Tr.get(N.requestId);v&&(Tr.delete(N.requestId),N.type==="error"?v.reject(new Error(((k=N.data)==null?void 0:k.message)||"Command failed")):v.resolve(N.data));return}if(N.type==="session_output"){const v=N.sessionId||N.cliId||N.cliType;v&&Dt.emitSessionOutput(v,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Dt.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated);return}if(N.type==="topic_update"){const v=N.update;v&&Ot.publish(v);return}if(N.type==="status"||N.type==="initial_state"){const v=N.data;if(!v)return;const{injectEntries:w,markLoaded:M,getIdes:T}=s.current,$=v.instanceId||"standalone",E=T().find(C=>C.id===$),F=_p($);Dt.register($,F),Dt.setState($,"connected"),m("connected",$),Dt.emitStatus($,v);const D=jr(v,{daemonId:$,existingDaemon:E,existingEntries:T()});io("ws_status",{type:N.type,daemonId:$,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),io("entries",{daemonId:$,entries:D.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),D.length>0&&w(D,{authoritativeDaemonIds:[$]}),M(),c.current!==$&&((g=i.current)==null||g.call(i),c.current=$,i.current=Ot.subscribe({sendData:Nn},$,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${$}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const V=s.current.getIdes(),J=V.find(R=>R.id===$),I=jr(C.status,{daemonId:$,existingDaemon:J,existingEntries:V,timestamp:C.timestamp});I.length>0&&s.current.injectEntries(I),C.userName&&o.current&&o.current(C.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=P=>{b.current&&(St==null||St.stopScreenshots(),St&&Dt.setState(St.daemonId,"disconnected"),m("disconnected"),f.current=null,A.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,_s("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),h())},y.onerror=P=>{S.current||!b.current||(A.current="error",_s("error",{message:P instanceof Event?"event":String(P),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function h(){if(!b.current)return;clearTimeout(p.current);const y=x.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),_s("schedule_reconnect",{reason:A.current,delayMs:y}),p.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,Ip),u()},y)}return u(),()=>{var y;b.current=!1,S.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),St&&(St.stopScreenshots(),Dt.unregister(St.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Rp({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>($s=(c,d)=>{r(c),d&&o(d)},()=>{$s=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=Ap(s),m={};return n&&(m[n]=d),m.standalone=d,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(hc,{connectionOverrides:i,children:t.jsx(Pp,{children:e})})}const Lp=[{id:"dashboard",path:"/dashboard",icon:t.jsx(ho,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Ar,{}),label:"Settings"}];function Dp({children:e}){const s=ws(),r=In(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=p=>{s(p),o(!1)},m=()=>{c(p=>{const x=!p;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=p=>`nav-item${r.pathname.startsWith(p)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:p=>p.key==="Escape"&&o(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),t.jsx("nav",{className:"sidebar-nav",children:Lp.map(p=>t.jsxs("div",{className:f(p.path),id:`nav-${p.id}`,onClick:()=>d(p.path),title:i?p.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(bo,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(go,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.53"]}),t.jsx(Jd,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const Ep=[{icon:t.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(yo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(kt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ks,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(bo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],$p=[{icon:t.jsx(Mc,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(ho,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(_r,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(kc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(An,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Bp=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function Kp(){return t.jsxs(si,{icon:t.jsx(go,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.53"]}),children:[t.jsx(Mt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Mt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Ep.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Qo.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:ti.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ei.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Mt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:$p.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Mt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Bp.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(ri,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Wc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wp(){const{ides:e}=rs(),s=e.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Ct(),{userName:o}=rs(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=x=>{const b=x.target.value.trim();s!=null&&s.id&&b!==o&&n(s.id,"set_user_name",{userName:b}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=x=>{f(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return t.jsxs(si,{icon:t.jsx(Ar,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Fd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Mt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.53"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Mt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(x=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${x.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:x.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:x.type})]},x.type))})}),t.jsx(Mt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(tu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Mt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(au,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(pu,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(xu,{})]})]})}),t.jsx(Mt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Zd,{}),t.jsx(Gt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),t.jsx(Mt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(jc,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:x=>c(x.target.value),onBlur:d,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}Xd();uu();const Op=fo({baseUrl:""});function co(){const{ides:e,initialLoaded:s}=rs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(fn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(fn,{to:"/dashboard",replace:!0})}function Hp(){const e=a.useMemo(()=>({sendCommand:gr,sendData:Nn}),[]);return t.jsx(lc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(yc,{client:Op,children:t.jsx(Rp,{children:t.jsx(wc,{value:e,children:t.jsx(Dp,{children:t.jsxs(dc,{children:[t.jsx(zt,{path:"/dashboard",element:t.jsx(np,{})}),t.jsx(zt,{path:"/machine",element:t.jsx(co,{})}),t.jsx(zt,{path:"/machines/:id",element:t.jsx(Np,{})}),t.jsx(zt,{path:"/machines",element:t.jsx(co,{})}),t.jsx(zt,{path:"/about",element:t.jsx(Kp,{})}),t.jsx(zt,{path:"/settings",element:t.jsx(Wp,{})}),t.jsx(zt,{path:"*",element:t.jsx(fn,{to:"/dashboard",replace:!0})})]})})})})})})}xd({connectionManager:Dt});uc(document.getElementById("root")).render(t.jsx(Hp,{}));
|