@adhdev/daemon-standalone 0.8.60 → 0.8.62

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.
@@ -0,0 +1,72 @@
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 wc=Object.defineProperty;var jc=(e,s,r)=>s in e?wc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var dt=(e,s,r)=>jc(e,typeof s!="symbol"?s+"":s,r);import{r as a,j as t,M as $n,a as Bn,b as Io,c as Ao,u as Cs,R as st,d as zs,t as kc,e as Nc,D as Sc,f as kn,g as Nn,h as Wn,i as Cc,k as Ic,B as Ac,l as Tc,m as Yt,N as Sn,n as Mc}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 Lc(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 as=Lc();function ja(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 To=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}),Mo=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ka(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 Xr(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,l=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),l&&(n.versionUpdateRequired=!0),n)}function Cr(e){return Array.isArray(e)?e.map(Cr):!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,Cr(r)]))}function _c(e,s){try{return JSON.stringify(Cr(e))===JSON.stringify(Cr(s))}catch{return!1}}function sr(e,s,r){return _c(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Rc(e,s,r){var m,p,u,x,v,C,L;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of e){const g=i.get(d.id);if(!g){i.set(d.id,{...d,_lastUpdate:n});continue}const k=ka(d),f=ka(g);if(k>f){const N=(m=d.chats)!=null&&m.length?d.chats:g.chats,R=Xr(g,d,{...g,...d,chats:N,_lastUpdate:n});i.set(d.id,sr(g,R,n))}else if(k<f){const N={};if(d.status&&d.status!==g.status&&(N.status=d.status),d.cdpConnected!==void 0&&(N.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((u=g.chats)!=null&&u.length)&&(N.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==g.machineNickname&&(N.machineNickname=d.machineNickname),d.version!==void 0&&(N.version=d.version),d.serverVersion!==void 0&&(N.serverVersion=d.serverVersion),d.versionMismatch===!0&&(N.versionMismatch=!0),Object.keys(N).length>0){const R=Xr(g,d,{...g,...N,_lastUpdate:g._lastUpdate});i.set(d.id,sr(g,R,n))}else sr(g,{...g,_lastUpdate:g._lastUpdate},n)}else{const N=d.timestamp||n,R=g._lastUpdate||g.timestamp||0;if(N>=R){const b=(x=d.chats)!=null&&x.length?d.chats:g.chats,w=Xr(g,d,{...g,...d,chats:b,_lastUpdate:n});i.set(d.id,sr(g,w,n))}else(v=d.chats)!=null&&v.length&&!((C=g.chats)!=null&&C.length)&&i.set(d.id,{...g,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const g=d.daemonId||((L=d.id)==null?void 0:L.split(":")[0]);g&&l.add(g)}for(const[d,g]of i){const k=g.daemonId||d.split(":")[0];if(!l.has(k))continue;if(o.has(k)&&!c.has(d)){i.delete(d);continue}const f=n-(g._lastUpdate||g.timestamp||0);(g.transport==="pty"&&!c.has(d)&&f>1e4||g.transport==="acp"&&!c.has(d)&&f>1e4||g.transport==="cdp-page"&&!c.has(d)&&f>3e4)&&i.delete(d)}for(const[d,g]of i)n-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&i.delete(d);return Array.from(i.values())}function Pc(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 Dc({children:e,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,l]=a.useState([]),[m,p]=a.useState(void 0),u=a.useRef(r);a.useEffect(()=>{u.current=r},[r]);const x=a.useCallback((k,f)=>{n(N=>{let R=!1;const b=N.map(w=>w.id!==k||w.chats===f?w:(R=!0,{...w,chats:f}));return R?b:N})},[]),v=a.useCallback((k,f)=>{n(N=>{const R=N.length===0?k:Rc(k,N,f),b=!Pc(N,R);return b&&as.record({kind:"dashboard.entries_applied",payload:{incoming:ja(k),next:ja(R)}}),b?R:N})},[]),C=a.useCallback(()=>i(!0),[]),L=a.useMemo(()=>({injectEntries:v,markLoaded:C,getIdes:()=>u.current}),[v,C]),d=s,g=a.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:o,toasts:c,setToasts:l,wsStatus:(d==null?void 0:d.wsStatus)??"connected",isConnected:(d==null?void 0:d.isConnected)??!0,connectionStates:(d==null?void 0:d.connectionStates)??{},connectionTransports:(d==null?void 0:d.connectionTransports)??{},showReconnected:(d==null?void 0:d.showReconnected)??!1,retryConnection:d==null?void 0:d.retryConnection,isP2PActive:(d==null?void 0:d.isP2PActive)??!1,p2pStates:(d==null?void 0:d.p2pStates)??{},userRole:d==null?void 0:d.userRole,userName:m,setUserName:p}),[r,x,o,c,d==null?void 0:d.wsStatus,d==null?void 0:d.isConnected,d==null?void 0:d.connectionStates,d==null?void 0:d.connectionTransports,d==null?void 0:d.showReconnected,d==null?void 0:d.retryConnection,d==null?void 0:d.isP2PActive,d==null?void 0:d.p2pStates,d==null?void 0:d.userRole,m]);return t.jsx(Mo.Provider,{value:L,children:t.jsx(To.Provider,{value:g,children:e})})}function os(){return a.useContext(To)}function Ir(){return a.useContext(Mo)}function Lo(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function o(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const m=r==null?void 0:r(),p=o(l),u=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return m&&u.searchParams.set("token",m),!l.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,m={}){const p={"Content-Type":"application/json",...m.headers||{}},u=r==null?void 0:r();u&&(p.Authorization=`Bearer ${u}`);const x=o(l),v=new AbortController,C=setTimeout(()=>v.abort(),15e3);try{const L=await fetch(x,{...m,headers:p,signal:v.signal});if(L.status===401)throw n==null||n(),new Error("Unauthorized");if(!L.ok){const d=await L.json().catch(()=>({error:L.statusText}));throw new Error(d.error||`API Error: ${L.status}`)}return L.json()}finally{clearTimeout(C)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,m,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:m,payload:p})}),execTerminal:(l,m,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:p})}),sendAgentMessage:(l,m,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,m,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:m,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,m,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Ec=Lo({baseUrl:"http://localhost:3847"}),$c=a.createContext(Ec);function Bc({client:e,children:s}){return t.jsx($c.Provider,{value:e,children:s})}const Wc={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},_o=a.createContext(Wc);function Kc({value:e,children:s}){return t.jsx(_o.Provider,{value:e,children:s})}function Rt(){return a.useContext(_o)}const De={size:18};function Ro({size:e=De.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 Kn({size:e=De.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 Ht({size:e=De.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 On({size:e=De.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 Oc({size:e=De.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 Hc({size:e=De.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 Po({size:e=De.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 Uc({size:e=De.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 Er({size:e=De.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 Do({size:e=De.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 zc({size:e=De.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 Ut({size:e=De.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 Tt({size:e=De.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 Hn({size:e=De.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 Fc({size:e=De.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 vs({size:e=De.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 Is({size:e=De.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 is({size:e=De.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 Fs({size:e=De.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 Eo({size:e=De.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 $o({size:e=De.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 Bo({size:e=De.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 Vc({size:e=De.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 $r({size:e=De.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 Gc({size:e=De.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 Un({size:e=De.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 qc({size:e=De.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 kt({size:e=De.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 Yc({size:e=De.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 Xc({size:e=De.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 Qc({size:e=De.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 Jc({size:e=De.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 Br({size:e=De.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 Zc({size:e=De.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 el({size:e=De.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 tl({size:e=De.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 sl({size:e=De.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 rl({size:e=De.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 nl({size:e=De.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 al({size:e=De.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 ol({size:e=De.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 il({size:e=De.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 cl({size:e=De.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 ll({size:e=De.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 Na({size:e=De.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 Sa(e){return!!e&&typeof e=="object"&&"text"in e}function zn(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:Sa(i)?String(i.text||""):"").join(r):Sa(e)?o=String(e.text||""):o=String(e||""),n?o.replace(/\s+/g," ").trim():o}function Vs(e){return zn(e,{normalizeWhitespace:!0})}const Qr=new Map;function Wo(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function dl(e,s,r){return Number(e.receivedAt||r[hs(e,s)]||0)||0}function Ko(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ul(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function rr(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 Jr(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 Ca(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Ko(e)?t.jsx($n,{remarkPlugins:[Bn,Io,Ao],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function nr({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:Ca(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const o=Jr(r);return o?t.jsx("img",{src:o,alt:rr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const o=Jr(r);return o?t.jsx("audio",{controls:!0,src:o,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const o=Jr(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:rr(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||rr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const o=rr(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}),Ca(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 hs(e,s){const r=e,n=zn(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 ml=a.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx($n,{remarkPlugins:[Bn],children:s.text}),t.jsx("span",{className:"action-time",children:Wo(s.timestamp)})]})},(e,s)=>e.log===s.log),fl=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var w,j,y;const m=(s.role||"").toLowerCase(),p=m==="user"||m==="human",u=s.kind||(m==="tool"?"tool":"standard"),x=ul(s.content)?s.content:null,v=!!(x!=null&&x.some(h=>h.type!=="text")),C=zn(s.content,{joiner:`
4
+ `});if(u==="thought"){const h=typeof((w=s.meta)==null?void 0:w.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(Qc,{size:13}),t.jsx("span",{children:h})]}),t.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),v&&x?t.jsx("div",{className:"tool-text w-full",children:t.jsx(nr,{parts:x,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const h=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",W=typeof((y=s.meta)==null?void 0:y.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:h}),t.jsx("span",{children:W})]}),v&&x?t.jsx("div",{className:"chat-msg-body",children:t.jsx(nr,{parts:x,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:v&&x?t.jsx(nr,{parts:x,renderAsPreformatted:!1}):C.slice(0,100)});const L=s.meta,g=(typeof(L==null?void 0:L.renderMode)=="string"?L.renderMode.trim():"")==="preformatted",k=C,f=!1,N=k,R=g,b=!R&&Ko(N);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(k||v||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${k||v?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?o||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Wo(r)})]}),(k||v)&&t.jsx("div",{className:"chat-markdown",children:v&&x?t.jsx(nr,{parts:x,renderAsPreformatted:R}):R?t.jsx("pre",{className:"chat-preformatted",children:N}):b?t.jsx($n,{remarkPlugins:[Bn,Io,Ao],children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),f]})})},(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),pl=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:m={},emptyState:p,onLoadMore:u,isLoadingMore:x,hasMoreHistory:v,hiddenLiveCount:C=0,loadError:L,scrollToBottomRequestNonce:d},g){var we;const k=a.useRef(null),f=a.useRef(null),N=a.useRef(null),R=a.useRef(0),b=a.useRef(""),w=a.useRef(!1),j=a.useRef(null),y=a.useRef(!1),h=a.useRef(null),W=a.useRef(!1),[I,T]=a.useState(new Set),M=a.useRef(!1),O=a.useRef(!1),_=()=>{const te=k.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},S=a.useCallback((te="auto")=>{const ae=k.current;ae&&ae.scrollTo({top:ae.scrollHeight,behavior:te})},[]),H=a.useCallback(()=>{const te=k.current;!te||!l||Qr.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight)})},[l]),q=a.useCallback(()=>{var re;const te=k.current,ae=(re=window.getSelection)==null?void 0:re.call(window);if(!te||!ae||ae.rangeCount===0||ae.isCollapsed){W.current=!1;return}const V=ae.anchorNode,oe=ae.focusNode;W.current=!!(V&&oe&&te.contains(V)&&te.contains(oe))},[]),A=a.useCallback((te="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,S(te)})},[S]),P=s.length>0?`${s.length}:${(((we=s[s.length-1])==null?void 0:we.content)||"").length}`:"0:0";a.useEffect(()=>{const te=!w.current,ae=b.current!==l;if(b.current=l,te||ae){if(w.current=!0,M.current=!1,y.current=!0,!W.current){const oe=l?Qr.get(l):null;oe?requestAnimationFrame(()=>{const re=k.current;if(!re)return;const Z=Math.max(0,re.scrollHeight-re.clientHeight-oe.fromBottom);re.scrollTop=Number.isFinite(Z)?Z:oe.top,O.current=!0}):A("auto")}R.current=s.length;return}s.length>R.current?!M.current&&!W.current&&A("auto"):_()&&!M.current&&!W.current&&A("auto"),R.current=s.length},[P,l,c,s.length,A]),a.useEffect(()=>{d&&(M.current=!1,y.current=!0,O.current=!0,h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{y.current=!1,h.current=null},180),W.current||A("auto"))},[A,d]),a.useEffect(()=>()=>{H(),j.current!=null&&cancelAnimationFrame(j.current),h.current!=null&&window.clearTimeout(h.current)},[H]),a.useEffect(()=>{const te=f.current;if(!te)return;const ae=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{y.current=!1,h.current=null},180)},V=new ResizeObserver(()=>{y.current&&(W.current||(A("auto"),ae()))});return V.observe(te),()=>{V.disconnect(),h.current!=null&&(window.clearTimeout(h.current),h.current=null)}},[A,l]),a.useImperativeHandle(g,()=>({scrollToBottom:(te="smooth")=>{S(te)}}),[S]),a.useEffect(()=>{const te=k.current;if(!te)return;let ae;const V=()=>{clearTimeout(ae),ae=setTimeout(()=>{M.current=!_(),H()},50)};return te.addEventListener("scroll",V,{passive:!0}),()=>{te.removeEventListener("scroll",V),clearTimeout(ae)}},[H]),a.useEffect(()=>(document.addEventListener("selectionchange",q),()=>document.removeEventListener("selectionchange",q)),[q]);const K=a.useRef(0),z=a.useRef(!1);a.useEffect(()=>{const te=k.current;if(!te||!z.current||K.current===0)return;const ae=te.scrollHeight-K.current;ae>0&&(te.scrollTop=ae),H(),K.current=0,z.current=!1},[s.length,H]),a.useEffect(()=>{if(O.current||!l)return;const te=Qr.get(l),ae=k.current;if(!te||!ae)return;const V=Math.max(0,ae.scrollHeight-ae.clientHeight-te.fromBottom);ae.scrollTop=Number.isFinite(V)?V:te.top,O.current=!0},[l,s.length]);const X=()=>{const te=k.current;te&&(K.current=te.scrollHeight),z.current=!0,u==null||u()},xe=a.useMemo(()=>{const te=s.map((re,Z)=>({type:"message",data:re,index:Z,ts:dl(re,Z,m)}));if(!r||r.length===0)return te;const ae=[...r].sort((re,Z)=>re.timestamp-Z.timestamp).map((re,Z)=>({type:"action",data:re,index:Z,ts:re.timestamp})),V=[];let oe=0;for(const re of te){for(;oe<ae.length&&re.ts>0&&ae[oe].ts<re.ts;)V.push(ae[oe++]);V.push(re)}for(;oe<ae.length;)V.push(ae[oe++]);return V},[s,r,m]),Te=C>0||!!v,Ne=C>0?`↑ Show ${Math.min(C,80)} earlier messages${C>80?` (${C} hidden)`:""}`:L?`↻ ${L}`:"↑ Load older messages";return t.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:f,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..."}),Te&&!x&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:X,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${L&&C===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:Ne})}),xe.length===0&&!Te&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),xe.map(te=>{if(te.type==="action"){const se=te.data;return t.jsx(ml,{log:se},`action-${te.index}`)}const ae=te.data,V=te.index,oe=hs(ae,V),re=ae.receivedAt||m[oe],Z=`${l}-${oe}`,me=I.has(Z);return t.jsx(fl,{message:ae,receivedAt:re,agentName:n,userName:o,isCliMode:i,isTextExpanded:me,onToggleTextExpanded:()=>T(se=>{const ce=new Set(se);return me?ce.delete(Z):ce.add(Z),ce})},`msg-${oe}`)}),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:N})]})})}),xl=a.memo(pl,(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),hl="modulepreload",bl=function(e){return"/"+e},Ia={},gl=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(m=>{if(m=bl(m),m in Ia)return;Ia[m]=!0;const p=m.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${u}`))return;const x=document.createElement("link");if(x.rel=p?"stylesheet":hl,p||(x.as="script"),x.crossOrigin="",x.href=m,l&&x.setAttribute("nonce",l),document.head.appendChild(x),p)return new Promise((v,C)=>{x.addEventListener("load",v),x.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return o.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Aa=!1;const Oo=a.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,l]=a.useState(null),m=a.useRef([]),p=a.useRef(!1),u=a.useRef(!1),x=a.useRef(!1),v=()=>{const C=i.current;if(C){p.current&&(C.clear(),p.current=!1);for(const L of m.current)C.write(L);m.current=[],u.current&&(C.fit(),u.current=!1),x.current&&(C.bumpResize(),x.current=!1)}};return a.useImperativeHandle(o,()=>({write:C=>{i.current?i.current.write(C):m.current.push(C)},clear:()=>{i.current?i.current.clear():(m.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.current=[],p.current=!0)},resize:(C,L)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(C,L)},fit:()=>{i.current?i.current.fit():u.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const C=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(C)},[c]),a.useEffect(()=>{let C=!1;return gl(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(L=>{Aa||(Aa=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),C||l(()=>L.GhosttyTerminalView)}).catch(L=>{console.error("[CliTerminal] failed to load terminal renderer",L)}),()=>{C=!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"}})});Oo.displayName="CliTerminal";function ar({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 Ta({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,l=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:l}})})]}):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, ${l}, ${l}cc)`}})}),o&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function yl({cursorPos:e,viewportRef:s,imgRef:r}){var f;if(!e||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(f=s.current)==null?void 0:f.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,l=n.naturalHeight||o.height,m=c/l,p=o.width/o.height;let u,x,v,C;m>p?(u=o.width,x=o.width/m,v=0,C=(o.height-x)/2):(x=o.height,u=o.height*m,v=(o.width-u)/2,C=0);const L=o.left-i.left+v+u*e.nx,d=o.top-i.top+C+x*e.ny,g=Math.max(8,Math.min(i.width-8,L)),k=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:g-8,top:k-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 vl({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:m,isConnActive:p,zoom:u,isMobile:x,mobileFillZoom:v,onZoomOut:C,onZoomReset:L,onZoomIn:d,transportType:g,screenshotUsage:k,lastActionStatus:f}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:N=>N.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(N=>!N),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:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{m(N)},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(N=>!N),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:p?"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:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),g==="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"}),g==="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"}),k&&k.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:k.budgetExhausted?"TURN blocked":`TURN ${k.dailyUsedMinutes}/${k.dailyBudgetMinutes}m`}),f&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:f})]})]}),o&&t.jsxs("div",{onTouchStart:N=>N.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: ",u<=(x?v:1)+.01?x?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:N=>{N.stopPropagation(),C()},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:N=>{N.stopPropagation(),L()},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:N=>{N.stopPropagation(),d()},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 wl({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 jl(){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 Ma(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 Js(e,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!jl())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,l])=>[c,Ma(l)]))}),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,Ma(s[c])]))}),r.current=s})}function kl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:l,panYRef:m,setPanX:p,setPanY:u,setZoom:x,lastWheelTimeRef:v,onAction:C,setLastActionStatus:L,spawnRippleFromNormalized:d,clampPan:g,isMobile:k,mobileFillZoom:f}){const[N,R]=a.useState(null),b=a.useRef(null),w=a.useRef(null),j=a.useRef(null),y=a.useRef(!1),h=a.useRef(null),W=a.useRef(0),I=a.useRef(null),T=a.useRef(1),M=a.useRef({x:0,y:0}),O=a.useRef(!1),_=a.useRef(n),S=a.useRef(C),H=30,q=550,A=18,P=60,K=400,z=12,X=()=>{if(b.current)return;const Ne={nx:.5,ny:.5};b.current=Ne,R(Ne)};return a.useEffect(()=>{_.current=n,n==="mouse"&&X()},[n]),a.useEffect(()=>{S.current=C},[C]),a.useEffect(()=>{const Ne=e.current;if(!Ne)return;const we=Z=>{if(!r.current)return null;const me=r.current.getBoundingClientRect();return!me.width||!me.height?null:{nx:Math.max(0,Math.min(1,(Z.clientX-me.left)/me.width)),ny:Math.max(0,Math.min(1,(Z.clientY-me.top)/me.height))}},te=(Z,me)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,ce=se.getBoundingClientRect(),ee=se.naturalWidth||ce.width,fe=se.naturalHeight||ce.height,ne=ee/fe,ke=ce.width/ce.height;let ye,D;return ne>ke?(ye=ce.width,D=ce.width/ne):(D=ce.height,ye=ce.height*ne),{dnx:Z/ye,dny:me/D}},ae=(Z,me,se)=>{if(se<=1.05)return;const ce=-(Z-.5)*100,ee=-(me-.5)*100,fe=g(ce,ee,se);(Math.abs(fe.x-l.current)>.1||Math.abs(fe.y-m.current)>.1)&&(p(fe.x),u(fe.y),l.current=fe.x,m.current=fe.y)},V=Z=>{const me=s.current;if(me&&Z.target instanceof Node&&me.contains(Z.target))Z.preventDefault();else return;if(Z.touches.length===1){const se=Z.touches[0];w.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},O.current||(y.current=!1),h.current=setTimeout(()=>{if(!y.current&&!O.current)if(y.current=!0,_.current==="mouse"){const ce=b.current||{nx:.5,ny:.5};L("Right Click"),d(ce.nx,ce.ny,"right"),S.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=we(se);ce&&(L("Right Click"),d(ce.nx,ce.ny,"right"),S.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(Z.touches.length===2){h.current&&clearTimeout(h.current),y.current=!0,O.current=!0;const se=Z.touches[1].clientX-Z.touches[0].clientX,ce=Z.touches[1].clientY-Z.touches[0].clientY;I.current=Math.sqrt(se*se+ce*ce),T.current=c.current,M.current={x:(Z.touches[0].clientX+Z.touches[1].clientX)/2,y:(Z.touches[0].clientY+Z.touches[1].clientY)/2}}},oe=Z=>{const me=s.current;if(me&&Z.target instanceof Node&&me.contains(Z.target)&&Z.preventDefault(),Z.touches.length===1&&j.current){const se=Z.touches[0],ce=se.clientX-j.current.x,ee=se.clientY-j.current.y;if(!y.current&&w.current){const fe=se.clientX-w.current.x,ne=se.clientY-w.current.y;Math.sqrt(fe*fe+ne*ne)>8&&(y.current=!0,h.current&&clearTimeout(h.current))}if(y.current)if(_.current==="mouse"){const fe=te(ce,ee),ne=b.current||{nx:.5,ny:.5},ke=Math.max(0,Math.min(1,ne.nx+fe.dnx)),ye=Math.max(0,Math.min(1,ne.ny+fe.dny));b.current={nx:ke,ny:ye},R({nx:ke,ny:ye}),L(`Cursor: ${Math.round(ke*100)}%, ${Math.round(ye*100)}%`),ae(ke,ye,c.current);const D=Date.now();D-v.current>=30&&(v.current=D,S.current("input_mouseMoved",{nx:ke,ny:ye}).catch(()=>{}))}else if(c.current>1){const fe=s.current;if(fe){const ne=fe.clientWidth,ke=fe.clientHeight,ye=l.current+ce/ne*100,D=m.current+ee/ke*100,ge=g(ye,D,c.current);p(ge.x),u(ge.y),l.current=ge.x,m.current=ge.y}}else{const fe=we(se);if(fe){const ne=Date.now();ne-v.current>=40&&(v.current=ne,L("Scroll"),S.current("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}j.current={x:se.clientX,y:se.clientY};return}if(Z.touches.length===2&&I.current!==null){const se=Z.touches[1].clientX-Z.touches[0].clientX,ce=Z.touches[1].clientY-Z.touches[0].clientY,fe=Math.sqrt(se*se+ce*ce)/I.current,ne=(Z.touches[0].clientX+Z.touches[1].clientX)/2,ke=(Z.touches[0].clientY+Z.touches[1].clientY)/2,ye=ne-M.current.x,D=ke-M.current.y,ge=Math.abs(fe-1)>.03;if(_.current==="mouse"){if(ge){const G=Math.max(i,Math.min(5,T.current*fe));x(G),c.current=G}else if(Math.abs(ye)>2||Math.abs(D)>2){const G=b.current||{nx:.5,ny:.5},ve=Date.now();ve-v.current>=30&&(v.current=ve,L("Scroll"),S.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-ye*3),deltaY:Math.round(-D*3)}).catch(()=>{}))}}else{const G=Math.max(i,Math.min(5,T.current*fe));x(G),c.current=G;const ve=s.current;if(ve&&G>1){const Ie=ve.clientWidth,Ae=ve.clientHeight,We=l.current+ye/Ie*100,ze=m.current+D/Ae*100,Ke=g(We,ze,G);p(Ke.x),u(Ke.y),l.current=Ke.x,m.current=Ke.y}}M.current={x:ne,y:ke}}},re=Z=>{var me;if(h.current&&clearTimeout(h.current),I.current=null,Z.touches.length===1&&O.current){const se=Z.touches[0];w.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},y.current=!0;return}if(Z.touches.length===0){if(O.current){O.current=!1,y.current=!1;return}if(Z.changedTouches.length===1){const se=Z.changedTouches[0],ce=Date.now(),ee=ce-(((me=w.current)==null?void 0:me.time)||0),fe=w.current?se.clientX-w.current.x:0,ne=w.current?se.clientY-w.current.y:0,ke=Math.sqrt(fe*fe+ne*ne);if(_.current==="mouse"){if(ee<H||ee>q||ke>A){y.current=!1;return}const ye=b.current||we(se);ye&&(L(`Click: ${Math.round(ye.nx*100)}%, ${Math.round(ye.ny*100)}%`),d(ye.nx,ye.ny,"left"),S.current("input_click",{...ye}).catch(()=>{}))}else{if(y.current){y.current=!1;return}if(ee<P||ee>K||ke>z){y.current=!1;return}const ye=we(se);if(!ye)return;ce-W.current<300?(L("Double tap"),d(ye.nx,ye.ny,"double"),S.current("input_click",{...ye,clickCount:2}).catch(()=>{}),W.current=0):(L(`Tap: ${Math.round(ye.nx*100)}%, ${Math.round(ye.ny*100)}%`),d(ye.nx,ye.ny,"left"),S.current("input_click",{...ye}).catch(()=>{}),W.current=ce)}}y.current=!1}};return Ne.addEventListener("touchstart",V,{passive:!1}),Ne.addEventListener("touchmove",oe,{passive:!1}),Ne.addEventListener("touchend",re,{passive:!1}),()=>{Ne.removeEventListener("touchstart",V),Ne.removeEventListener("touchmove",oe),Ne.removeEventListener("touchend",re),h.current&&clearTimeout(h.current)}},[e,s,r,i,c,l,m,p,u,x,v,L,d,g]),{cursorPos:N,cursorPosRef:b,handleToggleInputMode:()=>{o(Ne=>{const we=Ne==="touch"?"mouse":"touch";return we==="mouse"&&X(),we})},handleZoomReset:()=>{const Ne=k?f:1;x(Ne),c.current=Ne,p(0),u(0),l.current=0,m.current=0}}}function Ho({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),l=a.useRef(null),m=a.useRef(null),[p,u]=a.useState(null),[x,v]=a.useState(""),[,C]=a.useState(!1),[L,d]=a.useState([]),g=a.useRef(0),[k,f]=a.useState(!1),[N,R]=a.useState(!1),b=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[w,j]=a.useState(b?"mouse":"touch"),[y,h]=a.useState(1),W=a.useRef(!1),[I,T]=a.useState(1),[M,O]=a.useState(0),[_,S]=a.useState(0);Js("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:w,zoom:I,panX:M,panY:_,isMenuOpen:k,isImeOpen:N});const H=a.useRef(0),q=a.useRef(I),A=a.useRef(M),P=a.useRef(_);a.useEffect(()=>{q.current=I},[I]),a.useEffect(()=>{A.current=M},[M]),a.useEffect(()=>{P.current=_},[_]),a.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const K=r==="connected",z=n,X=K?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",xe=K?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!b||W.current||!z)return;const ee=m.current,fe=l.current;if(!ee||!fe)return;const ne=()=>{const ke=fe.clientWidth,ye=fe.clientHeight,D=ee.naturalWidth,ge=ee.naturalHeight;if(!D||!ge||!ke||!ye)return;const G=Math.min(ke/D,ye/ge),Ie=Math.max(ke/D,ye/ge)/G;Ie>1.01&&(h(Ie),T(Ie),q.current=Ie),W.current=!0};ee.complete&&ee.naturalWidth?ne():ee.addEventListener("load",ne,{once:!0})},[z,b]);const Te=.5;a.useEffect(()=>{I<=Te&&(O(0),S(0))},[I,Te]);const Ne=(ee,fe,ne)=>{if(ne<=Te)return{x:0,y:0};const ke=(ne-1)/(2*ne)*100,ye=(ne-1)/(2*ne)*100;return{x:Math.max(-ke,Math.min(ke,ee)),y:Math.max(-ye,Math.min(ye,fe))}},we=(ee,fe)=>{if(!m.current)return null;const ne=m.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(ee-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(fe-ne.top)/ne.height))}},te=(ee,fe,ne)=>{const ke=l.current;if(!ke)return;const ye=ke.getBoundingClientRect(),D=++g.current;d(ge=>[...ge,{id:D,x:ee-ye.left,y:fe-ye.top,type:ne}]),setTimeout(()=>d(ge=>ge.filter(G=>G.id!==D)),600)},ae=(ee,fe,ne)=>{const ke=m.current,ye=l.current;if(!ke||!ye)return;const D=ke.getBoundingClientRect(),ge=ye.getBoundingClientRect(),G=ke.naturalWidth||D.width,ve=ke.naturalHeight||D.height,Ie=G/ve,Ae=D.width/D.height;let We,ze,Ke,qe;Ie>Ae?(We=D.width,ze=D.width/Ie,Ke=0,qe=(D.height-ze)/2):(ze=D.height,We=D.height*Ie,Ke=(D.width-We)/2,qe=0);const Ye=D.left-ge.left+Ke+We*ee,ft=D.top-ge.top+qe+ze*fe,$e=++g.current;d(lt=>[...lt,{id:$e,x:Ye,y:ft,type:ne}]),setTimeout(()=>d(lt=>lt.filter(ot=>ot.id!==$e)),600)},V=async ee=>{var ne;const fe=we(ee.clientX,ee.clientY);if(fe){u(`Click: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),te(ee.clientX,ee.clientY,"left"),(ne=c.current)==null||ne.focus();try{const ke=await e("input_click",{nx:fe.nx,ny:fe.ny});ke!=null&&ke.success||s(`❌ Click failed: ${ke==null?void 0:ke.error}`)}catch(ke){s(`❌ Click error: ${ke.message||ke}`)}}},oe=async(ee,fe,ne,ke=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:ee,code:fe,text:ne?ee:void 0,unmodifiedText:ne?ee:void 0,modifiers:ke})}catch(ye){s(`❌ Key error: ${ye.message||ye}`)}},re=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let ne=0;ee.altKey&&(ne|=1),ee.ctrlKey&&(ne|=2),ee.metaKey&&(ne|=4),ee.shiftKey&&(ne|=8),u(`Key: ${ee.key}`),await oe(ee.key,ee.code,ee.key.length===1,ne)},Z=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(x){const fe=x;v(""),u(`IME Sent: ${fe}`);try{const ne=await e("input_type",{text:fe});ne!=null&&ne.success||s(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ IME error: ${ne.message}`)}}else u("Key: Enter"),await oe("Enter","Enter",!1)}};a.useEffect(()=>{const ee=c.current;if(!ee)return;const fe=ne=>{var ke;if((ke=m.current)!=null&&ke.contains(ne.target)){ne.preventDefault();const ye=Date.now();if(ye-H.current<40)return;H.current=ye;const D=we(ne.clientX,ne.clientY);if(!D)return;u(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",fe,{passive:!1}),()=>ee.removeEventListener("wheel",fe)},[e]);const{cursorPos:me,handleToggleInputMode:se,handleZoomReset:ce}=kl({containerRef:c,viewportRef:l,imgRef:m,inputMode:w,setInputMode:j,minZoom:Te,zoomRef:q,panXRef:A,panYRef:P,setPanX:O,setPanY:S,setZoom:T,lastWheelTimeRef:H,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:ae,clampPan:Ne,isMobile:b,mobileFillZoom:y});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:re,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,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(${I}) translate(${M}%, ${_}%)`,transformOrigin:"center center",cursor:w==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:V,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):t.jsx(wl,{waitingLabel:X,waitingHint:xe,transportType:i}),w==="mouse"&&z&&t.jsx(yl,{cursorPos:me,viewportRef:l,imgRef:m}),L.map(ee=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return t.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 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(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),t.jsx(vl,{inputMode:w,onToggleInputMode:se,isImeOpen:N,setIsImeOpen:R,isMenuOpen:k,setIsMenuOpen:f,imeText:x,setImeText:v,handleImeSubmit:Z,isConnActive:K,zoom:I,isMobile:b,mobileFillZoom:y,onZoomOut:()=>T(ee=>Math.max(.5,ee-.25)),onZoomReset:ce,onZoomIn:()=>T(ee=>Math.min(5,ee+.25)),transportType:i,screenshotUsage:o,lastActionStatus:p}),t.jsx("style",{children:`
5
+ @keyframes slideUp {
6
+ from { opacity: 0; transform: translateY(6px); }
7
+ to { opacity: 1; transform: translateY(0); }
8
+ }
9
+ @keyframes slideUpSidebar {
10
+ from { opacity: 0; transform: translateY(6px); }
11
+ to { opacity: 1; transform: translateY(0); }
12
+ }
13
+ @keyframes click-ripple-ring {
14
+ 0% { transform: scale(0.3); opacity: 1; }
15
+ 100% { transform: scale(2.2); opacity: 0; }
16
+ }
17
+ @keyframes click-ripple-dot {
18
+ 0% { transform: scale(1); opacity: 0.9; }
19
+ 50% { transform: scale(1.8); opacity: 0.6; }
20
+ 100% { transform: scale(0.5); opacity: 0; }
21
+ }
22
+ @keyframes remote-float {
23
+ 0% { transform: translateY(0px); }
24
+ 50% { transform: translateY(-7px); }
25
+ 100% { transform: translateY(0px); }
26
+ }
27
+ `})]})}function Wr(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 l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const m=Math.floor(l/60);if(m<24)return`${m}h${r}`;const p=Math.floor(m/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Uo=e=>Wr(e);function Nl(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function As(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 Zs(e){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...Nl(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 Gs(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 qs(e,s,r){const n=Gs(e,s),o=As(e),i=o.isReconnecting,c=o.isConnecting,l=o.isGenerating,m=o.isWaiting,p=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||m,u=n.inboxBucket==="working"||l,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:p,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:m,inboxBucket:p?"needs_attention":u?"working":x?"task_complete":"idle"}}function Sl(e,s,r){return qs(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Cl(e,s,r){return Gs(e,r||new Map).surfaceHidden}function zo({activeConv:e,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.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(is,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,m)=>{const p=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(p),x=/^(reject|deny|delete|remove|abort)/.test(p),v=r===l,C=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:C,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${C&&!v?"opacity-40":"opacity-100"} ${C?"cursor-not-allowed":"cursor-pointer"}`,style:u?{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:v?"⏳ ...":c(l)},m)})})]})]})}var Il=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Al(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if(Al(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Il.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 Fo(e){return jt(e)==="generating"}function rt(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"IDE"}function Tl(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 Zr(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Kr(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 Ml(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 Ll(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function _l(e){return Ml(e.trim().replace(/\.local$/i,""))}function Rl(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Vo(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&&!Ll(c));if(r&&r!=="Unknown")return _l(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function At(e,s={}){return Rl(e)||Vo(e,s)}function Go(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function qo(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const o=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return o?String(r.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function cs(e,s){return Go(e).join(" · ")}function Ys(e){return e.transport==="pty"}function bs(e){return e.transport==="acp"}function La(e,s){return rt(e)}function _a(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=rt(r||"").trim().toLowerCase();return n===o||n===i||n===c}function Pl(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Dl(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=jt(n.status);if(!i){s.set(o,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(l<0||m<l)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function El(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 $l(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&&El(s.receivedAt)||0}function Bl(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Cn(e){return Math.max(Bl(e),$l(e.activeChat))}function Wl(e,s,r,n,o,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:o.localeCompare(i)}function Fn(e,s){return Wl(Cn(e),Cn(s),At(e,{fallbackId:e.id}),At(s,{fallbackId:s.id}),e.id,s.id)}const Yo="adhdev_notification_prefs",Ra={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Kl(){try{const e=localStorage.getItem(Yo);if(e){const s=JSON.parse(e);return{...Ra,...s}}}catch{}return{...Ra}}function Ol(e){try{localStorage.setItem(Yo,JSON.stringify(e))}catch{}}let Kt=Kl(),vr=[];function Hl(){vr.forEach(e=>e())}function Ul(e){Kt={...Kt,...e},Ol(Kt),Hl()}function zl(){const[,e]=a.useState(0);a.useEffect(()=>{const r=()=>e(n=>n+1);return vr.push(r),()=>{vr=vr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Ul(r)},[]);return[{...Kt},s]}function Ws(e){if(!Kt.globalEnabled)return!1;switch(e){case"disconnect":return Kt.disconnectAlert;case"completion":return Kt.completionAlert;case"approval":return Kt.approvalAlert;case"browser":return Kt.browserNotifications;default:return!0}}const Fl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Vl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Xo(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Gl(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function In(e,s,r){if(Xo())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 ql(e,s={}){const r={...Fl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Gl().then(l=>{i.current=l})},[]);const c=a.useCallback((l,m,p)=>{const u=Date.now();u-o.current<r.throttleMs||(o.current=u,In(l,m,p))},[r.throttleMs]);a.useEffect(()=>{var l;if(!(!r.enabled||!Xo())&&Ws("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of e)n.current.set(m.id,jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const p=n.current.get(m.id),u=jt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Ws("approval")&&u==="waiting_approval"&&p!=="waiting_approval"){const v=((l=m.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,v.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ws("completion")&&Fo(p)&&u==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&u==="error"&&p!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,u)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Yl=/^(run|approve|accept|yes|allow|always)/,Xl=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ql=/^(reject|deny|delete|remove|abort|cancel|no)/;function Vn(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Jl(e){const s=Vn(e).toLowerCase();return Yl.test(s)?"primary":Ql.test(s)?"danger":"default"}function Zl(e){return Xl.test(Vn(e).toLowerCase())?"approve":"reject"}function ed(e){return e.map((s,r)=>({label:Vn(s),variant:Jl(s),action:Zl(s),button:s,buttonIndex:r}))}function td(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
28
+ ${n}`}function sd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function rd(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 nd{constructor(){dt(this,"dedupMap",new Map);dt(this,"DEDUP_WINDOW_MS",5e3);dt(this,"DEDUP_MAX_SIZE",50);dt(this,"DEDUP_CLEANUP_AGE_MS",1e4);dt(this,"toastCallbacks",[]);dt(this,"systemMessageCallbacks",[]);dt(this,"clearSystemMessageCallbacks",[]);dt(this,"resolveActionFn",null);dt(this,"viewRequestRespondFn",null);dt(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 L,d;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),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(m==null?void 0:m.type)||"";let u=rt(p);const x=this.resolveOwningDaemon(s);if(x){const g=At(x,{fallbackId:x.id});g&&(u=!p||p==="adhdev-daemon"?g:`${g}/${u}`)}let v="",C="info";if(s.event==="agent:generating_completed"){const g=s.duration?` (${s.duration}s)`:"";v=`✅ ${u} agent task completed${g}`,C="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(v=`⚡ ${u} approval needed`,C="warning",n&&!((L=s.modalButtons)!=null&&L.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:td(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const g=this.resolveActionRouteTarget(s);if(!g)return;const k=this.resolveActionFn,f=ed(s.modalButtons).map(b=>({label:b.label,variant:b.variant,onClick:()=>{k(g,"resolve_action",{action:b.action,button:b.button,buttonIndex:b.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=sd(u,s.modalMessage,v),R=Date.now();this.emitToast({id:R,message:N,type:C,timestamp:R,targetKey:n||g,actions:f,duration:15e3}),v=""}}else if(s.event==="monitor:long_generating"){const g=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";v=`⚠️ ${u} agent is taking a long time${g}`,C="warning",Ws("browser")&&!document.hasFocus()&&In(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${g.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const g=s.requesterName||"A team member",k=s.requestId,f=s.orgId;if(v=`👁️ ${g} wants to view your session`,C="warning",k&&f&&this.viewRequestRespondFn){const N=Date.now(),R=rd(f,k,this.viewRequestRespondFn,(b,w)=>console.error(`[EventManager] ${b} view request failed:`,w));this.emitToast({id:N,message:v,type:C,timestamp:N,actions:R,duration:3e4}),v=""}Ws("browser")&&!document.hasFocus()&&In("👁️ View Request",`${g} wants to view your session`,`view-request-${k}`)}else s.event==="team:view_request_approved"?(v="✅ View request approved",C="success"):s.event==="team:view_request_rejected"&&(v=`❌ ${s.targetName||"Team member"} declined your view request`,C="warning");if(v){const g=Date.now();this.emitToast({id:g,message:v,type:C,timestamp:g,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new nd,Pa=new Map;function ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qo(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ad(e){return!ws(e)||!ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function or(e){return!ws(e)||!ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function _s(e){if(!(!ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function ir(e){return ws(e)&&e.success===!1}function od(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";nt.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";nt.showToast(n.notification.body,o)}}}function id(e,s){return e&&Qo(e.currentValue)?e.currentValue:s}function wr(e,s){return e.options||s[e.id]||[]}function en(e,s){return{value:s}}function cd(e,s,r){var o;return r?((o=wr(e,s).find(i=>i.value===r))==null?void 0:o.label)||r:""}const ld={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function dd({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c}){const{sendCommand:l}=Rt(),m=`${e}:${s||n}`,p=ld[n]||"#94a3b8",[u,x]=a.useState({}),v=a.useRef(0),C={};for(const _ of i||[])_.defaultValue!==void 0&&(C[_.id]=_.defaultValue);const L={...C,...c||{},...Date.now()<v.current?u:{}};a.useEffect(()=>{c&&Date.now()>v.current&&x({})},[c]);const[d,g]=a.useState(Pa.get(m)||{}),[k,f]=a.useState(null),[N,R]=a.useState(null),b=a.useCallback(async(_,S={})=>{const H={...S,...s&&{targetSessionId:s}};return await l(e,_,H)},[e,s,l]),w=a.useCallback(async(_,S={})=>{const H=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await b("invoke_provider_script",{...H,scriptName:_,...S})},[b,n,r,s]),j=a.useCallback((_,S,H)=>{const q=id(H,S);x(A=>({...A,[_.id]:q})),od(H==null?void 0:H.effects)},[]),y=a.useCallback((_,S)=>{x(H=>{const q={...H};return S===void 0?delete q[_.id]:q[_.id]=S,q}),v.current=0},[]);if(!i||i.length===0)return null;const h=i.filter(_=>_.placement==="bar"&&_.hidden!==!0).sort((_,S)=>(_.order??50)-(S.order??50));if(h.length===0)return null;const W=async _=>{if(k===_.id){f(null);return}if(wr(_,d).length>0){f(_.id);return}if(_.dynamic&&_.listScript){R(_.id);try{const H=await w(_.listScript,{}),q=ad(H);if(!q){const P=_s(H);P&&nt.showToast(P,"warning");return}const A=q.options;if(g(P=>{const K={...P,[_.id]:A};return Pa.set(m,K),K}),Qo(q.currentValue)){const P=q.currentValue;x(K=>({...K,[_.id]:P}))}f(_.id)}catch(H){const q=H instanceof Error?H.message:`Could not load ${_.label}`;nt.showToast(q,"warning")}finally{R(null)}}},I=async(_,S)=>{f(null);const H=(c==null?void 0:c[_.id])??C[_.id];x(q=>({...q,[_.id]:S})),v.current=Date.now()+5e3;try{if(!_.setScript)return;const q=await w(_.setScript,en(_,S)),A=or(q);if(A&&!A.ok||ir(q))throw new Error((A==null?void 0:A.error)||_s(q)||`Could not update ${_.label}`);j(_,S,A)}catch(q){y(_,H);const A=q instanceof Error?q.message:`Could not update ${_.label}`;nt.showToast(A,"warning")}},T=async _=>{const S=wr(_,d).map(z=>z.value);if(S.length===0)return;const H=String(L[_.id]||""),A=(S.indexOf(H)+1)%S.length,P=S[A];if(typeof P!="string")return;const K=(c==null?void 0:c[_.id])??C[_.id];x(z=>({...z,[_.id]:P})),v.current=Date.now()+5e3;try{if(!_.setScript)return;const z=await w(_.setScript,en(_,P)),X=or(z);if(X&&!X.ok||ir(z))throw new Error((X==null?void 0:X.error)||_s(z)||`Could not update ${_.label}`);j(_,P,X)}catch(z){y(_,K);const X=z instanceof Error?z.message:`Could not update ${_.label}`;nt.showToast(X,"warning")}},M=async _=>{const H=!L[_.id],q=(c==null?void 0:c[_.id])??C[_.id];x(A=>({...A,[_.id]:H})),v.current=Date.now()+5e3;try{if(!_.setScript)return;const A=await w(_.setScript,en(_,H)),P=or(A);if(P&&!P.ok||ir(A))throw new Error((P==null?void 0:P.error)||_s(A)||`Could not update ${_.label}`);j(_,H,P)}catch(A){y(_,q);const P=A instanceof Error?A.message:`Could not update ${_.label}`;nt.showToast(P,"warning")}},O=async _=>{if(!_.invokeScript)return;if(_.confirmMessage){const H=[_.confirmTitle,_.confirmMessage,_.confirmLabel].filter(A=>typeof A=="string"&&A.trim().length>0);if(!window.confirm(H.join(`
29
+
30
+ `)))return}const S=(c==null?void 0:c[_.id])??C[_.id];try{const H=await w(_.invokeScript),q=or(H);if(q&&!q.ok||ir(H))throw new Error((q==null?void 0:q.error)||_s(H)||`Could not run ${_.label}`);q&&j(_,S??!0,q)}catch(H){y(_,S);const q=H instanceof Error?H.message:`Could not run ${_.label}`;nt.showToast(q,"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:p},children:o}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),h.map(_=>{const S=String(L[_.id]||""),H=cd(_,d,S),q=k===_.id,A=N===_.id,P=wr(_,d);switch(_.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:q?`${p}55`:"transparent",border:"1px solid",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>W(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),A?"...":H||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),q&&P.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>f(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:_.label.toUpperCase()}),P.map(K=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:K.value===S?`${p}18`:"transparent",color:K.value===S?p:"var(--text-secondary)",fontWeight:K.value===S?600:400,borderLeft:K.value===S?`2px solid ${p}`:"2px solid transparent"},title:K.description||K.label,onMouseEnter:z=>{z.currentTarget.style.background=`${p}12`},onMouseLeave:z=>{z.currentTarget.style.background=K.value===S?`${p}18`:"transparent"},onClick:()=>I(_,K.value),children:K.label},K.value))]})]})]},_.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:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>T(_),title:`Click to cycle: ${P.map(K=>K.label).join(" → ")}`,children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),H||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},_.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:S?`${p}44`:"transparent",background:S?`${p}14`:"var(--surface-tertiary)",color:S?p:"var(--text-muted)"},onClick:()=>M(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.label]},_.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:()=>O(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.resultDisplay==="inline"&&S?`${_.label}: ${S}`:_.label]},_.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:S?"var(--text-primary)":"var(--text-muted)"},children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),S?`${_.label}: ${S}`:_.label]},_.id);default:return null}})]})}const ud=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[l,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var u;i&&((u=c.current)==null||u.focus())},[s,i]);const p=()=>{const u=l.trim();!u||n||(m(""),o(u))};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:l,onChange:u=>m(u.target.value),onPaste:u=>{const x=u.clipboardData.getData("text");x&&m(v=>v+x),u.preventDefault()},onKeyDown:u=>{if(u.key==="Enter"){if(u.nativeEvent.isComposing){u.preventDefault();return}u.preventDefault(),p()}},onBlur:u=>{if(window.innerWidth<768){const x=u.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:p,disabled:!l.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${l.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:l.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:l.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),Xe=e=>e.transport==="pty",js=(e,s)=>Xe(e)?e.mode||"terminal":"chat",Jo=(e,s)=>Xe(e)&&js(e)==="terminal",Ve=e=>e.transport==="acp";function Ot(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Zo(e){return e.machineName||""}function Ar(e){return qt(e)}function It(e){return e.agentType||""}function Gn(e){return e.hostIdeType||""}function Or(e){return e.displayPrimary||e.agentName||"Agent"}function qn(e){return[e.displaySecondary,Zo(e)].filter(Boolean)}function er(e){return e.agentName||rt(It(e))}function md(e){var s,r;if(!Ot(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return rt(Gn(e)||It(e))}function Yn(e){return Ot(e)?e.sessionId:e.nativeSessionId}function Da(e){return Ot(e)?"native":e.tabKey}function fd(e){return e.sessionId}function pd(e,s){if(s)return Ot(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function xd(e,s){const r=It(e),n=Ot(e)?s!=null&&s.type?rt(s.type):rt(Gn(e)||r):er(e);return{isNativeConversation:Ot(e),isCli:Xe(e),isAcp:Ve(e),isCliTerminal:Jo(e),providerType:r,displayLabel:n,targetEntry:pd(e,s)}}function ei({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=Cs(),c=qt(e),l=Zo(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,u=!p&&(e.transport==="pty"||e.transport==="acp"),x=er(e),v=md(e),C=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),L=a.useCallback(()=>{if(r){r();return}const d=Yn(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[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:L,title:v,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:v})]}):t.jsxs("span",{className:"conversation-meta-chip",title:v,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:v})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Fs,{size:12}),t.jsx("span",{children:x})]}),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Fs,{size:12}),t.jsx("span",{children:x})]}),l&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:l,children:[t.jsx(Ht,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ht,{size:12}),t.jsx("span",{children:l})]}))]})}function Ea(e,s){return`${e}:${s}`}function hd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function cr(e,s){hd()&&console.debug(`[subscription-manager] ${e}`,s)}class bd{constructor(){dt(this,"active",new Map)}subscribe(s,r,n,o){var p;const i=Ea(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const u={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,u),cr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const m=()=>{var v;const u=this.active.get(i);if(!u||(u.handlers.delete(o),u.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};cr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=s.sendData)==null||v.call(s,r,x)};return m.initialSendAccepted=l,m}publish(s){const r=Ea(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,as.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),as.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;cr("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);cr("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 Vt=new bd;function gd(e,s){if(!e)return s;if(!s)return e;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function yd(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,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,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 lr(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),activeChat:gd(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),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 vd(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 Tr(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:p,childrenByParent:u}=vd(m),x=yd(i,n),v=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,C=p.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),L=p.filter(g=>g.kind==="agent"&&g.transport==="pty"),d=p.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...v&&{machine:v,platform:v.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:C.some(g=>!!g.cdpConnected)});for(const g of C){const k=x.get(g.id),f=lr(g,k),N=(u.get(g.id)||[]).map(R=>lr(R,x.get(R.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:g.id,workspace:f.workspace,terminals:0,childSessions:N,agents:N.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l})}for(const g of L){const k=x.get(g.id),f=lr(g,k);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:g.id,cliName:f.providerName||f.providerType,mode:f.mode||(k==null?void 0:k.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l,_isCli:!0})}for(const g of d){const k=x.get(g.id),f=lr(g,k);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:g.id,cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const tn=new Map,sn=new Map,rn=new Set,Ks=new Map,wd=1200;function jd(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 $a(e,s){const r=Ks.get(e);!r||r.size===0||(Ks.delete(e),r.forEach(n=>n(s)))}function kd(e,s){return new Promise(r=>{const n=Ks.get(e)||new Set;Ks.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Ks.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function tr(){const{sendCommand:e,sendData:s}=Rt(),{injectEntries:r,getIdes:n}=Ir();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=sn.get(o)||0;if(!(i!=null&&i.force)&&rn.has(o)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const m=tn.get(o);if(m)return m;const p=(async()=>{if(s&&!rn.has(o)&&(rn.add(o),Vt.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const g=n(),k=g.find(N=>N.id===o),f=Tr(d.status,{daemonId:o,existingDaemon:k,existingEntries:g,timestamp:d.timestamp});f.length>0&&r(f),sn.set(o,Date.now()),$a(o,!0)}),!(i!=null&&i.force)&&await kd(o,wd)))return;const u=await e(o,"get_status_metadata"),x=jd(u);if(!x)return;const v=n(),C=v.find(d=>d.id===o),L=Tr(x,{daemonId:o,existingDaemon:C,existingEntries:v,timestamp:x.timestamp||Date.now()});L.length>0&&r(L,{authoritativeDaemonIds:[o]}),sn.set(o,Date.now()),$a(o,!0)})().finally(()=>{tn.delete(o)});return tn.set(o,p),p},[n,r,e,s])}function zt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Xn(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=Vs(e.content),i=Vs(s.content);if(!o||o!==i)return!1;const c=zt(e),l=zt(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function Ba(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),zt(e)&&(s+=1),s}function ks(e){return Vs(e==null?void 0:e.content)}function An(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function Nd(e,s){const r=ks(e),n=ks(s);return!r||!n||r===n?null:An(r,n)?e:An(n,r)?s:null}function Sd(e,s){const r=Nd(e,s);if(r)return r;const n=Ba(e),o=Ba(s);return o!==n?o>n?s:e:ks(s).length>=ks(e).length?s:e}function Xs(e){const s=[];for(const r of e){const n=s.findIndex(o=>Xn(o,r));if(n>=0){s.splice(n,1,Sd(s[n],r));continue}s.push(r)}return s}function Cd(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:Xs([...r,...n])}function Wa(e){return[...e].sort((s,r)=>{const n=zt(s),o=zt(r);return n&&o&&n!==o?n-o:0})}function Ka(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=>Xn(i,n));return o>=0?(r.splice(o,1),!1):!0})}function Id(e,s){return e.filter(r=>{const n=ks(r),o=String((r==null?void 0:r.role)||"").toLowerCase(),i=zt(r);return!s.some(c=>{if(Xn(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!o||o!==l)return!1;const m=ks(c);if(!An(m,n)&&m!==n)return!1;const p=zt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const Ad=60,Td=200;function Md(e={}){return e.isCliLike?Td:Ad}function Ld(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function _d(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 Oa(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 ti(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return _d([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function Rd(e){return{knownMessageCount:e.length,lastMessageSignature:ti(e[e.length-1])}}function Pd(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Xs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Xs([...e.slice(0,n),...r])}case"full":default:return r}}const Ha=60;function Tn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:m=!1,scrollToBottomRequestNonce:p,isInputActive:u=!0}){var we,te;const x=a.useRef(new Map),v=a.useRef(new Map),C=a.useRef(new Map),{sendCommand:L,sendData:d}=Rt(),g=tr();Js("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const k=st.useMemo(()=>As(e),[e.status,e.connectionState]),f=a.useMemo(()=>xd(e,s),[e,s]),N=Md({isCliLike:f.isCli||f.isAcp}),R=a.useRef(new Map),b=a.useCallback(ae=>(R.current.has(ae)||R.current.set(ae,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:N}),R.current.get(ae)),[N]),w=a.useCallback((ae,V)=>{const oe=b(ae);R.current.set(ae,{...oe,...V}),j(re=>re+1)},[b]),[,j]=a.useState(0),y=e.tabKey,h=b(y),W=h.messages,I=h.hasMore,T=h.error,M=v.current.get(y),O=Cd(M,e.messages);a.useEffect(()=>{h.visibleLiveCount>=N||w(y,{visibleLiveCount:N})},[N,h.visibleLiveCount,y,w]);const _=Math.max(0,O.length-h.visibleLiveCount),S=Or(e),H=Ar(e),q=e.sessionId||"",A=e.providerSessionId||q,[P,K]=a.useState(!1);a.useEffect(()=>{const ae=f.targetEntry;H&&(!ae||ae.providerControls===void 0||ae.controlValues===void 0)&&g(H,{minFreshMs:3e4}).catch(()=>{})},[H,f.isAcp,(we=f.targetEntry)==null?void 0:we.providerControls,(te=f.targetEntry)==null?void 0:te.controlValues,g]),a.useEffect(()=>{if(!H||!q||!d)return;const ae=v.current.get(y)||[],V=C.current.get(y),oe=V&&V.knownMessageCount?V:Rd(ae),re=`daemon:${H}:session:${q}`;return Vt.subscribe({sendData:d},H,{type:"subscribe",topic:"session.chat_tail",key:re,params:{targetSessionId:q,historySessionId:A,knownMessageCount:oe.knownMessageCount,lastMessageSignature:oe.lastMessageSignature,...oe.knownMessageCount?{}:{tailLimit:Ha}}},me=>{const se=v.current.get(y)||[],ce=Pd(se,me),ee=Math.max(ce.length,Number(me.totalMessages||0));C.current.set(y,{knownMessageCount:ee,lastMessageSignature:typeof me.lastMessageSignature=="string"?me.lastMessageSignature:ti(ce[ce.length-1])}),Oa(se)!==Oa(ce)&&(v.current.set(y,ce),as.record({interactionId:me.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:q,syncMode:me.syncMode,previousCount:se.length,nextCount:ce.length}}),j(ne=>ne+1))})},[H,A,d,q,y]);const z=a.useCallback(async()=>{if(P)return;const ae=e.tabKey,V=b(ae);if(O.length>V.visibleLiveCount){w(ae,{visibleLiveCount:Math.min(O.length,V.visibleLiveCount+Ha),error:null});return}K(!0),w(ae,{error:null});try{const oe=Ar(e);if(!oe){w(ae,{hasMore:!1});return}const re=It(e),Z=await L(oe,"chat_history",{agentType:re,offset:V.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),me=Ld(Z),se=me.messages||[];if(se.length>0){const ce=b(ae);w(ae,{messages:[...se,...ce.messages],offset:ce.offset+se.length,hasMore:!!me.hasMore})}else w(ae,{hasMore:!!me.hasMore})}catch(oe){const re=(oe==null?void 0:oe.message)||"";re.includes("P2P not available")||re.includes("channel not open")||re.includes("P2P not connected")||re.includes("timeout")?w(ae,{error:"Connection not ready — tap to retry"}):w(ae,{hasMore:!1,error:"Failed to load history"})}finally{K(!1)}},[P,e,O.length,L,b,w]),{allMessages:X,receivedAtMap:xe}=a.useMemo(()=>{const ae=_>0?O.slice(-h.visibleLiveCount):O;if(W.length===0){const Z=Wa(Xs(ae)),me={};return Z.forEach((se,ce)=>{const ee=`${e.tabKey}:${hs(se,ce)}`;let fe=zt(se)||x.current.get(ee)||0;fe||(fe=Date.now(),x.current.set(ee,fe)),me[hs(se,ce)]=fe}),{allMessages:Z,receivedAtMap:me}}const V=Id(W,ae),oe=Wa(Xs([...V,...ae])),re={};return oe.forEach((Z,me)=>{const se=`${e.tabKey}:${hs(Z,me)}`;let ce=zt(Z)||x.current.get(se)||0;ce||(ce=Date.now(),x.current.set(se,ce)),re[hs(Z,me)]=ce}),{allMessages:oe,receivedAtMap:re}},[e.tabKey,_,W,O,h.visibleLiveCount]),Te=a.useMemo(()=>c.filter(ae=>ae.routeId===e.tabKey).sort((ae,V)=>ae.timestamp-V.timestamp),[c,e.tabKey]),Ne=a.useMemo(()=>{if(O.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((k.isGenerating||e.status==="streaming")&&K(!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(Fs,{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(vs,{size:14})," Open ",S," 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(Eo,{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(vs,{size:14})," Open ",S," 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"&&!P)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,P,O.length,S,k.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(ei,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(xl,{messages:X,actionLogs:Te,agentName:er(e)||S||"Agent",userName:l,isCliMode:f.isCli||f.isAcp,isWorking:k.isGenerating,contextKey:e.tabKey,receivedAtMap:xe,onLoadMore:z,isLoadingMore:P,hasMoreHistory:I,hiddenLiveCount:_,loadError:T??void 0,emptyState:Ne,scrollToBottomRequestNonce:p}),u&&!f.isCliTerminal&&(()=>{var ae,V;return t.jsx(dd,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:f.providerType,displayLabel:f.displayLabel,controls:(ae=f.targetEntry)==null?void 0:ae.providerControls,controlValues:(V=f.targetEntry)==null?void 0:V.controlValues})})(),!f.isCliTerminal&&t.jsx(ud,{contextKey:e.tabKey,panelLabel:S,isSending:n,onSend:r,isActive:u})]})}let si=os;function ri(){return si()}class Dd{constructor(){dt(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 ni=new Dd;class Ed{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 ct=new Ed;function $d(e){e.dashboardWS&&(ni=e.dashboardWS),e.connectionManager&&(ct=e.connectionManager),e.useDaemonsHook&&(si=e.useDaemonsHook)}function at(e){return Or(e)}function ls(e){return qn(e).join(" · ")}function ai(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=Vs(s==null?void 0:s.content);return r||(e.title?e.title:ls(e)||"No messages yet")}function oi(e,s){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Bd(e,s){const r=["Chat",...qn(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function Zt(e){return oi(e)||ls(e)}function Wd(e){return`${at(e)} · ${ai(e)}`}function Kd(e){const s=Gn(e)||It(e);return`${at(e)} — ${rt(s)}`}function Od(e){return er(e)||"CLI"}function ii(e){return e.title||er(e)||e.routeId}function ci(e){return e?`Remote · ${at(e)||e.workspaceName||"Session"}`:"Remote"}function Hd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var P;const{ides:c}=os(),l=a.useRef(null),{sendCommand:m,sendData:p}=Rt(),[u,x]=a.useState(""),[v,C]=a.useState(!1),[L,d]=a.useState(1),g=a.useRef(!1),k=a.useRef(0),f=a.useRef(!1),N=a.useRef(""),R=a.useRef(null),b=a.useRef(!1),w=a.useRef(null),j=e.tabKey,y=e.sessionId||"",h=e.daemonId||((P=e.routeId)==null?void 0:P.split(":")[0])||e.routeId||"",W=c.find(K=>K.id===h&&K.type==="adhdev-daemon"),I=(W==null?void 0:W.terminalSizingMode)==="fit"?"fit":"measured",T=.6,M=1.15,O=()=>{if(typeof window>"u")return 1;const K=window.innerWidth||0;return K<=360?.68:K<=390?.74:K<=430?.82:K<=480?.9:1},_=()=>{var K,z;k.current=0,f.current=!1,N.current="",R.current=null,b.current=!1,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),C(!1),(z=(K=r.current)==null?void 0:K.reset)==null||z.call(K)},S=()=>{var K,z;k.current=0,f.current=!1,N.current="",R.current=null,b.current=!1,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),C(!0),(z=(K=r.current)==null?void 0:K.reset)==null||z.call(K)},H=()=>{var z;if(w.current=null,!i)return;const K=N.current;K&&(N.current="",(z=r.current)==null||z.write(K))},q=K=>{K&&(N.current+=K,i&&w.current===null&&(w.current=requestAnimationFrame(H)))},A=(K,z=0,X,xe)=>{var Te,Ne,we,te,ae;z>0&&k.current>=z||z===0&&f.current||(k.current=z,C(!0),typeof X=="number"&&typeof xe=="number"&&X>0&&xe>0&&((Ne=(Te=r.current)==null?void 0:Te.resize)==null||Ne.call(Te,X,xe)),(te=(we=r.current)==null?void 0:we.reset)==null||te.call(we),K&&((ae=r.current)==null||ae.write(K)))};return a.useEffect(()=>{_()},[y]),a.useEffect(()=>{var z;if(!y)return;const K=((z=ct.onRuntimeEvent)==null?void 0:z.call(ct,y,X=>{if(!(!X||X.sessionId!==y)){if(X.type==="runtime_snapshot"){if(!i){R.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}A(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){f.current=!0,typeof X.seq=="number"&&(k.current=Math.max(k.current,X.seq)),v||C(!0),typeof X.data=="string"&&q(X.data);return}if(X.type==="session_cleared"){if(!i){b.current=!0,N.current="",R.current=null;return}S()}}}))||(()=>{});return()=>{K()}},[h,y,r,i,v]),a.useEffect(()=>{var z,X,xe;if(!y)return;h&&((z=ct.getState)==null?void 0:z.call(ct,h))==="connected"&&(C(!0),(X=ct.requestRuntimeSnapshot)==null||X.call(ct,h,y).catch(()=>{}));const K=(xe=ct.onStateChange)==null?void 0:xe.call(ct,(Te,Ne)=>{var we;Te!==h||Ne!=="connected"||(C(!0),(we=ct.requestRuntimeSnapshot)==null||we.call(ct,h,y).catch(()=>{}))});return()=>{K==null||K()}},[h,y,r]),a.useEffect(()=>{s&&_()},[s,j,r]),a.useEffect(()=>{x("")},[e.tabKey]),a.useEffect(()=>{const K=()=>{g.current||d(O())};return K(),window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),a.useEffect(()=>{var z;if(!i){(z=l.current)==null||z.blur();return}b.current&&(b.current=!1,S());const K=R.current;K&&(R.current=null,A(K.text,K.seq,K.cols,K.rows)),N.current&&w.current===null&&(w.current=requestAnimationFrame(H)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),a.useEffect(()=>()=>{w.current!==null&&(cancelAnimationFrame(w.current),w.current=null)},[]),a.useEffect(()=>{const K=z=>{var xe;const X=z.detail;X!=null&&X.sessionId&&X.sessionId!==y||v&&((xe=r.current)==null||xe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",K),()=>{window.removeEventListener("adhdev:fit-cli-terminal",K)}},[v,y,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:()=>{g.current=!0,d(K=>Math.max(T,Number((K-.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:()=>{g.current=!0,d(K=>Math.min(M,Number((K+.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/L}%`,height:`${100/L}%`,transform:`scale(${L})`,transformOrigin:"top left"},children:t.jsx(Oo,{ref:r,readOnly:!v||!i,sizingMode:I,onInput:K=>{v&&(p!=null&&p(h,{type:"pty_input",sessionId:y,targetSessionId:y,data:K})||m(h,"pty_input",{targetSessionId:y,data:K}).catch(console.error))}})})}),!v&&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:l,type:"text",placeholder:`Send message to ${at(e)}...`,value:u,disabled:!v||!i||o,onChange:K=>x(K.target.value),onPaste:K=>{const z=K.clipboardData.getData("text");z&&x(X=>X+z),K.preventDefault()},onKeyDown:K=>{if(K.key!=="Enter")return;if(K.nativeEvent.isComposing){K.preventDefault();return}K.preventDefault();const z=u.trim();!v||!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 K=u.trim();!v||!K||o||(x(""),n(K))},disabled:!v||!i||!u.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.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:u.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function Ud({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)"},l={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:l[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 zd({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 l=(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:[l," 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 Qn({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($r,{size:n}):t.jsx(Ut,{size:n})})}function Fd(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 Gt(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Fd(s==null?void 0:s.receivedAt)||0}function Mn(e,s=0){return Gt(e)||e.lastUpdated||s||0}function li(e){return Gt(e)||e.lastUpdated||0}function Mr(e,s,r=li){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 Ln(e){var r;const s=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Vd(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Ln(e)&&!e.title.trim()}function Gd(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Ln(r))-Number(Ln(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:Mr(s,r)})[0]||null}function Bt(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=Gd(o);return n?i&&Vd(n)?i:n:i||r[0]||null}function Ua({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function za({conversation:e,isAttention:s,shortcutIndex:r,onClick:n}){const o=qn(e),i=Wr(Gt(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:Or(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 qd({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:m,onSetCliViewMode:p,onOpenConversation:u,onHideConversation:x,hiddenConversations:v=[],onShowConversation:C,onShowAllHidden:L,onResetPanelsToMain:d,inboxOpen:g,onInboxOpenChange:k,hiddenOpen:f,onHiddenOpenChange:N,onOpenNewSession:R,actionShortcuts:b}){const{ides:w,p2pStates:j={}}=os(),y=!!e&&Xe(e)&&!Ve(e),h=!!e&&Ve(e),W=m||(e?Jo(e)?"terminal":"chat":null),[I,T]=a.useState(!1),M=a.useRef(null),O=a.useRef(null),_=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",S=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",H=w.filter(V=>V.type==="adhdev-daemon"),q=a.useMemo(()=>Zs(w),[w]),A=Object.values(j),P=A.filter(V=>V==="connected").length,K=A.filter(V=>V==="connecting"||V==="new"||V==="checking").length,X=r!=="connected"||H.length===0?null:K>0&&P===0?"P2P connecting...":P>0&&s===0?"Waiting for IDE...":null,xe=a.useMemo(()=>o.filter(V=>!Cl(V,o,q)),[o,q]),Te=a.useMemo(()=>xe.filter(V=>qs(V,q).requiresAction).sort(Mr),[xe,q]),Ne=a.useMemo(()=>xe.filter(V=>{const oe=(e==null?void 0:e.tabKey)===V.tabKey;return qs(V,q,{hideOpenTaskCompleteUnread:!0,isOpenConversation:oe}).unread}).sort(Mr),[e,xe,q]),we=a.useMemo(()=>[...Te,...Ne].slice(0,9),[Te,Ne]),te=Te.length+Ne.length;a.useEffect(()=>{if(!g)return;const V=oe=>{var re;(re=M.current)!=null&&re.contains(oe.target)||k(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[g,k]),a.useEffect(()=>{if(!f)return;const V=oe=>{var re;(re=O.current)!=null&&re.contains(oe.target)||N(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[f,N]),a.useEffect(()=>{if(!f&&!g)return;const V=oe=>{if(!oe.altKey)return;const re=oe.code.match(/^Digit([1-9])$/);if(!re)return;const Z=Number(re[1])-1,me=f?v[Z]:void 0,se=g?we[Z]:void 0,ce=me||se;if(ce){if(oe.preventDefault(),oe.stopPropagation(),me){C==null||C(me),N(!1);return}u==null||u(ce),k(!1)}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[v,f,g,we,N,k,u,C]);const ae=V=>{if(!V)return;const oe=o.find(re=>re.tabKey===V);oe&&(x==null||x(oe))};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(Ut,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?at(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:_,boxShadow:S}})})]}),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:_,boxShadow:S}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),R&&t.jsx("button",{type:"button",onClick:R,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(qc,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(y||h||!Ve(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ls(e)||at(e),children:at(e)}),(y||h)&&l&&t.jsxs(t.Fragment,{children:[y&&p&&W&&t.jsx(Qn,{mode:W,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:h?"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(kt,{size:14})})]}),!Ve(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Hn,{size:14})}),!y&&!Ve(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Tt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:M,children:[t.jsxs("div",{className:`dashboard-header-hidden${I?" is-drop-target":""}`,ref:O,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),T(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",T(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||T(!1)},onDrop:V=>{const oe=V.dataTransfer.getData("text/tab-key");V.preventDefault(),T(!1),ae(oe)},children:[t.jsxs("button",{type:"button",onClick:()=>N(!f),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${b!=null&&b.toggleHiddenTabs?` (${b.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx($o,{size:16}),v.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:v.length})]}),f&&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(Ua,{value:b==null?void 0:b.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[d&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d,children:"Reset panels"}),v.length>0&&L&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{L(),N(!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(Ua,{value:b==null?void 0:b.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:at(e)})]}),v.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:v.map(V=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{C==null||C(V),N(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:at(V)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[v.indexOf(V)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",v.indexOf(V)+1]}):null,ls(V)]})]},V.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>k(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Br,{size:16}),te>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:te})]}),g&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Te.map(V=>t.jsx(za,{conversation:V,isAttention:!0,shortcutIndex:we.indexOf(V)>=0?we.indexOf(V)+1:void 0,onClick:()=>{u==null||u(V),k(!1)}},V.tabKey))]}),Ne.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),Ne.map(V=>t.jsx(za,{conversation:V,shortcutIndex:we.indexOf(V)>=0?we.indexOf(V)+1:void 0,onClick:()=>{u==null||u(V),k(!1)}},V.tabKey))]}),te===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function xt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Yd(e,s){return String(e||"")!==String(s||"")}function Xd(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),o=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!o&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(m=>String(m||"").toLowerCase()).join(`
31
+ `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||o&&!Go(c.summaryMetadata).map(m=>m.toLowerCase()).join(`
32
+ `).includes(o)))}function Qd(e,s="recent"){const r=e.slice();return r.sort((n,o)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(s==="messages"){const i=(Number(o.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(o.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function di(e,s={}){return Qd(Xd(e,s),s.sortMode||"recent")}function Lr(e){return e?"Resume saved history":"Start fresh"}function Jn(e){return e?"Resuming saved history…":"Starting fresh…"}function Jd(){return"Start fresh"}function ui(e,s=!1){return e==="cli"?Lr(s):e==="ide"?"Start IDE":"Start ACP session"}function mi(e,s=!1){return e==="cli"?Jn(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Zd(){return"Recover hosted runtime"}function eu(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function tu(){return"Open saved history"}function su(){return"Saved History"}function Zn(){return"Use saved history when you want continuity in the same provider conversation."}function ru(){return"No saved history found yet."}function nu(){return"Refresh saved history"}function au(){return"Refreshing saved history…"}function es(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ts(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 Ns(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ss(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ea(e){return`Resume saved history with ${e}?`}function ta(){return"Review or change the target workspace before resuming saved history."}function ou(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 sa({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:m,onClose:p,onNewChat:u,onSwitchSession:x,onRefreshHistory:v,onResumeSavedSession:C}){var y;const L=s.find(h=>h.id===e.routeId),d=(L==null?void 0:L.chats)||[],g=(y=L==null?void 0:L.activeChat)==null?void 0:y.id,k=Xe(e)&&!Ve(e),[f,N]=a.useState(()=>xt()),R=l||f,b=h=>{if(m){m(h);return}N(h)},w=a.useMemo(()=>di(o,{textQuery:R.textQuery,workspaceQuery:R.workspaceQuery,modelQuery:R.modelQuery,resumableOnly:R.resumableOnly,sortMode:R.sortMode}),[R.modelQuery,R.resumableOnly,R.sortMode,R.textQuery,R.workspaceQuery,o]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[t.jsx("div",{onClick:p,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:k?su():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Kd(e)}),k&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Zn()})]}),t.jsx("button",{onClick:p,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(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!k&&t.jsx("button",{onClick:u,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"}),k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:R.textQuery,onChange:h=>b({...R,textQuery:h.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:R.workspaceQuery,onChange:h=>b({...R,workspaceQuery:h.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:R.modelQuery,onChange:h=>b({...R,modelQuery:h.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:R.sortMode,onChange:h=>b({...R,sortMode:h.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:R.resumableOnly,onChange:h=>b({...R,resumableOnly:h.target.checked})}),"Resume-ready only"]})]}),w.map(h=>{const W=e.providerSessionId===h.providerSessionId,I=W||!h.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!C||C(h)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${I?"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 ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:h.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ou(h.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:h.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:[h.workspace||"Workspace unknown",cs(h.summaryMetadata)?` · ${cs(h.summaryMetadata)}`:"",h.messageCount>0?` · ${h.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:W?"ACTIVE":h.canResume?c===h.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},h.id)})]}):d.map(h=>t.jsxs("div",{onClick:()=>{x(e.routeId,h.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${g===h.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 ${g===h.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.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:[h.id.substring(0,12),"..."]}),g===h.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},h.id)),(k&&!i&&w.length===0||!k&&d.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(Jc,{size:32})}),t.jsx("div",{className:"text-[13px]",children:k?o.length>0?"No saved history matches these filters.":ru():"No recent chat sessions found."})]}),k&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:au()})})]}),t.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:t.jsx("button",{onClick:v,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(Is,{size:13})," ",k?nu():"Refresh History"]})})})]})]});return typeof document>"u"?j:zs.createPortal(j,document.body)}const Fa={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 fi({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=Fa[n.type]||Fa.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(kt,{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:l=>{l.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const iu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function cu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function lu(e){return e.sessionId||e.instanceId||e.agentType}function nn(e,s){return e||s}function Va(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 pi(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=At(r,{fallbackId:r.id}));return s}function xi(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 ra(e,s,r={}){return du(e,s,xi(e,r))}function du(e,s,r={}){var v,C,L,d,g,k;const n=[],o=r.machineName,i=r.connectionState,c=cu(e),l=rt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(f=>{var N,R;return{sessionId:f.id,instanceId:f.id,providerSessionId:f.providerSessionId,transport:f.transport,agentType:f.providerType,agentName:f.providerName||rt(f.providerType),status:f.status,title:f.title,lastMessagePreview:f.lastMessagePreview,lastMessageRole:f.lastMessageRole,lastMessageAt:f.lastMessageAt,lastMessageHash:f.lastMessageHash,messages:((N=f.activeChat)==null?void 0:N.messages)||[],activeModal:((R=f.activeChat)==null?void 0:R.activeModal)||void 0,unread:f.unread,lastSeenAt:f.lastSeenAt,lastUpdated:f.lastUpdated,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden}}):[],p=iu(e),u=e.activeChat||{title:""},x=u.title&&String(u.title).trim()?String(u.title).trim():"";if(p){const f=e.sessionId||e.instanceId,N=La(e.type),R=(v=e.activeChat)==null?void 0:v.activeModal,b=R&&Array.isArray(R.buttons)&&R.buttons.length>0,w=jt((C=e.activeChat)==null?void 0:C.status,{activeModal:(L=e.activeChat)==null?void 0:L.activeModal})||jt((g=(d=e.agents)==null?void 0:d[0])==null?void 0:g.status)||"idle",j=e.activeChat||{title:"",messages:[]};let y=j.title&&String(j.title).trim()?String(j.title).trim():"";const h=(k=e.activeChat)==null?void 0:k.id,W=e.chats;if(h&&Array.isArray(W)&&W.length>0){const S=W.find(H=>H.id===h||H.id&&String(H.id)===String(h));S!=null&&S.title&&String(S.title).trim()&&(y=String(S.title).trim())}const I=(Xe(e)||Ve(e),e.type),T=(Xe(e)||Ve(e))&&_a(y,N,I)?"":y,M=j.messages||[],O=Va(s,[e.id,f]),_=Ka(M,O);n.push({routeId:e.id,sessionId:f,providerSessionId:e.providerSessionId,nativeSessionId:f,transport:e.transport,daemonId:e.daemonId||void 0,mode:Xe(e)?e.mode||"terminal":"chat",agentName:N,agentType:I,status:w,title:T,messages:[...M,..._],resume:e.resume,hostIdeType:!Xe(e)&&!Ve(e)?e.type:void 0,workspaceName:c,displayPrimary:c||T||(Xe(e)?e.mode==="chat"?N:"Terminal":N),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:b?R.buttons:void 0,modalMessage:b?R.message:void 0,streamSource:"native",tabKey:nn(f,e.id),machineName:o,connectionState:i})}if(p&&(Xe(e)||Ve(e)))return n;for(const f of m){const N=f.activeModal&&Array.isArray(f.activeModal.buttons)&&f.activeModal.buttons.length>0,R=Pl(f),b=lu(f),w=`${e.id}:${b}`,j=f.title&&String(f.title).trim()||"",y=_a(j,f.agentName,f.agentType)?"":j,h=f.messages||[],W=Va(s,[w,f.sessionId,f.instanceId]),I=Ka(h,W);(f.transport==="cdp-webview"||f.sessionId||f.providerSessionId||h.length>0||I.length>0||N||y||!["idle","panel_hidden","disconnected","not_monitored"].includes(R))&&n.push({routeId:e.id,sessionId:f.sessionId||f.instanceId,providerSessionId:f.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:f.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:f.agentName,agentType:f.agentType,status:R,title:y,messages:[...h,...I],hostIdeType:e.type,workspaceName:c,displayPrimary:c||x||y||l,displaySecondary:`${l} · ${f.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:f.lastMessagePreview,lastMessageRole:f.lastMessageRole,lastMessageAt:f.lastMessageAt,lastMessageHash:f.lastMessageHash,lastUpdated:f.lastUpdated||e.lastUpdated,modalButtons:N?f.activeModal.buttons:void 0,modalMessage:N?f.activeModal.message:void 0,streamSource:"agent-stream",tabKey:nn(f.sessionId||f.instanceId,w),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:La(e.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:nn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function uu(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 mu(e,s){const r=uu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const hi=[{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:"🏄"}],bi=[{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:"🧩"}],gi=[{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:"🟠"}],fu=hi,pu=bi,xu=gi;function ds(...e){return kc(Nc(e))}function hu({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:ds("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 yi({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(hu,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ds("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Dt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:ds("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 vi({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:ds("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 bu={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"},gu={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function yu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ds("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",bu[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:gu[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 vu={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"},wu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ju({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ds("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",vu[e],r),children:[t.jsx("span",{className:ds("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",wu[e])}),n]})}const _n="adhdev:themechange";function ku(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ps(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?ku():e}function wi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function jr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(_n,{detail:{preference:e,theme:s}}))}function Nu(){const e=ps(),s=xs(e);wi(s),jr(e,s)}function na(){const[e,s]=a.useState(ps),[r,n]=a.useState(()=>xs(ps()));a.useEffect(()=>{wi(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=m=>{if(e==="system"){const p=m.matches?"light":"dark";n(p),jr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),a.useEffect(()=>{const c=m=>{const p=m.detail||{},u=p.preference,x=p.theme;s(u==="dark"||u==="light"||u==="system"?u:ps()),n(x==="dark"||x==="light"?x:xs(ps()))},l=m=>{if(m.key!=="theme")return;const p=ps(),u=xs(p);s(p),n(u)};return window.addEventListener(_n,c),window.addEventListener("storage",l),()=>{window.removeEventListener(_n,c),window.removeEventListener("storage",l)}},[]);const o=a.useCallback(c=>{const l=xs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}jr(c,l)},[]),i=a.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",m=xs(l);n(m);try{localStorage.setItem("theme",l)}catch{}return jr(l,m),l})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Ga={dark:"Dark",light:"Light",system:"System"};function Su({collapsed:e}){const{preference:s,cycleTheme:r}=na(),n=s==="dark"?t.jsx(el,{size:16}):s==="light"?t.jsx(Zc,{size:16}):t.jsx(tl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ga[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Ga[s]})]})}function Jt({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 Cu({onPrefChange:e}){const[s,r]=zl(),n=(o,i)=>{r({[o]:i}),e==null||e(o,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Br,{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(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{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(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(sl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(rl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fs,{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 _r(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Iu(e,s){const r=_r(e),n=_r(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 ji(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Os(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Iu(r,s)>=0)return!1;const n=_r(r),o=_r(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Au(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function an(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(vi,{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(Lu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function qa({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 zs.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:l=>l.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 Mu(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...fu,...pu,...xu].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 Lu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var O,_;const[i,c]=a.useState("idle"),[l,m]=a.useState(""),[p,u]=a.useState(null),[x,v]=a.useState("idle"),[C,L]=a.useState(""),d=e.version||null,g=((O=e.machine)==null?void 0:O.platform)||((_=e.system)==null?void 0:_.platform)||"",k=At(e,{fallbackId:e.id}),f=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",N=s.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),R=s.filter(S=>S.daemonId===e.id&&S.transport==="pty"),b=s.filter(S=>S.daemonId===e.id&&S.transport==="acp"),w=e.p2p,j=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const S=Au(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(c("done"),m(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(c("done"),m(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(S.error||"Upgrade failed"))}catch(S){c("error"),m(an(S,"Connection lost during upgrade"))}}},y=async()=>{if(u(null),!!n){v("loading");try{await n(e.id),v("done"),L("Machine disconnected.")}catch(S){v("error"),L(an(S,"Failed to disconnect"))}}},h=async()=>{if(u(null),!!o){v("loading");try{await o(e.id),v("done"),L("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){v("error"),L(an(S,"Failed to revoke token"))}}},W="0.8.62",I=ji(e,W),T=Os(e,W),M=N.length+R.length+b.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:f}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:k}),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),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${I?"":"bg-bg-secondary"}`,style:I?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!I&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&I&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${W}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${W}`}`}`}),n&&t.jsx("button",{onClick:()=>u("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:()=>u("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(ju,{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:[w&&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 ${w.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${w.state==="connecting"||w.state==="new"?"animate-pulse":""}`,style:w.state==="connecting"||w.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",w.state==="connected"?"connected":w.state==="connecting"||w.state==="new"?"connecting...":w.state||"off"]}),w.peers!==void 0&&w.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",w.peers," peer",w.peers!==1?"s":"",")"]})]}),w&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(S=>{const H=Mu(S.type),q=S.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:H.icon}),t.jsx("span",{children:H.name}),q!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${q?"bg-green-400":"animate-pulse"}`,style:q?void 0:{background:"var(--status-warning)"},title:q?"CDP connected":"CDP connecting..."})]},S.id)}),R.map(S=>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:S.cliName||"CLI"})]},S.id)),b.map(S=>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:S.cliName||"ACP"})]},S.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||C)&&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:C||l})]}),p==="disconnect"&&t.jsx(qa,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
33
+
34
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
+
36
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:y,onCancel:()=>u(null)}),p==="revoke"&&t.jsx(qa,{title:"⚠️ Remove Machine",message:`Remove "${k}" from your dashboard?
37
+
38
+ This will:
39
+ • Immediately disconnect the machine
40
+ • Delete the machine registration
41
+ • Require restarting ADHDev on that machine
42
+
43
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:h,onCancel:()=>u(null)})]})}const _u=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ru(){const{preference:e,setPreference:s}=na();return t.jsx("div",{className:"flex gap-2",children:_u.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 Pu(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 Du(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function on(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ya(e){const{r:s,g:r,b:n}=Du(e);return .2126*on(s)+.7152*on(r)+.0722*on(n)}function Xa(e,s){const r=Ya(e),n=Ya(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function ki(e){const s=Pu(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Xa(s,r)>=Xa(s,n)?r:n}const Rn={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},Pn={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},Eu=[{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"}}}],Ni="adhdev-chat-theme",Si="adhdev-chat-theme-custom";function kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ni)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Si);if(s){const r=JSON.parse(s);return{...e==="dark"?Rn:Pn,...r[e]}}}catch{}return e==="dark"?Rn:Pn}function dr(e,s){try{localStorage.setItem(Si,JSON.stringify({dark:e,light:s}))}catch{}}function Lt(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 Rr(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 $u={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Hs(e,s){var o;const r=(o=$u[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",Rr(r,24)),n.style.setProperty("--accent-on-primary",ki(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Rr(r,18)})`),n.style.setProperty("--border-accent",Lt(r,.35)),n.style.setProperty("--nav-active-bg",Lt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Lt(r,.06)}`)}function ss(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Lt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Lt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Lt(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",Lt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Lt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Rr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",ki(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Rr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Lt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Lt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Lt(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 ${Lt(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 aa(){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 Bu(e){try{localStorage.setItem(Ni,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=rs()?"dark":"light";ss(Et(s))}else aa(),Hs(e,rs()?"dark":"light")}function Wu(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=rs()?"dark":"light";ss(Et(s))}else aa(),Hs(e,rs()?"dark":"light")}function rs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 Rs({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 Ku({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>Et(r));a.useEffect(()=>{o(Et(r))},[r]);const i=a.useCallback((c,l)=>{o(m=>{const p={...m,[c]:l},x=Et(r==="dark"?"light":"dark");return r==="dark"?dr(p,x):dr(x,p),ss(p),s(p),p})},[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(Rs,{title:"App Background",children:[t.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Rs,{title:"App Text",children:[t.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Rs,{title:"Borders & Accent",children:[t.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Rs,{title:"Chat Bubbles",children:[t.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Rs,{title:"Chat Layout",children:[t.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(wt,{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?Rn:Pn,m=Et(e?"light":"dark");e?dr(c,m):dr(m,c),o(c),ss(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 Ou(){const[e,s]=a.useState(kr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Et("dark"));a.useEffect(()=>{n(rs());const m=new MutationObserver(()=>{const x=rs();n(x);const v=kr();v==="custom"?ss(Et(x?"dark":"light")):Hs(v,x?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=rs();n(x);const v=kr();v==="custom"?ss(Et(x?"dark":"light")):Hs(v,x?"dark":"light")};return p.addEventListener("change",u),()=>{m.disconnect(),p.removeEventListener("change",u)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ss(Et(r?"dark":"light")):(aa(),Hs(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=m=>{s(m),Bu(m)},l=[...Eu,{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:l.map(m=>{const p=e===m.id,u=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:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.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:u.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:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&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(Ku,{dark:r,onColorsChange:m=>i(m)})]})}const Ci="adhdev_mobileDashboardMode_v1";function Ii(){try{return localStorage.getItem(Ci)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Hu(e){try{localStorage.setItem(Ci,e)}catch{}}function Uu(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(Ii()==="chat")},[]),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ut,{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),Hu(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function zu(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 Fu(e,s){const{sendData:r}=Rt(),{injectEntries:n,getIdes:o}=Ir(),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 l=c.map(m=>Vt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const u=o().find(v=>v.id===m),x=zu(u,m,p);n([x])}));return()=>{l.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Vu=4e3;function Ai(e,s){const{sendData:r}=Rt(),[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 l=null;const m=Vt.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}:{}}},p=>{l&&(clearTimeout(l),l=null),o(p.diagnostics),c(!1)});return m.initialSendAccepted?l=setTimeout(()=>{c(!1)},Vu):c(!1),()=>{l&&clearTimeout(l),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 Gu(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ti(e){const{sendData:s}=Rt(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Gu(e);if(!o||!e.sessionId||!s){n({});return}const i=Vt.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}),as.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 Mi="adhdev_hiddenTabs";function qu(){try{const e=localStorage.getItem(Mi);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ms(e){try{localStorage.setItem(Mi,JSON.stringify([...e]))}catch{}}function Yu(){const[e,s]=a.useState(qu),r=a.useCallback(p=>{s(u=>{const x=new Set(u);return x.has(p)?x.delete(p):x.add(p),ms(x),x})},[]),n=a.useCallback(p=>{s(u=>{if(u.has(p))return u;const x=new Set(u);return x.add(p),ms(x),x})},[]),o=a.useCallback(p=>{s(u=>{if(!u.has(p))return u;const x=new Set(u);return x.delete(p),ms(x),x})},[]),i=a.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return ms(u),u})},[]),c=a.useCallback((p,u)=>{s(x=>{const v=new Set(x);for(const C of u)v.add(C);return ms(v),v})},[]),l=a.useCallback((p,u)=>{s(x=>{const v=new Set(x);for(const C of u)v.delete(C);return ms(v),v})},[]),m=a.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:m}}function Qa(e,s){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=s[r];return!n||e.mode===n?e:{...e,mode:n}}function Xu(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(o=>{const i=Qa(o,s),c=Array.isArray(o.childSessions)?o.childSessions.map(m=>Qa(m,s)):o.childSessions,l=c!==o.childSessions;return i!==o||l?(r=!0,{...i,...l?{childSessions:c}:{}}):o});return r?n:e}function Ja(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Qu({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Vl()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:ii(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return ql(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const m=Date.now(),p={};for(const[u,x]of Object.entries(l))m-x<5e3&&(p[u]=x);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const m=l.filter(p=>p.timestamp>c).slice(-100);return m.length===l.length?l:m})},6e4);return()=>clearInterval(i)},[n]),null}function Ju(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 cn(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 Za(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1];return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??"")].join(":")}function Zu(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastUpdated||""),Za(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),Za(r.activeChat)].join(":"))].join("|")}function em(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 tm(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 sm(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 rm(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function nm(e){const s=rm(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=Vs(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function am({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useMemo(()=>Ju(e),[e]),c=a.useMemo(()=>pi(e),[e]),l=a.useRef([]),m=a.useRef([]),p=a.useRef([]),u=a.useRef(new Map),x=a.useRef(new Map),v=a.useMemo(()=>{const b=new Map,w=[];for(const W of i){const{connectionState:I="new",machineName:T}=xi(W,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),M=tm(W,r),O=Zu(W),_=u.current.get(W.id);if(_&&_.ide===W&&_.sourceSignature===O&&_.connectionState===I&&_.machineName===T&&sm(_.localRefs,M)){b.set(W.id,_),w.push(..._.conversations);continue}const S=ra(W,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),H={ide:W,sourceSignature:O,connectionState:I,machineName:T,localRefs:M,conversations:S};b.set(W.id,H),w.push(...S)}u.current=b;const j=new Map,y=W=>{const I=nm(W),T=x.current.get(W.tabKey);if(T&&T.signature===I)return j.set(W.tabKey,T),T.timestamp;const M={signature:I,timestamp:li(W)||(T==null?void 0:T.timestamp)||0};return j.set(W.tabKey,M),M.timestamp},h=[...w].sort((W,I)=>Mr(W,I,y));return x.current=j,h},[i,r,s,c]),C=a.useMemo(()=>{const b=em(v,n);return cn(l.current,b)?l.current:(l.current=b,b)},[v,n]),L=a.useMemo(()=>{const b=new Map,w=Array.from(new Set(C.map(j=>j.routeId)));for(const j of w){const y=Bt(C,j);y&&b.set(j,y)}return b},[C]),d=a.useMemo(()=>{const b=new Map;for(const w of C)if(w.sessionId&&b.set(w.sessionId,w),w.streamSource==="native"&&w.sessionId){const j=L.get(w.routeId);j&&b.set(w.sessionId,j)}return b},[C,L]),g=a.useMemo(()=>{const b=new Map;for(const w of C)w.sessionId&&b.set(w.sessionId,w),b.set(w.routeId,L.get(w.routeId)||w),b.set(w.tabKey,w);return b},[C,L]),k=a.useCallback(b=>{if(b)return d.get(b)},[d]),f=a.useCallback(b=>{if(b)return g.get(b)},[g]),N=a.useMemo(()=>{const b=C.filter(w=>!o.has(w.tabKey));return cn(m.current,b)?m.current:(m.current=b,b)},[C,o]),R=a.useMemo(()=>{const b=N.map(w=>w.tabKey);return cn(p.current,b)?p.current:(p.current=b,b)},[N]);return{chatIdes:i,conversations:C,visibleConversations:N,visibleTabKeys:R,resolveConversationBySessionId:k,resolveConversationByTarget:f}}function om({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(l=>{const m=new URLSearchParams(l);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function im({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{nt.setIdes(e)},[e]),a.useEffect(()=>{nt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),a.useEffect(()=>{const i=nt.onToast(m=>{r(u=>u.some(v=>v.message===m.message&&m.timestamp-v.timestamp<3e3)?u:[...u.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const p=m.duration||5e3;setTimeout(()=>r(u=>u.filter(x=>x.id!==m.id)),p)}),c=nt.onSystemMessage((m,p)=>{var C,L;const u=o(m),x=(C=p._localId)==null?void 0:C.startsWith("sys_approval_"),v=!!(u&&(u.status==="waiting_approval"||(L=u.modalButtons)!=null&&L.length||u.modalMessage));x&&v||n(d=>({...d,[m]:[...d[m]||[],p]}))}),l=nt.onClearSystemMessage((m,p)=>{n(u=>{var x;return(x=u[m])!=null&&x.length?{...u,[m]:u[m].filter(v=>{var C;return!(v.role==="system"&&((C=v._localId)!=null&&C.startsWith(p)))})}:u})});return()=>{i(),c(),l()}},[r,n]),a.useEffect(()=>{const i=ni.on("status_event",c=>{nt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=l=>{var g;const m=l.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 p=m.targetSessionId||m.targetKey||m.daemonId,u=o(p),x=(u==null?void 0:u.routeId)||m.daemonId;if(!x)return;const v=Number(m.buttonIndex),C=m.button||((g=u==null?void 0:u.modalButtons)==null?void 0:g[v])||"Approve",L=String(C).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);s(x,"resolve_action",{action:d?"approve":"reject",button:C,...Number.isFinite(v)&&{buttonIndex:v},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[o,s])}const cm="adhdev_dashboardLayout_v1",lm="adhdev_dashboardDockview_v1",dm="adhdev_dashboardDockviewHiddenRestore_v1",Ps={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function oa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Li(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function _i(e){return`${cm}:${e}`}function um(e){const s=_i(e);return oa(s,null)}function mm(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=_i(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Ri(e){return`${lm}:${e}`}function fm(e){const s=Ri(e);return oa(s,null)}function pm(e,s){try{const r=Ri(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Pi(e){return`${dm}:${e}`}function xm(e){const s=Pi(e);return oa(s,{})}function hm(e,s){try{const r=Pi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function bm(){return{groupAssignments:[...Ps.groupAssignments],focusedGroup:Ps.focusedGroup,groupActiveTabIds:{...Ps.groupActiveTabIds},groupTabOrders:{...Ps.groupTabOrders},groupSizes:[...Ps.groupSizes]}}function gm(){const[e]=a.useState(()=>Li(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[l,m]=a.useState({}),[p,u]=a.useState([]),[x,v]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,L]=a.useState(!1),d=a.useCallback(()=>{if(C)return;const g=um(e)??bm();r(new Map(g.groupAssignments)),o(g.focusedGroup),c(g.groupActiveTabIds),m(g.groupTabOrders),u(g.groupSizes),L(!0)},[C,e]);return a.useEffect(()=>{C&&mm(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[C,e,s,n,i,l,p]),a.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),k=f=>v(f.matches);return g.addEventListener("change",k),()=>g.removeEventListener("change",k)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:m,groupSizes:p,setGroupSizes:u,isMobile:x,hasHydratedStoredLayout:C,hydrateStoredLayout:d}}function ym(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 vm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:m,historyModalOpen:p,activeConv:u,isRefreshingHistory:x,ides:v,handleRefreshHistory:C}){const L=a.useRef(!1),d=a.useRef(!1),g=a.useRef(null),k=a.useRef(!1);a.useEffect(()=>{if(!e||L.current||s.length===0)return;if(!o){i();return}const f=r(e);if(!f)return;const N=n.get(f.tabKey)??0;c(R=>({...R,[N]:f.tabKey})),l(N),L.current=!0,d.current=!0,g.current!=null&&(window.clearTimeout(g.current),g.current=null),m(R=>{const b=new URLSearchParams(R);return b.delete("activeTab"),b},{replace:!0})},[e,s,r,n,o,i,c,l,m]),a.useEffect(()=>{if(!(d.current||o)&&s.length!==0){if(!e){i(),d.current=!0;return}if(L.current){d.current=!0;return}if(g.current==null)return g.current=window.setTimeout(()=>{g.current=null,!(d.current||o)&&(i(),d.current=!0)},1500),()=>{g.current!=null&&(window.clearTimeout(g.current),g.current=null)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!p){k.current=!1;return}if(!u||k.current||x)return;const f=v.find(N=>N.id===u.routeId);f&&(!f.chats||f.chats.length===0||ym(f.chats,u))&&(k.current=!0,C())},[p,u,x,v,C]),a.useEffect(()=>{if(!u)return;let f=null,N=0,R=-1,b=0;const w=()=>{f=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(h=>h.offsetParent!==null);if(j.length===0){N<18&&(N+=1,f=requestAnimationFrame(w));return}let y=0;for(const h of j)h.scrollTop=h.scrollHeight,y+=h.scrollHeight;y===R?b+=1:(b=0,R=y),N+=1,!(b>=2||N>=18)&&(f=requestAnimationFrame(w))};return f=requestAnimationFrame(w),()=>{f!=null&&cancelAnimationFrame(f)}},[u==null?void 0:u.tabKey])}function wm({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:l}){const[m,p]=a.useState(null),[u,x]=a.useState(null),v=a.useMemo(()=>{if(e||!n)return null;const k=l(n);return k&&!Xe(k)&&!Ve(k)?k:null},[e,n,l]),C=a.useMemo(()=>{const k=m==null?void 0:m.routeId;if(!k)return null;const f=m!=null&&m.tabKey?i.find(N=>N.tabKey===m.tabKey):o?i.find(N=>N.tabKey===o):null;return(f==null?void 0:f.routeId)===k?f:Bt(i,k)},[i,m,o]),L=a.useMemo(()=>{if(C)return c.find(k=>k.id===C.routeId)},[c,C]);a.useEffect(()=>{v&&(p({routeId:v.routeId,tabKey:Da(v)}),x(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const d=a.useCallback(k=>{k&&(p({routeId:k.routeId,tabKey:Da(k)}),x(k))},[]),g=a.useCallback(()=>{p(null),x(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:L,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:d,closeRemoteDialog:g}}function gs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Xe(e)||Ve(e)?{agentType:It(e)}:e.streamSource==="agent-stream"?{agentType:It(e)}:s}function Qs(e){return e?Ar(e):""}function Ds(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ln(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 eo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[l,m]=a.useState(!1),[p,u]=a.useState(!1),x=a.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(g){console.error("Launch failed",g)}},[e]),v=a.useCallback(async(d,g)=>{try{const k=d||(s==null?void 0:s.daemonId)||"",f=await e(k,"switch_chat",{id:g,sessionId:g,...gs(s)}),N=f==null?void 0:f.result;if((f==null?void 0:f.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ds(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ds(o,`⚠️ Switch error: ${N}`):Ds(o,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),Ds(o,`❌ Switch failed: ${k.message||"connection error"}`)}},[s,e,o]),C=a.useCallback(async()=>{if(!(!s||l)){m(!0);try{const d=Qs(s);await e(d,"new_chat",{...gs(s)}),c(g=>({...g,[s.tabKey]:Date.now()})),i(g=>({...g,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,l,e,c,i]),L=a.useCallback(async()=>{var d,g;if(!(!s||p)){u(!0);try{const k=Qs(s),f=async()=>e(k,"list_chats",{forceExpand:!0,...gs(s)});let N=await f(),R=(N==null?void 0:N.chats)||((d=N==null?void 0:N.result)==null?void 0:d.chats);ln(R,s)&&(await new Promise(b=>setTimeout(b,450)),N=await f(),R=(N==null?void 0:N.chats)||((g=N==null?void 0:N.result)==null?void 0:g.chats)),N!=null&&N.success&&Array.isArray(R)&&(n(s.routeId,R),ln(R,s)&&!ln(r,s)&&Ds(o,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{u(!1)}}},[s,r,p,e,n,o]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:x,handleSwitchSession:v,handleNewChat:C,handleRefreshHistory:L}}function jm(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 km(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function to(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 ur(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const o={};n.forEach((c,l)=>{o[c]=l}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const m=o[l];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function so(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 Nm(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 Sm(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,l)=>c+l,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function ro(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 no(e){return Array(e).fill(100/e)}function Cm({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:m,visibleTabKeys:p}){const u=a.useRef(null),x=a.useMemo(()=>ur(e,p),[e,p]),v=x.assignments,C=a.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),L=C>1,d=a.useCallback((b,w)=>{s(j=>{const y=new Map(ur(j,p).assignments);return w===0?y.delete(b):y.set(b,w),y}),n(j=>({...j,[w]:b})),r(w)},[s,p,n,r]),g=a.useCallback(b=>{s(w=>{const j=ur(w,p).assignments,y=new Map;for(const[h,W]of j)W!==b&&(W>b?y.set(h,W-1):y.set(h,W));return y}),c(w=>{if(w.length<=1)return[];const j=[...w];j.splice(b,1);const y=j.reduce((h,W)=>h+W,0);return y>0?j.map(h=>h/y*100):[]}),r(0)},[s,p,c,r]),k=a.useCallback((b,w)=>{w.preventDefault();const j=u.current;if(!j)return;const y=w.clientX,h=j.offsetWidth,W=i.length===C?[...i]:no(C),I=M=>{const _=(M.clientX-y)/h*100,S=[...W];S[b]=Math.max(15,W[b]+_),S[b+1]=Math.max(15,W[b+1]-_),c(S)},T=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",T)},[i,C,c]),f=a.useCallback((b,w,j)=>{if(C>=4)return;const y=j==="left"?w:w+1;s(h=>{const W=ur(h,p).assignments,I=new Map;for(const T of m){const M=W.get(T.tabKey)??0,O=M>=y?M+1:M;O>0&&I.set(T.tabKey,O)}return y>0&&I.set(b,y),I}),c(h=>{const W=h.length===C?[...h]:no(C),I=W[w]??100/C,T=Math.max(15,I/2),M=Math.max(15,I/2),O=[...W];O[w]=T,O.splice(y,0,M);const _=O.reduce((S,H)=>S+H,0);return O.map(S=>S/_*100)}),n(h=>{const W=ro(h,y);return W[y]=b,W}),o(h=>{const W=ro(h,y);return W[y]=[b],W}),r(y)},[C,s,p,m,c,n,o,r]);a.useEffect(()=>{jm(e,v)||s(v)},[e,v,s]),a.useEffect(()=>{const{mapping:b,usedGroups:w}=x;n(j=>{const y=so(j,b);return to(j,y)?j:y}),o(j=>{const y=so(j,b);return to(j,y)?j:y}),r(j=>{const y=l?0:Nm(j,w,b);return j===y?j:y}),c(j=>{const y=l?[]:Sm(j,w,x.groupCount);return km(j,y)?j:y})},[x,l,n,o,r,c]);const N=a.useMemo(()=>{const b=Array.from({length:C},()=>[]);for(const w of m){const j=v.get(w.tabKey)??0,y=Math.min(j,C-1);b[y].push(w)}return b},[m,v,C]),R=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:v,numGroups:C,isSplitMode:L,groupedConvs:N,moveTabToGroup:d,closeGroup:g,handleResizeStart:k,splitTabRelative:f,clearAllSplits:R}}function Im({ides:e,sendDaemonCommand:s}){const r="0.8.62",n=a.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:ji(u,r)).sort((u,x)=>Number(Os(x,r))-Number(Os(u,r))),[r,e]),o=a.useMemo(()=>n.some(u=>Os(u,r)),[r,n]),[i,c]=a.useState(!1),[l,m]=a.useState({}),p=a.useCallback(async u=>{var x,v;m(C=>({...C,[u]:"upgrading"}));try{const C=await s(u,"daemon_upgrade",{});(x=C==null?void 0:C.result)!=null&&x.upgraded||(v=C==null?void 0:C.result)!=null&&v.success?m(L=>({...L,[u]:"done"})):m(L=>({...L,[u]:"error"}))}catch{m(C=>({...C,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}function ao(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ia(e){return e instanceof Error?e.message:String(e||"")}function oo(e){const s=ia(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function io(e,s){const r=ia(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Hr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[l,m]=a.useState(!1),p=a.useRef(!1),u=a.useRef(null),x=a.useCallback(async d=>{if(!s)return;const g=d.trim();if(!g||p.current)return;const k=s.tabKey,f=Date.now(),N=u.current;if(N&&N.tabKey===k&&N.message===g&&f-N.timestamp<2e3)return;p.current=!0,m(!0),u.current={tabKey:k,message:g,timestamp:f};const R=`${f}-${Math.random().toString(36).slice(2,8)}`,b={role:"user",content:g,timestamp:f,_localId:R},w=!(Xe(s)||Ve(s));w&&r(j=>({...j,[k]:[...j[k]||[],b]}));try{const j=Qs(s);if(!j)return;const y=await e(j,"send_chat",{message:g,...gs(s)}),h=ao(y);if(w&&(h!=null&&h.deduplicated||(h==null?void 0:h.sent)===!1)){r(W=>({...W,[k]:(W[k]||[]).filter(I=>I._localId!==R)}));return}if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Send failed");setTimeout(()=>{const W=Date.now()-6e4;r(I=>{const T=I[k];if(!T)return I;const M=T.filter(O=>O.timestamp>W);return M.length===T.length?I:{...I,[k]:M}})},6e4)}catch(j){const y=ia(j);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",j),w&&r(h=>({...h,[k]:(h[k]||[]).filter(W=>W._localId!==R)}))}finally{p.current=!1,m(!1)}},[s,e,r]),v=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),C=a.useCallback(async d=>{if(s)try{const k=(s.modalButtons||[]).indexOf(d),f=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f),R=Qs(s);if(!R)return;const b=await e(R,"resolve_action",{button:d,action:N?"approve":"reject",...k>=0&&{buttonIndex:k},...gs(s)}),w=ao(b);w.success||n(j=>[...j,{routeId:s.tabKey,text:io(d,w==null?void 0:w.error),timestamp:Date.now()}])}catch(g){oo(g)||console.error("[ModalButton] Error:",g),n(k=>[...k,{routeId:s.tabKey,text:oo(g)?io(d,g):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),L=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:x,handleRelaunch:v,handleModalButton:C,handleFocusAgent:L}}const ca=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:C,scrollToBottomRequestNonce:L,isInputActive:d=!0}){const g=Ti(s),k=g.status||g.modalMessage||g.modalButtons?{...s,...g.status?{status:g.status}:{},...g.modalMessage!==void 0?{modalMessage:g.modalMessage}:{},...g.modalButtons!==void 0?{modalButtons:g.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(zo,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.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(is,{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:l,children:"Relaunch with CDP"})]})}):null,k.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(Hd,{activeConv:k,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Tn,{activeConv:k,ideEntry:o,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:C,scrollToBottomRequestNonce:L,isInputActive:d})})]}):t.jsx(Tn,{activeConv:k,ideEntry:o,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:C,scrollToBottomRequestNonce:L,isInputActive:d})]})},(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 Am({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:m,onOpenNativeConversation:p,onOpenMachine:u,onOpenHistory:x,onOpenRemote:v,onHideConversation:C,onStopCli:L,cliViewMode:d,onSetCliViewMode:g,handleSendChat:k,handleFocusAgent:f,handleModalButton:N,handleRelaunch:R}){const b=a.useRef(null),w=Xe(e)&&!s,j=w&&d==="terminal",y=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 ${y} 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(Kn,{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:at(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(ei,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>u(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[w&&d&&t.jsx(Qn,{mode:d,onChange:g,compact:!0}),w&&L&&t.jsx("button",{onClick:()=>{L(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(kt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:t.jsx(Hn,{size:14})}),!s&&!w&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(Tt,{size:14})}),C&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(e),type:"button",title:"Close chat",children:t.jsx(kt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ca,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:b,handleModalButton:N,handleRelaunch:R,handleSendChat:k,isSendingChat:c,handleFocusAgent:f,isFocusingAgent:l,actionLogs:o,userName:i})})]})}const dn={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 Tm(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Di(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(Tm())},[]);const l=a.useCallback(()=>{navigator.clipboard.writeText(dn[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:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:dn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:dn[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 Ei({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ut}];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 mr({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 fs({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 Es({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 fr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:m,isConnecting:p}=As(e.conversation),u=at(e.conversation),x=ls(e.conversation),v=oi(e.conversation,{requiresAction:s==="needs_attention"}),C=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",L=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",d=c?"text-text-secondary":"text-text-primary",g=c?"text-text-muted":"text-text-secondary",k=c?"text-text-secondary opacity-80":"text-text-muted",f=c?"text-text-muted opacity-80":"text-text-muted",N="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] ${C}`,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 ${L}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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 ${d}`,children:u}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${f}`,children:Uo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${g}`,children:[x,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):v==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${k}`,children:e.preview})]}),o&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&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 co({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 Mm({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:m,onShowConversation:p,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:v,onOpenSettings:C,onSectionChange:L,wsStatus:d="connected",isStandalone:g=!1}){const k=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",f=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,R=e==="machines"?"Machines":"Chats",b=g?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=g?"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 ${b}`,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:R}),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(Br,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:C,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(Er,{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] ${w}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:k?t.jsx(Es,{icon:t.jsx(co,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Es,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:g?"Waiting for your daemon":"Connect your machines",subtitle:g?"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:!g&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Di,{})})}):t.jsx(fs,{children:c.map((j,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(j.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:l(j.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:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.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(mr,{title:"Needs attention",className:"mb-0"}),t.jsx(fs,{children:s.map((j,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:m})},j.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(mr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(fs,{children:r.map((j,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:m})},j.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(mr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(fs,{children:n.map((j,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"working",getAvatarText:l,onOpenConversation:m})},j.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(mr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(fs,{children:o.map((j,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:m})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):k?t.jsx(Es,{icon:t.jsx(co,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):f?t.jsx(Es,{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(Ut,{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(Es,{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:u,children:"Restore all"})]}),t.jsx(fs,{className:"bg-bg-secondary/25",children:i.map((j,y)=>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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),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:l(at(j))}),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:at(j)}),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:ls(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.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(Ei,{section:e,onSectionChange:L})]})}function Lm(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 $i(e){const s=[e.workspace||"Workspace unknown"],r=cs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Lm(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Ur(...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 _m(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 zr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=_m(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 Rm(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}function Pm(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Fr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),o=Pm(n);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(o==null?void 0:o.path)=="string"?o.path:r,c=i.includes("\\")?"\\":"/",l=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${c}${u}`:`${p.replace(/[\\/]+$/,"")}${c}${u}`,m=Array.isArray(o==null?void 0:o.files)?o.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:i,directories:m}}function Vr({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:m,onConfirm:p}){const[u,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const v=Rm(r),C=u.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:l,"aria-label":"Close folder browser",children:t.jsx(kt,{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:()=>{!v||o||m(v)},disabled:!v||o,children:[t.jsx(Kn,{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:u,onChange:L=>x(L.target.value),onKeyDown:L=>{L.key!=="Enter"||!C||o||(L.preventDefault(),m(C))},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:()=>{!C||o||m(C)},disabled:!C||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(L=>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(L.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(vs,{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:L.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:L.path})]})]},L.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:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(C||r),disabled:!C&&!r||o,children:c})]})]})})}function la({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:m=!1,showArgsInput:p,argsValue:u,onArgsChange:x,showModelInput:v,modelValue:C,onModelChange:L,historyProviderNode:d,onConfirm:g,onCancel:k}){const f=n==null?void 0:n.find(N=>N.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:k,"aria-label":"Close launch confirmation",children:t.jsx(kt,{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:N=>i(N.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(N=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(f==null?void 0:f.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),d,r.map(N=>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:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),v&&L&&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:C||"",onChange:N=>L(N.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})]}),p&&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:u||"",onChange:N=>x(N.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:k,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:g,disabled:m,children:[t.jsx(Un,{size:14}),m?l:c]})]})]})})}function lo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ns(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?"⭐ ":""}${lo(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:lo(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(p=>p.key===m))return{options:i,selectedKey:m}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Dm(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Em(e){return[Dm(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function $m(e){return e.lastLaunchedAt?Wr(e.lastLaunchedAt):""}function Bi(e){return{metaText:Em(e),updatedLabel:$m(e)}}function un(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Bm({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ot,Ze,ht,ut;const c=tr(),[l,m]=a.useState(!1),p=(((ot=e.detectedIdes)==null?void 0:ot.length)||0)>0,u=a.useMemo(()=>(e.workspaces||[]).map(ue=>({id:ue.id,path:ue.path,label:ue.label})),[e]),x=e.defaultWorkspaceId||null,[v,C]=a.useState(x||((Ze=u[0])==null?void 0:Ze.id)||""),[L,d]=a.useState(""),[g,k]=a.useState(""),[f,N]=a.useState([]),[R,b]=a.useState(!1),[w,j]=a.useState(""),[y,h]=a.useState(!1),[W,I]=a.useState(un(p,s.length,r.length)),T=a.useRef(null),[M,O]=a.useState(null),_=a.useRef("__home__"),[S,H]=a.useState("__home__"),[q,A]=a.useState(""),[P,K]=a.useState(""),[z,X]=a.useState(""),[xe,Te]=a.useState([]),[Ne,we]=a.useState(()=>xt().textQuery),[te,ae]=a.useState(()=>xt().workspaceQuery),[V,oe]=a.useState(()=>xt().modelQuery),[re,Z]=a.useState(()=>xt().resumableOnly),[me,se]=a.useState(()=>xt().sortMode),[ce,ee]=a.useState(!1),[fe,ne]=a.useState(!1),ke=a.useRef(null),ye=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const D=v==="__custom__"?L.trim():((ht=u.find(ue=>ue.id===v))==null?void 0:ht.path)||"",ge=v==="__custom__"&&!!D&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),G=v!=="__custom__"&&((ut=u.find(ue=>ue.id===v))==null?void 0:ut.path)||"",ve=a.useMemo(()=>(e.recentLaunches||[]).map(ue=>ue.workspace),[e]),Ie=a.useCallback(async ue=>{b(!0),j("");try{const Oe=await o(ue);k(Oe.path),d(Oe.path),N(Oe.directories)}catch(Oe){j(Oe instanceof Error?Oe.message:"Could not load folder")}finally{b(!1)}},[o]),Ae=a.useCallback(()=>{var Oe;C("__custom__"),h(!0);const ue=zr(e.platform,Ur(L.trim(),G,ve,e.defaultWorkspacePath,(Oe=u.find(et=>et.id===x))==null?void 0:Oe.path,u.map(et=>et.path)));Ie(ue)},[L,x,Ie,ve,G,e.platform,u]),We=a.useCallback(ue=>{if(ue!=null&&ue.workspaceId){C(ue.workspaceId),d("");return}if(ue!=null&&ue.workspacePath){C("__custom__"),d(ue.workspacePath);return}C(""),d("")},[]),ze=a.useCallback(ue=>{if(C(ue),ue==="__custom__"){Ae();return}d("")},[Ae]),Ke=a.useCallback(ue=>{C("__custom__"),d(ue)},[]),qe=a.useCallback((ue,Oe)=>{T.current=Oe,_.current=ue.selectedWorkspaceKey||"__home__",H(ue.selectedWorkspaceKey||"__home__"),A(ue.initialArgs||""),K(ue.initialModel||""),X(""),Te([]);const et=ue.providerType?`${e.id}:${ue.providerType}`:null;if(Yd(ye.current,et)){const Ge=xt();we(Ge.textQuery),ae(Ge.workspaceQuery),oe(Ge.modelQuery),Z(Ge.resumableOnly),se(Ge.sortMode)}ye.current=et,O(ue),ue.providerType&&i&&(ee(!0),i(ue.providerType).then(Ge=>Te(Ge||[])).catch(Ge=>console.warn("Failed to load saved sessions",Ge)).finally(()=>ee(!1)))},[i,e.id]),Ye=a.useMemo(()=>di(xe,{textQuery:Ne,workspaceQuery:te,modelQuery:V,resumableOnly:re,sortMode:me}),[V,re,xe,me,Ne,te]);a.useEffect(()=>{z&&(Ye.some(ue=>ue.providerSessionId===z)||X(""))},[Ye,z]);const ft=a.useCallback(()=>{T.current&&(ne(!0),T.current().finally(()=>{T.current=null,ne(!1),O(null)}))},[]),$e=a.useCallback(()=>{T.current=null,O(null)},[]),lt=a.useCallback(ue=>{_.current=ue,H(ue)},[]);return a.useEffect(()=>{var ue;ke.current!==e.id&&(ke.current=e.id,C(x||((ue=u[0])==null?void 0:ue.id)||"__custom__"),d(""),k(""),N([]),j(""),h(!1),we(xt().textQuery),ae(xt().workspaceQuery),oe(xt().modelQuery),Z(xt().resumableOnly),se(xt().sortMode),ye.current=null,I(un(p,s.length,r.length)))},[r.length,s.length,x,p,e.id,u]),a.useEffect(()=>{var ue;v!=="__custom__"&&(v&&u.some(Oe=>Oe.id===v)||C(x||((ue=u[0])==null?void 0:ue.id)||"__custom__"))},[x,v,u]),a.useEffect(()=>{W==="ide"&&p||W==="cli"&&s.length>0||W==="acp"&&r.length>0||I(un(p,s.length,r.length))},[W,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:m,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:v,customWorkspacePath:L,browseCurrentPath:g,browseDirectories:f,browseBusy:R,browseError:w,browseDialogOpen:y,activeLauncherKind:W,launchConfirm:M,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:S,launchConfirmArgs:q,launchConfirmModel:P,launchConfirmResumeId:z,launchConfirmSavedSessions:xe,launchConfirmTextFilter:Ne,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:V,launchConfirmResumableOnly:re,launchConfirmSortMode:me,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:ce,launchConfirmBusy:fe,resolvedWorkspacePath:D,canCreateMissingWorkspace:ge,openBrowseDialog:Ae,loadBrowsePath:Ie,handleWorkspaceChoiceChange:ze,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:d,setBrowseDialogOpen:h,setActiveLauncherKind:I,openLaunchConfirm:qe,handleConfirmLaunch:ft,closeLaunchConfirm:$e,setWorkspaceSelectionFromOption:We,setLaunchConfirmWorkspaceKeyAndSync:lt,setLaunchConfirmArgs:A,setLaunchConfirmModel:K,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:ae,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:Z,setLaunchConfirmSortMode:se}}function Wm({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:m,section:p,showBottomNav:u,onBack:x,onSectionChange:v,onOpenConversation:C,onOpenRecent:L,onOpenMachineDetails:d,onMachineUpgrade:g,onLaunchDetectedIde:k,onAddWorkspace:f,onBrowseDirectory:N,onLaunchWorkspaceProvider:R,onListSavedSessions:b}){const w=S=>S==="ide"?"IDE":S==="cli"?"CLI":"ACP",j=r.slice(0,4),y=s.slice(0,3),h=Bm({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:l,onBrowseDirectory:N,onListSavedSessions:b}),W=a.useMemo(()=>j.map(S=>{const{metaText:H,updatedLabel:q}=Bi(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:H,updatedLabel:q,onClick:()=>{const{options:A,selectedKey:P}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspacePath:S.workspace});h.openLaunchConfirm({title:S.kind==="ide"?es("restart-ide",S.label):S.providerSessionId?ea(S.label):es("start-fresh",S.label),description:S.kind==="ide"?ts("restart-ide"):S.providerSessionId?ta():ts("start-fresh"),confirmLabel:S.kind==="ide"?Ns("restart-ide"):S.providerSessionId?Lr(!0):Ns("start-fresh"),busyLabel:S.kind==="ide"?Ss("restart-ide"):S.providerSessionId?Jn(!0):Ss("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:P,details:[{label:"Mode",value:w(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const K=A.find(z=>z.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(K),await L({...S,workspace:(K==null?void 0:K.workspacePath)??null})})}}}),[h,L,j]),I=a.useMemo(()=>y.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:at(S.conversation),secondary:Bd(S.conversation,{timestampLabel:S.timestamp?Uo(S.timestamp):null}),unread:S.unread,onClick:()=>C(S.conversation)})),[C,y]),T=h.showAllRecent?W:W.slice(0,4),M=W.length>0,O=I.length>0,_=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 ${_} 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(Kn,{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:At(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:[O&&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:I.map(S=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),M&&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:T.map(S=>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:S.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:S.primary}),S.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),W.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:()=>h.setShowAllRecent(S=>!S),children:h.showAllRecent?"Show fewer":`Show ${W.length-4} more`})})]}),(h.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:h.workspaceChoice,onChange:S=>h.handleWorkspaceChoiceChange(S.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:h.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[h.workspaceRows.map(S=>t.jsxs("option",{value:S.id,children:[S.id===h.defaultWorkspaceId?"⭐ ":"",Kr(S.path,S.label)||S.path]},S.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),h.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(vs,{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:h.resolvedWorkspacePath||h.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:h.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:()=>{h.resolvedWorkspacePath&&f(h.resolvedWorkspacePath)},disabled:!h.resolvedWorkspacePath||h.browseBusy,children:"Save as workspace"})]})]}),h.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[h.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("acp"),children:"ACP"})]}),h.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:h.activeLauncherKind==="ide"?"Choose an IDE":h.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:h.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(S=>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:H,selectedKey:q}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${S.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:H,selectedWorkspaceKey:q,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:S.name}]},async()=>{const A=H.find(P=>P.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(A),k(S.type,{workspacePath:(A==null?void 0:A.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:S.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},S.type)):(h.activeLauncherKind==="cli"?n:o).map(S=>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 H=h.activeLauncherKind==="cli"?"cli":"acp",{options:q,selectedKey:A}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${S.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${H.toUpperCase()}`,workspaceOptions:q,selectedWorkspaceKey:A,details:[{label:"Mode",value:H.toUpperCase()},{label:"Provider",value:S.displayName}],showArgsInput:!0,showModelInput:H==="acp",initialArgs:"",initialModel:"",providerType:S.type},async()=>{const P=q.find(K=>K.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(P),R(H,S.type,{workspaceId:(P==null?void 0:P.workspaceId)??null,workspacePath:(P==null?void 0:P.workspacePath)??null,args:h.launchConfirmArgs,model:h.launchConfirmModel,resumeSessionId:h.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[S.icon?`${S.icon} `:"",S.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},S.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,h.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:()=>f(h.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:g,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:d,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"})]})]})]})]}),h.browseDialogOpen&&t.jsx(Vr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:h.browseCurrentPath,directories:h.browseDirectories,busy:h.browseBusy,error:h.browseError,confirmLabel:"Use this folder",onClose:()=>h.setBrowseDialogOpen(!1),onNavigate:S=>{h.loadBrowsePath(S)},onConfirm:S=>{h.chooseCustomWorkspacePath(S),h.setBrowseDialogOpen(!1)}}),h.launchConfirm&&t.jsx(la,{title:h.launchConfirm.title,description:h.launchConfirm.description,details:h.launchConfirm.details,workspaceOptions:h.launchConfirm.workspaceOptions,selectedWorkspaceKey:h.launchConfirmWorkspaceKey,onWorkspaceChange:h.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:h.launchConfirm.providerType?Lr(!!h.launchConfirmResumeId):h.launchConfirm.confirmLabel,busyLabel:h.launchConfirm.providerType?void 0:h.launchConfirm.busyLabel,busy:h.launchConfirmBusy,showArgsInput:h.launchConfirm.showArgsInput,argsValue:h.launchConfirmArgs,onArgsChange:h.setLaunchConfirmArgs,showModelInput:h.launchConfirm.showModelInput,modelValue:h.launchConfirmModel,onModelChange:h.setLaunchConfirmModel,historyProviderNode:h.launchConfirm.providerType&&(h.launchConfirmSessionsLoading||h.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"}),h.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Zn()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:h.launchConfirmTextFilter,onChange:S=>h.setLaunchConfirmTextFilter(S.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmWorkspaceFilter,onChange:S=>h.setLaunchConfirmWorkspaceFilter(S.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmModelFilter,onChange:S=>h.setLaunchConfirmModelFilter(S.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsxs("select",{value:h.launchConfirmSortMode,onChange:S=>h.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:h.launchConfirmResumableOnly,onChange:S=>h.setLaunchConfirmResumableOnly(S.target.checked),disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:h.launchConfirmResumeId,onChange:S=>h.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Jd()}),h.filteredLaunchConfirmSavedSessions.map(S=>t.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.providerSessionId))]}),!h.launchConfirmSessionsLoading&&h.launchConfirmSavedSessions.length>0&&h.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),h.launchConfirmResumeId&&(()=>{const S=h.filteredLaunchConfirmSavedSessions.find(q=>q.providerSessionId===h.launchConfirmResumeId);if(!S)return null;const H=$i(S);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:H.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:H.providerSessionId}),t.jsx("div",{className:"mt-1",children:H.metaLine}),H.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:H.updatedLabel}),H.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:H.preview})]})})()]}),onConfirm:h.handleConfirmLaunch,onCancel:h.closeLaunchConfirm}),u&&t.jsx(Ei,{section:p,onSectionChange:v})]})}function Wi(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 Km(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:cs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,m,p,u;const o=Ys(n)?"cli":bs(n)?"acp":"ide",i=cs(n.summaryMetadata);return{id:`${o}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Ys(n)?n.cliName||n.type:bs(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:bs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(p=(m=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:m.at)==null?void 0:p.call(m,-1))==null?void 0:u.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=qt(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,v)=>v.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Cn(n),m=o.filter(x=>x.unread||x.requiresAction).length,p=Wi(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Wd(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 pr(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 Hm({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:m,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:v,onRequestedMobileSectionConsumed:C,setSelectedTabKey:L,setScreen:d,setSelectedMachineId:g,setSection:k,setMachineBackTarget:f,resetMachineAction:N}){const R=a.useRef(null),b=a.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const j=Gs(w,c),y=Math.max(Date.now(),Gt(w),j.lastUpdated||0);pr("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:at(w),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Gt(w),readAt:y}),l(qt(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,seenAt:y}).then(h=>{pr("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:h})}).catch(h=>{pr("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:h instanceof Error?h.message:String(h)})})},[c,l]);return a.useEffect(()=>{var j;if(!n){d("inbox"),L(((j=e[0])==null?void 0:j.tabKey)||null),R.current=null;return}if(i!=="chat"){R.current=null;return}const w=`${n.tabKey}:${n.sessionId||""}`;R.current!==w&&(R.current=w,b(n))},[e,b,i,n,d,L]),a.useEffect(()=>{if(!m)return;const w=e.find(j=>j.tabKey===m);w&&(L(w.tabKey),d("chat"),p==null||p())},[e,p,m,d,L]),a.useEffect(()=>{if(!u)return;const w=s.find(j=>j.id===u);w&&(g(w.id),N(),k("machines"),f("inbox"),d("machine"),x==null||x())},[s,x,u,N,f,d,k,g]),a.useEffect(()=>{v&&(k(v),d("inbox"),C==null||C())},[C,v,d,k]),a.useEffect(()=>{const w=r.filter(j=>j.inboxBucket==="task_complete"||j.unread);w.length!==0&&pr("inbox_state",{screen:i,selectedTabKey:o,items:w.map(j=>{const y=Gs(j.conversation,c);return{liveState:y,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:at(j.conversation),serverBucket:y.inboxBucket,computedBucket:j.inboxBucket,serverUnread:y.unread,computedUnread:j.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:Gt(j.conversation)}})})},[r,c,i,o]),{markConversationRead:b}}function Um(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function uo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function zm(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Fm({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,l]=a.useState(""),[m,p]=a.useState(null),u=a.useCallback(()=>{i("idle"),l(""),p(null)},[]),x=a.useCallback(async(f,N,R)=>{var b;try{i("loading"),l(`Launching ${N}…`);const w={ideType:N,enableCdp:!0};(b=R==null?void 0:R.workspacePath)!=null&&b.trim()&&(w.workspace=R.workspacePath.trim()),await e(f,"launch_ide",w),i("done"),l(`${N} launch requested`)}catch(w){i("error"),l(w instanceof Error?w.message:"Launch IDE failed"),console.error("Launch IDE failed",w)}},[e]),v=a.useCallback(async(f,N,R)=>{if(N.trim())try{i("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const b=await e(f,"workspace_add",{path:N.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(b!=null&&b.success){i("done"),l(R!=null&&R.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((b==null?void 0:b.error)||"Could not save workspace")}catch(b){i("error"),l(b instanceof Error?b.message:"Could not save workspace")}},[e]),C=a.useCallback(async f=>{var N,R,b,w,j,y;try{i("loading"),l("Starting daemon upgrade…");const h=await e(f,"daemon_upgrade",{});if((N=h==null?void 0:h.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((R=h==null?void 0:h.result)==null?void 0:R.version)||"latest"}.`);return}if((b=h==null?void 0:h.result)!=null&&b.upgraded||(w=h==null?void 0:h.result)!=null&&w.success){i("done"),l(`Upgrade to v${((j=h==null?void 0:h.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((y=h==null?void 0:h.result)==null?void 0:y.error)||"Upgrade failed")}catch(h){i("error"),l(h instanceof Error?h.message:"Upgrade failed")}},[e]),L=a.useCallback(async(f,N,R,b)=>{var y,h,W;const w=Date.now(),j={machineId:f,kind:N,providerType:R,workspaceId:(b==null?void 0:b.workspaceId)||null,workspacePath:(b==null?void 0:b.workspacePath)||null,resumeSessionId:(b==null?void 0:b.resumeSessionId)||null,startedAt:w};try{i("loading"),l(`Launching ${R}…`),p(j);const I={cliType:R};(y=b==null?void 0:b.workspacePath)!=null&&y.trim()?I.dir=b.workspacePath.trim():b!=null&&b.workspaceId&&(I.workspaceId=b.workspaceId),b!=null&&b.resumeSessionId&&(I.resumeSessionId=b.resumeSessionId),(h=b==null?void 0:b.args)!=null&&h.trim()&&(I.cliArgs=b.args.trim().split(/\s+/).filter(Boolean)),(W=b==null?void 0:b.model)!=null&&W.trim()&&(I.initialModel=b.model.trim());const T=await e(f,"launch_cli",I),M=(T==null?void 0:T.result)||T,O=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(T!=null&&T.success&&O){p(null),i("done"),l(`${R} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(T!=null&&T.success){i("loading"),l(`${R} launch requested — waiting for session…`);return}p(null),i("error"),l((T==null?void 0:T.error)||(M==null?void 0:M.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(I){if(zm(I)){i("loading"),l(`${R} launch requested — waiting for session…`);return}p(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),d=a.useCallback(async(f,N)=>{try{const R=await e(f,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),b=(R==null?void 0:R.result)??R;return Array.isArray(b==null?void 0:b.sessions)?b.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),g=a.useCallback(async(f,N)=>Fr(e,f,N),[e]);a.useEffect(()=>{var b;if(!m)return;const f=uo(m.workspacePath),N=r.find(w=>{var T,M,O,_;if(!w||w.type==="adhdev-daemon"||Um(w.daemonId||w.id)!==m.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==m.kind||String(w.agentType||w.type||"")!==m.providerType)return!1;const W=String(w.providerSessionId||"");if(m.resumeSessionId&&W)return W===m.resumeSessionId;if(f){const S=uo(w.workspace||w.runtimeWorkspaceLabel);return S?S===f:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((_=(O=(M=(T=w.activeChat)==null?void 0:T.messages)==null?void 0:M.at)==null?void 0:O.call(M,-1))==null?void 0:_.timestamp)||0)>=m.startedAt-5e3});if(!N)return;const R=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(b=n.find(w=>w.routeId===N.id))==null?void 0:b.sessionId;R&&(p(null),i("done"),l(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(R)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const f=window.setTimeout(()=>{p(N=>!N||N.startedAt!==m.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[m]);const k=a.useCallback(async(f,N)=>{if(N.kind==="ide"&&N.providerType){await x(f,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await L(f,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[x,L]);return{machineAction:{state:o,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:v,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:L,handleListSavedSessions:d,handleBrowseDirectory:g,handleOpenRecent:k}}function Vm({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:m,setMachineBackTarget:p}){const u=a.useCallback(k=>{i(k.tabKey),c("chat"),n(k)},[n,c,i]),x=a.useCallback(k=>{const f=e.find(N=>N.routeId===k.routeId&&N.streamSource==="native");f&&(i(f.tabKey),c("chat"),n(f))},[e,n,c,i]),v=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),C=a.useCallback((k,f="inbox")=>{l(k),o(),m("machines"),p(f),c("machine")},[o,p,c,m,l]),L=a.useCallback(k=>{const f=qt(k);f&&C(f,"chat")},[C]),d=a.useCallback(()=>{o(),c(r)},[r,o,c]),g=a.useCallback(k=>{m(k),c("inbox")},[c,m]);return{openConversation:u,openNativeConversation:x,backFromConversation:v,openMachine:C,openConversationMachine:L,backFromMachine:d,changeMachineSection:g}}function Gm(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function qm(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 xr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Ym({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:m,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:v,requestedMobileSection:C,onRequestedMobileSectionConsumed:L,onOpenHistory:d,onOpenRemote:g,onStopCli:k,wsStatus:f,isConnected:N,onShowHiddenConversation:R,onShowAllHiddenConversations:b,onHideConversation:w,onOpenNewSession:j}){const[y,h]=a.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[W,I]=a.useState(()=>e[0]?"chat":"inbox"),[T,M]=a.useState("chats"),[O,_]=a.useState(null),[S,H]=a.useState("inbox"),q=Cs(),A="0.8.62",P=a.useMemo(()=>e.find(G=>G.tabKey===y)||e[0]||null,[e,y]),K=a.useMemo(()=>P?r.find(G=>G.id===P.routeId):void 0,[r,P]),z=a.useMemo(()=>!P||Ve(P)||!Xe(P)?null:js(P),[P]),X=a.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(Fn),[r]),xe=a.useMemo(()=>X.find(G=>G.id===O)||null,[X,O]),Te=a.useMemo(()=>Zs(r),[r]),Ne=Hr({sendDaemonCommand:o,activeConv:P||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),we=Fm({sendDaemonCommand:o,navigate:q,ides:r,conversations:e}),te=a.useMemo(()=>e.map(G=>{const ve=W==="chat"&&(P==null?void 0:P.tabKey)===G.tabKey,Ie=qs(G,Te,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ve}),Ae=Gt(G),We=ai(G);return{conversation:G,timestamp:Ae,preview:We,unread:Ie.unread,requiresAction:Ie.requiresAction,isWorking:Ie.isWorking,inboxBucket:Ie.inboxBucket}}),[e,Te,W,P]),{markConversationRead:ae}=Hm({conversations:e,machineEntries:X,items:te,selectedConversation:P,selectedTabKey:y,screen:W,liveSessionInboxState:Te,sendDaemonCommand:o,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:v,requestedMobileSection:C,onRequestedMobileSectionConsumed:L,setSelectedTabKey:h,setScreen:I,setSelectedMachineId:_,setSection:M,setMachineBackTarget:H,resetMachineAction:we.resetMachineAction}),V=Vm({conversations:e,selectedConversation:P,machineBackTarget:S,markConversationRead:ae,resetMachineAction:we.resetMachineAction,setSelectedTabKey:h,setScreen:I,setSelectedMachineId:_,setSection:M,setMachineBackTarget:H}),oe=a.useMemo(()=>xr(te.filter(G=>G.requiresAction)),[te]),re=a.useMemo(()=>xr(te.filter(G=>G.unread&&!G.requiresAction)),[te]),Z=a.useMemo(()=>xr(te.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking)),[te]),me=a.useMemo(()=>xr(te.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[te]),se=a.useMemo(()=>xe?te.filter(G=>qt(G.conversation)===xe.id):[],[te,xe]),ce=a.useMemo(()=>Km(xe,r),[r,xe]),ee=(xe==null?void 0:xe.version)||null,fe=!!xe&&!!ee&&!0&&ee!==A,ne=a.useMemo(()=>(xe==null?void 0:xe.availableProviders)||[],[xe]),ke=a.useMemo(()=>ne.filter(G=>G.category==="cli"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ne]),ye=a.useMemo(()=>ne.filter(G=>G.category==="acp"&&G.installed!==!1).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[ne]),D=a.useMemo(()=>Om(X,te),[te,X]),ge=a.useCallback(async G=>{xe&&await we.handleOpenRecent(xe.id,G)},[we,xe]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:W==="chat"&&P?t.jsx(Am,{selectedConversation:P,isAcp:Ve(P),isStandalone:l,selectedIdeEntry:K,actionLogs:n,userName:m,isSendingChat:Ne.isSendingChat,isFocusingAgent:Ne.isFocusingAgent,handleModalButton:Ne.handleModalButton,handleRelaunch:Ne.handleRelaunch,onBack:V.backFromConversation,onOpenNativeConversation:V.openNativeConversation,onOpenMachine:V.openConversationMachine,onHideConversation:w,onOpenHistory:d,onOpenRemote:g,onStopCli:k,cliViewMode:z,onSetCliViewMode:async G=>{if(P&&z!==G)try{await o(qt(P)||P.routeId,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:It(P),mode:G})}catch(ve){qm(ve)?console.warn("Skipped CLI view mode switch:",ve instanceof Error?ve.message:String(ve)):console.error("Failed to switch CLI view mode:",ve)}},handleSendChat:Ne.handleSendChat,handleFocusAgent:Ne.handleFocusAgent}):W==="machine"&&xe?t.jsx(Wm,{selectedMachineEntry:xe,selectedMachineConversations:se,selectedMachineRecentLaunches:ce,cliProviders:ke,acpProviders:ye,selectedMachineNeedsUpgrade:fe,appVersion:A,machineAction:we.machineAction,isStandalone:l,section:T,showBottomNav:S==="inbox",onBack:V.backFromMachine,onSectionChange:V.changeMachineSection,onOpenConversation:V.openConversation,onOpenRecent:ge,onOpenMachineDetails:()=>q(`/machines/${xe.id}`),onMachineUpgrade:()=>we.handleMachineUpgrade(xe.id),onLaunchDetectedIde:(G,ve)=>we.handleLaunchDetectedIde(xe.id,G,ve),onAddWorkspace:(G,ve)=>we.handleAddWorkspace(xe.id,G,ve),onBrowseDirectory:G=>we.handleBrowseDirectory(xe.id,G),onLaunchWorkspaceProvider:(G,ve,Ie)=>we.handleLaunchWorkspaceProvider(xe.id,G,ve,Ie),onListSavedSessions:G=>we.handleListSavedSessions(xe.id,G)}):t.jsx(Mm,{section:T,attentionItems:oe,unreadItems:re,workingItems:Z,completedItems:me,hiddenConversations:s,machineCards:D,getAvatarText:Gm,onOpenConversation:V.openConversation,onShowConversation:R,onShowAllHidden:b,onOpenNewSession:j,onOpenMachine:V.openMachine,onOpenSettings:()=>q("/settings"),onSectionChange:M,wsStatus:f,isConnected:N,isStandalone:l})})}function mn(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),[l,m]=a.useState(!1),[p,u]=a.useState(null),x=a.useCallback(()=>{c.current=0,m(!1),u(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const v=a.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),C=a.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!mn(s,r)){u("merge");return}const k=g.currentTarget.getBoundingClientRect(),f=g.clientX-k.left,N=k.width/3;f<N?u("split-left"):f>N*2?u("split-right"):u("merge")},[s,r]),L=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),u(null))},[]),d=a.useCallback(g=>{c.current=0,m(!1);const k=g.dataTransfer.getData("text/tab-key"),f=k?e.some(R=>R.tabKey===k):!1,N=p;if(u(null),i(),!!k){if(g.preventDefault(),N==="split-left"&&mn(s,r)){r==null||r(k,"split-left");return}if(N==="split-right"&&mn(s,r)){r==null||r(k,"split-right");return}if(f){o(k);return}n==null||n(k)}},[e,p,s,r,n,o,i]);return{dragOver:l,dropAction:p,resetDragState:x,handleDragEnter:v,handleDragOver:C,handleDragLeave:L,handleDrop:d}}function Qm(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 Jm({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[l,m]=a.useState(r??[]),[p,u]=a.useState(null),x=a.useRef(null),v=a.useRef(null),C=a.useRef(n),L=a.useRef(o);a.useEffect(()=>{C.current=n},[n]),a.useEffect(()=>{L.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(j=>{const y=Qm(j,e);return y.length===j.length&&y.every((h,W)=>h===j[W])?j:y})},[e]);const d=a.useMemo(()=>{const j=p??l;if(j.length===0)return e;const y=new Map(j.map((h,W)=>[h,W]));return[...e].sort((h,W)=>{const I=y.get(h.tabKey)??999,T=y.get(W.tabKey)??999;return I-T})},[e,p,l]);a.useEffect(()=>{var y,h;if(d.length===0){i!==null&&(c(null),(y=C.current)==null||y.call(C,null));return}if(i&&d.some(W=>W.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(h=C.current)==null||h.call(C,j))},[d,i]);const g=a.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),k=a.useCallback(j=>{var y;c(j),(y=C.current)==null||y.call(C,j)},[]),f=a.useCallback((j,y,h)=>{m(W=>{var O;const I=W.filter(_=>_!==j),T=I.indexOf(y);if(T<0)return W;const M=h==="left"?T:T+1;return I.splice(M,0,j),(O=L.current)==null||O.call(L,I),I}),u(null)},[]),N=a.useCallback((j,y,h)=>{const I=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==j),T=I.indexOf(y);if(T<0)return;const M=h==="left"?T:T+1;I.splice(M,0,j),x.current=I,u(I)},[l,e]),R=a.useCallback(()=>{var y;const j=x.current;j&&(m(j),(y=L.current)==null||y.call(L,j))},[]),b=a.useCallback(()=>{x.current=null,u(null)},[]),w=a.useCallback(j=>{m(y=>{var W;const h=y.filter(I=>I!==j);return h.push(j),(W=L.current)==null||W.call(L,h),h})},[]);return{activeTabId:i,activeConv:g,sortedConversations:d,previewOrderRef:x,draggingTabRef:v,selectTab:k,handleTabReorder:f,updatePreviewOrder:N,commitPreviewOrder:R,clearPreviewOrder:b,moveTabToEnd:w,setDraggingTabKey:j=>{v.current=j}}}function Zm({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 da({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",l=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:l}),i&&t.jsx(Di,{}),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 Ki="adhdev-tab-shortcuts";function Oi(){try{return JSON.parse(localStorage.getItem(Ki)||"{}")}catch{return{}}}function Hi({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>Oi()),[l,m]=a.useState(null),p=a.useCallback(x=>{const v=[];return x.metaKey&&v.push(o?"⌘":"Meta"),x.ctrlKey&&v.push("Ctrl"),x.altKey&&v.push(o?"⌥":"Alt"),x.shiftKey&&v.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(v.push(x.key.length===1?x.key.toUpperCase():x.key),v.join("+"))},[o]),u=a.useCallback(x=>{c(x);try{localStorage.setItem(Ki,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!e||!l)return;const x=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){m(null);return}const C=p(v);if(!C)return;const L={...i};for(const[d,g]of Object.entries(L))g===C&&delete L[d];L[l]=C,u(L),m(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,u,p]),a.useEffect(()=>{if(!e)return;const x=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[C,L]of Object.entries(i))if(s.includes(C)&&p(v)===L){v.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,p]),{isMac:o,tabShortcuts:i,shortcutListening:l,setShortcutListening:m,saveShortcuts:u}}const ef=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:m,onSelectTab:p,onConversationActivated:u,onPreviewReorder:x,onReorderTab:v,onCommitPreviewOrder:C,onClearPreviewOrder:L,onDragStateReset:d,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:f,longPressTimer:N,isGroupActive:R}){const b=As(s),w=b.isGenerating?"agent-tab-generating":b.isWaiting?"agent-tab-waiting":"",j=b.isReconnecting,y=a.useCallback(H=>{l.current=s.tabKey,g(s.tabKey),H.dataTransfer.setData("text/tab-key",s.tabKey),H.dataTransfer.effectAllowed="move"},[s.tabKey,l,g]),h=a.useCallback(()=>{l.current=null,g(null),C(),L(),d()},[l,g,C,L,d]),W=a.useCallback(H=>{const q=l.current;if(!(!q||q===s.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const A=H.currentTarget.getBoundingClientRect(),P=H.clientX<A.left+A.width/2?"left":"right";x(q,s.tabKey,P)}},[s.tabKey,l,x]),I=a.useCallback(H=>{H.preventDefault(),H.stopPropagation();const q=H.dataTransfer.getData("text/tab-key");if(q&&q!==s.tabKey){const A=H.currentTarget.getBoundingClientRect(),P=H.clientX<A.left+A.width/2?"left":"right";c.includes(q)?v(q,s.tabKey,P):k&&k(q)}L()},[s.tabKey,c,v,k,L]),T=a.useCallback(H=>{H.stopPropagation(),m(),p(s.tabKey),u(s)},[s,u,m,p]),M=a.useCallback(H=>{H.preventDefault(),f(H.clientX,H.clientY,s.tabKey)},[s.tabKey,f]),O=a.useCallback(H=>{const q=H.touches[0];N.current=setTimeout(()=>{f(q.clientX,q.clientY,s.tabKey)},600)},[s.tabKey,N,f]),_=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),S=["adhdev-dockview-tab",w,r&&"is-active",R&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:S,draggable:!0,onDragStart:y,onDragEnd:h,onDragOver:W,onDrop:I,onClick:T,onContextMenu:M,onTouchStart:O,onTouchEnd:_,onTouchMove:_,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:b.isGenerating?t.jsx("div",{className:"tab-spinner"}):b.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):b.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:at(s),children:at(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(s)}):b.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Zt(s),t.jsx("span",{className:"connecting-dots"})]}):Zt(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 tf({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:v,onDragTabKeyChange:C,onReceiveTab:L,onHideTab:d,isGroupActive:g,allowTabShortcuts:k=!0}){const[f,N]=a.useState(null),R=a.useRef(null),b=a.useRef(null),w=a.useMemo(()=>e.map(M=>M.tabKey),[e]);Js("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:j,tabShortcuts:y,shortcutListening:h,setShortcutListening:W,saveShortcuts:I}=Hi({enabled:k,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!f)return;const M=O=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(O.target)||N(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[f]),a.useEffect(()=>{const M=b.current;if(!M)return;const O=_=>{Math.abs(_.deltaY)<=Math.abs(_.deltaX)||(_.preventDefault(),M.scrollLeft+=_.deltaY)};return M.addEventListener("wheel",O,{passive:!1}),()=>M.removeEventListener("wheel",O)},[]);const T=a.useCallback((M,O,_)=>{N({x:M,y:O,tabKey:_})},[]);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:b,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(ef,{conv:M,isActive:s===M.tabKey,isDraggedTab:o.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:k?y[M.tabKey]:void 0,conversationKeys:w,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:v,onDragTabKeyChange:C,onReceiveTab:L,onOpenContextMenu:T,longPressTimer:R,isGroupActive:g},M.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&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:f.x,top:f.y},children:[k&&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:M=>{M.stopPropagation(),W(f.tabKey),N(null)},children:["⌨ ",y[f.tabKey]?`Change shortcut (${y[f.tabKey]})`:"Set shortcut"]}),y[f.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 M={...y};delete M[f.tabKey],I(M),N(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[k&&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:()=>{d(f.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&h&&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:()=>W(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.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. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+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 sf({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,userName:p,groupIndex:u,onFocus:x,isSplitMode:v,numGroups:C,onMoveTab:L,onReceiveTab:d,style:g,onActiveTabChange:k,initialActiveTabId:f,initialTabOrder:N,onTabOrderChange:R,onHideTab:b,isFocused:w,allowTabShortcuts:j=!0}){const{sendCommand:y}=Rt(),h=a.useRef(null),{activeTabId:W,activeConv:I,sortedConversations:T,draggingTabRef:M,selectTab:O,handleTabReorder:_,updatePreviewOrder:S,commitPreviewOrder:H,clearPreviewOrder:q,moveTabToEnd:A,setDraggingTabKey:P}=Jm({conversations:e,initialActiveTabId:f,initialTabOrder:N,onActiveTabChange:k,onTabOrderChange:R}),K=Hr({sendDaemonCommand:o,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:z,dropAction:X,resetDragState:xe,handleDragEnter:Te,handleDragOver:Ne,handleDragLeave:we,handleDrop:te}=Xm({conversations:e,numGroups:C,onMoveTab:L,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:q}),ae=I&&!Ve(I)&&js(I)==="terminal",V=a.useMemo(()=>I?s.find(se=>se.id===I.routeId):void 0,[s,I]),oe=a.useMemo(()=>I?n.filter(se=>se.routeId===I.tabKey):[],[n,I]),re=a.useMemo(()=>Zs(s),[s]),Z=a.useMemo(()=>new Set(T.filter(se=>Sl(se,re,{isOpenConversation:se.tabKey===W})).map(se=>se.tabKey)),[W,re,T]);Js("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:W,dragOver:z});const me=a.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&y(se.routeId,"focus_session",{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[y]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...g,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(tf,{conversations:T,activeTabId:W,groupIndex:u,numGroups:C,unreadTabKeys:Z,draggingTabRef:M,onFocus:x,onSelectTab:O,onConversationActivated:me,onPreviewReorder:S,onReorderTab:_,onCommitPreviewOrder:H,onClearPreviewOrder:q,onDragStateReset:xe,onDragTabKeyChange:P,onMoveTab:L,onReceiveTab:d,onHideTab:b,isGroupActive:w??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Te,onDragOver:Ne,onDragLeave:we,onDrop:te,children:[z&&t.jsx(Zm,{dropAction:X,canSplit:!!(C<4&&L)}),I?t.jsx(ca,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ae,ideEntry:V,terminalRef:h,handleModalButton:K.handleModalButton,handleRelaunch:K.handleRelaunch,handleSendChat:K.handleSendChat,isSendingChat:K.isSendingChat,handleFocusAgent:K.handleFocusAgent,isFocusingAgent:K.isFocusingAgent,actionLogs:oe,userName:p,isInputActive:!v||!!w}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(da,{conversationsCount:e.length,isSplitMode:v,isStandalone:l,hasRegisteredMachines:m})})]})]})}function rf({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:x,hasRegisteredMachines:v,userName:C,focusedGroup:L,setFocusedGroup:d,moveTabToGroup:g,splitTabRelative:k,closeGroup:f,handleResizeStart:N,groupActiveTabIds:R,setGroupActiveTabIds:b,groupTabOrders:w,setGroupTabOrders:j,toggleHiddenTab:y,allowTabShortcuts:h=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((W,I)=>{const T=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(st.Fragment,{children:[s&&I>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:M=>N(I-1,M),onDoubleClick:()=>f(I),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(sf,{style:s?{flexBasis:T??`${100/r}%`,flexGrow:T?0:1,flexShrink:T?0:1}:void 0,conversations:W,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:x,hasRegisteredMachines:v,userName:C,groupIndex:I,isFocused:s&&L===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(M,O)=>{O==="left"&&I>0?g(M,I-1):O==="right"&&I<r-1?g(M,I+1):O==="split-left"&&r<4?k(M,I,"left"):O==="split-right"&&r<4&&k(M,I,"right")},onReceiveTab:M=>g(M,I),onActiveTabChange:M=>b(O=>(O[I]??null)===(M??null)?O:{...O,[I]:M}),initialActiveTabId:R[I],initialTabOrder:w[I],onTabOrderChange:M=>j(O=>{const _=O[I]||[];return _.length===M.length&&_.every((S,H)=>S===M[H])?O:{...O,[I]:M}}),onHideTab:y,allowTabShortcuts:h})]},I)})})}function Ui({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,l]=a.useState(null);a.useEffect(()=>e?ct.onScreenshot("ide-page",(u,x)=>{if(u!==e)return;const v=new FileReader;v.onload=()=>i(v.result),v.readAsDataURL(x)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var u;return e?((u=ct.onStatus)==null?void 0:u.call(ct,(x,v)=>{x===e&&v!=null&&v.screenshotUsage&&l(v.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const p=e?ct.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const m=a.useCallback(async(p,u)=>{const x=e?ct.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(p,u,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const zi="adhdev-dashboard-action-shortcuts",nf=1200,af={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function of(){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 Fi(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 Dn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Pr(e){const s=Object.fromEntries(Fi(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(zi)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(af))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Vi(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function cf({enabled:e=!0,onTrigger:s}){const r=of(),[n,o]=a.useState(()=>Pr(r)),[i,c]=a.useState(null),[l,m]=a.useState([]),p=a.useRef({parts:[],timer:null}),u=a.useCallback(d=>{const g=[];return d.metaKey&&g.push(r?"⌘":"Meta"),d.ctrlKey&&g.push("Ctrl"),d.altKey&&g.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(g.push(Vi(d.key)),g.join("+"))},[r]),x=a.useCallback(d=>{o(d);try{localStorage.setItem(zi,JSON.stringify(d))}catch{}},[]);a.useEffect(()=>{const d=Pr(r),g=Object.entries(n),k=Object.entries(d);g.length===k.length&&g.every(([f,N])=>d[f]===N)||x(d)},[n,r,x]);const v=a.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),C=a.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},nf))},[]);a.useEffect(()=>{if(!i)return;const d=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),m([]);return}const k=u(g);if(!k)return;const N=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(k);if(l.length===0&&N){m([k]);return}const b=[...l,k].slice(0,2).join(" "),w={...n};for(const[j,y]of Object.entries(w))y===b&&delete w[j];w[i]=b,x(w),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,u,x,i,l]),a.useEffect(()=>{if(!e||i)return;const d=g=>{if(g.defaultPrevented)return;const k=u(g);if(!k)return;const f=g.metaKey||g.ctrlKey||g.altKey;if(Dn(g.target)&&!f)return;const N=p.current.parts,R=f?[k]:[...N.slice(-1),k].slice(-2),b=R.join(" "),w=R[R.length-1],j=Object.entries(n).filter(([,T])=>!!T),y=j.find(([,T])=>T===b);if(y){g.preventDefault(),v(),s(y[0]);return}if(j.some(([,T])=>T.startsWith(`${b} `))){g.preventDefault(),p.current.parts=R,C();return}const W=j.find(([,T])=>T===w);if(W){g.preventDefault(),v(),s(W[0]);return}if(j.some(([,T])=>T.startsWith(`${w} `))){g.preventDefault(),p.current.parts=[w],C();return}v()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,C,e,u,s,v,i]),a.useEffect(()=>()=>v(),[v]);const L=a.useMemo(()=>Fi(r),[r]);return{isMac:r,actionDefinitions:L,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:x}}const Gi=a.createContext(null);function Gr(){const e=a.useContext(Gi);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Nr(e){return at(e)||e.tabKey}function lf(e){return`remote:${e}`}function Ft(e){return e.startsWith("remote:")}function mo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function fn(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 l,m;try{s.focus(),(m=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||m.call(l)}catch{}})}catch{}}function hr(e,s){e.classList.remove(kn.className,Nn.className),e.classList.add(s==="light"?kn.className:Nn.className)}function fo(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 df(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 uf(e,s,r){var l;const n=[s];let o;for(const m of n){let p;for(const u of m){const x=e.addPanel({id:u.tabKey,component:"conversation",title:Nr(u),params:{kind:"conversation",tabKey:u.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});p||(p=x.id)}o=p??o}const i=r??((l=s[0])==null?void 0:l.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function po(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Ft(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!==Nr(n)&&o.api.setTitle(Nr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Nr(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 xo(e,s,r){var m,p;const n=r?lf(r):null;for(const u of[...e.panels])Ft(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const o=Bt(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=ci(o);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(o==null?void 0:o.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((p=e.panels.find(u=>!Ft(u.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function mf({params:e,api:s}){var x;const r=Gr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Hr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const v=[s.onDidActiveChange(C=>i(C.isActive)),s.onDidActiveGroupChange(C=>{if(!s.isActive&&!C.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const C of v)C.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(v=>v.id===c.routeId):void 0,[r.ides,c]),p=a.useMemo(()=>c?r.actionLogs.filter(v=>v.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(da,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const u=!Ve(c)&&js(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ca,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:m,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function ff({params:e}){var m;const s=Gr(),r=a.useMemo(()=>Bt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(p=>p.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:l}=Ui({doId:o,targetSessionId:r?Yn(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(Ho,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):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 pf(){const e=Gr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(da,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function xf(e){var C,L;df(e);const s=Gr(),r=a.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Bt([...s.conversationsByTabKey.values()],e.params.routeId),g=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,k=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${k?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.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:d!=null&&d.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:d.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=((L=e.api.group.activePanel)==null?void 0:L.id)===e.api.id,i=e.api.isGroupActive,c=qs(n,s.liveSessionInboxState,{isOpenConversation:o}),l=c.isReconnecting,m=c.isConnecting,p=c.isGenerating,u=c.isWaiting,x=c.unread,v=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:at(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var g;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((g=d.target)==null?void 0:g.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:p?t.jsx("div",{className:"tab-spinner"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?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:at(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Zt(n)}):t.jsx("span",{children:Zt(n)})})]}),v&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function hf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,initialDataLoaded:p,userName:u,toggleHiddenTab:x,actionShortcuts:v,registerActionHandlers:C,onActiveTabChange:L,requestedActiveTabKey:d,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:k,scrollToBottomRequest:f}){var mt,Nt,Q;const{theme:N}=na(),{sendCommand:R}=Rt(),b=a.useRef(null),w=a.useRef(null),j=a.useRef(!1),y=a.useRef(!1),h=a.useRef(!1),W=a.useRef(null),I=a.useRef([]),[T,M]=a.useState(null),[O,_]=a.useState(!1),[S,H]=a.useState(!1),[q,A]=a.useState(0),P=a.useRef(null),K=a.useMemo(()=>Li(typeof window<"u"?window.innerWidth:1280),[]),z=a.useRef(typeof window>"u"?{}:xm(K)),X=a.useMemo(()=>new Map(e.map($=>[$.tabKey,$])),[e]),xe=a.useMemo(()=>Zs(r),[r]),Te=a.useMemo(()=>{const $=b.current;return $?$.groups.some(B=>{try{const F=B.model.location.type;return F!=="floating"&&F!=="popout"?!1:B.panels.some(Y=>X.has(Y.id))}catch{return!1}}):!1},[X,q,e]),Ne=a.useCallback(()=>{var $;($=b.current)==null||$.focus()},[]),we=a.useCallback($=>{const B=document,F=$.document;for(const de of B.querySelectorAll('link[rel="stylesheet"]')){const Re=F.createElement("link");Re.rel="stylesheet",Re.href=de.href,de.crossOrigin&&(Re.crossOrigin=de.crossOrigin),F.head.appendChild(Re)}for(const de of B.querySelectorAll("style")){const Re=F.createElement("style");Re.textContent=de.textContent,F.head.appendChild(Re)}const Y=[];for(const de of B.styleSheets)try{for(const Re of de.cssRules)Re instanceof CSSStyleRule&&(Re.selectorText===":root"||Re.selectorText==="html")&&Y.push(Re.cssText)}catch{}if(Y.length>0){const de=F.createElement("style");de.textContent=Y.join(`
44
+ `),F.head.appendChild(de)}const ie=B.documentElement.getAttribute("data-theme");ie&&F.documentElement.setAttribute("data-theme",ie),F.documentElement.style.colorScheme=ie==="light"?"light":"dark",F.body.className=B.body.className;const Se=B.documentElement.getAttribute("style");Se&&F.documentElement.setAttribute("style",Se);const U=F.getElementById("dv-popout-window");U instanceof HTMLElement&&(U.classList.add("adhdev-dockview"),hr(U,N))},[N]),te=a.useCallback(()=>{var B;const $=b.current;if($)for(const F of $.groups)try{const Y=(B=F.element)==null?void 0:B.ownerDocument;if(!Y||Y===document)continue;const ie=Y.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),hr(ie,N));const Se=document.documentElement.getAttribute("data-theme");Se&&Y.documentElement.setAttribute("data-theme",Se),Y.documentElement.style.colorScheme=Se==="light"?"light":"dark",Y.body.className=document.body.className;const U=document.documentElement.getAttribute("style");U?Y.documentElement.setAttribute("style",U):Y.documentElement.removeAttribute("style")}catch{}},[N]),ae=a.useCallback(()=>{var B;const $=b.current;if($)for(const F of $.groups)try{const Y=(B=F.element)==null?void 0:B.ownerDocument;if(!Y||Y===document)continue;const ie=Y.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),hr(ie,N),ie.classList.toggle("is-showing-dockview-overlay",S),ie.classList.toggle("is-dragging-dockview",O)}catch{}},[O,S,N]),V=a.useCallback($=>{const B=b.current;if(!B)return;const F=B.getPanel($);F&&B.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:Y})=>{we(Y),ne();const ie=X.get($);Y.document.title=ie?`${at(ie)} — ADHDev`:"ADHDev — Popout"}})},[X,we]),oe=a.useCallback($=>{const B=b.current,F=B==null?void 0:B.getPanel($);if(!B||!F)return;const Y=B.groups.filter(ie=>{var Se;try{return((Se=ie.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});Y.length>0?F.api.moveTo({group:Y[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),re=a.useCallback($=>{var Y;const B=b.current;if(!B)return!1;const F=B.getPanel($);if(!F)return!1;try{return((Y=F.group.element)==null?void 0:Y.ownerDocument)!==document}catch{return!1}},[]),Z=a.useCallback($=>{re($)&&oe($),x($)},[re,oe,x]),me=a.useCallback($=>{const B=b.current,F=B==null?void 0:B.getPanel($);!B||!F||B.addFloatingGroup(F,{width:600,height:500})},[]),se=a.useCallback($=>{var F;const B=(F=b.current)==null?void 0:F.getPanel($);if(!B)return!1;try{return B.group.model.location.type==="floating"}catch{return!1}},[]),ce=a.useCallback(()=>{var B,F;const $=(F=(B=b.current)==null?void 0:B.activePanel)==null?void 0:F.id;return!$||Ft($)?null:X.has($)?$:null},[X]),ee=a.useCallback($=>{const B=b.current,F=B==null?void 0:B.getPanel($);if(!B||!F)return;const Y=B.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});Y.length>0?F.api.moveTo({group:Y[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),fe=a.useCallback(()=>{var Se;const $=b.current;if(!$)return;const F=$.groups.filter(U=>{var de;try{return((de=U.element)==null?void 0:de.ownerDocument)===document&&U.model.location.type==="grid"}catch{return!1}})[0]||null,Y=[...$.panels];for(const U of Y){const de=(Se=U.group.element)==null?void 0:Se.ownerDocument,Re=U.group.model.location.type;de===document&&Re==="grid"||(F&&F.id!==U.group.id?U.api.moveTo({group:F,position:"center"}):U.api.moveTo({position:"center"}))}const ie=$.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),fn(document)},[]),ne=a.useCallback(()=>{var B,F;const $=b.current;if($)for(const Y of $.groups){const ie=(B=Y.element)==null?void 0:B.ownerDocument;if(!ie||ie===document)continue;const Se=ie.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let U=null,de=ie.title||"ADHDev",Re="Popout workspace";const Le=Y.activePanel;if(Le)if(U=Le.id,Ft(Le.id)){const Ue=((F=Le.params)==null?void 0:F.routeId)||Le.id.slice(7),Ee=Bt([...X.values()],Ue);de=ci(Ee),Re=Ee!=null&&Ee.machineName?`Remote view · ${Ee.machineName}`:"Remote view"}else{const Ue=X.get(Le.id);de=Ue?at(Ue):Le.title||Le.id,Re=Ue?Zt(Ue):"Dockview panel"}ie.title=`${de} — ADHDev`;let He=ie.getElementById("adhdev-popout-header");He instanceof HTMLElement||(He=ie.createElement("div"),He.id="adhdev-popout-header",ie.body.appendChild(He)),He.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(";")),He.innerHTML=`
45
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
47
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${mo(de)}</div>
48
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${mo(Re)}</div>
49
+ </div>
50
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
51
+ <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>
52
+ <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>
53
+ </div>
54
+ `,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const Fe=He.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const tt=He.querySelector("[data-adhdev-popout-dock]");tt&&(tt.disabled=!U,tt.style.opacity=U?"1":"0.5",tt.style.cursor=U?"pointer":"default",tt.onclick=()=>{var Ue;U&&oe(U),(Ue=ie.defaultView)==null||Ue.focus()})}},[X,oe]),ke=a.useCallback($=>{var Y;const B=b.current,F=B==null?void 0:B.getPanel($);if(!(!B||!F)){F.group.model.openPanel(F),F.api.setActive();try{const ie=F.group.model.location;ie.type==="popout"?ie.getWindow().focus():fn((Y=F.group.element)==null?void 0:Y.ownerDocument)}catch{}}},[]),ye=a.useCallback($=>{const B=b.current,F=B==null?void 0:B.activePanel,Y=(B==null?void 0:B.activeGroup)||(F==null?void 0:F.group);if(!B||!F||!Y)return;const ie=Y.panels||[];if(ie.length<=1)return;const Se=ie.findIndex(Re=>Re.id===F.id);if(Se<0)return;const U=(Se+$+ie.length)%ie.length,de=ie[U];de&&(de.group.model.openPanel(de),de.api.setActive())},[]),D=a.useCallback($=>{var tt;const B=b.current,F=(B==null?void 0:B.activeGroup)||((tt=B==null?void 0:B.activePanel)==null?void 0:tt.group);if(!B||!F)return;const Y=B.groups||[],ie=Y.find(Ue=>Ue.id===F.id);if(!ie)return;const Se=ie.element.getBoundingClientRect(),U=Se.left+Se.width/2,de=Se.top+Se.height/2,Re=(Ue,Ee,yt,Be)=>Math.max(0,Math.min(Ee,Be)-Math.max(Ue,yt)),Le=Ue=>{const Ee=Ue.element.getBoundingClientRect(),yt=Ee.left+Ee.width/2,Be=Ee.top+Ee.height/2;let E=0,J=0,le=0,Me=!1;if($==="left"?(Me=yt<U,E=Math.max(0,Se.left-Ee.right),J=Math.abs(Be-de),le=Re(Se.top,Se.bottom,Ee.top,Ee.bottom)):$==="right"?(Me=yt>U,E=Math.max(0,Ee.left-Se.right),J=Math.abs(Be-de),le=Re(Se.top,Se.bottom,Ee.top,Ee.bottom)):$==="above"?(Me=Be<de,E=Math.max(0,Se.top-Ee.bottom),J=Math.abs(yt-U),le=Re(Se.left,Se.right,Ee.left,Ee.right)):(Me=Be>de,E=Math.max(0,Ee.top-Se.bottom),J=Math.abs(yt-U),le=Re(Se.left,Se.right,Ee.left,Ee.right)),!Me)return Number.POSITIVE_INFINITY;const pe=le>0?0:120;return E*3+J+pe};let He=null,Fe=Number.POSITIVE_INFINITY;for(const Ue of Y){if(Ue.id===ie.id)continue;const Ee=Le(Ue);Number.isFinite(Ee)&&(Ee>=Fe||(Fe=Ee,He=Ue))}return He||void 0},[]),ge=a.useCallback($=>{var Y;const B=D($);if(!B)return;const F=B.activePanel||B.panels[0];F&&(B.model.openPanel(F),F.api.setActive(),fn((Y=B.element)==null?void 0:Y.ownerDocument))},[D]),G=a.useCallback(($,B)=>{const F=b.current,Y=F==null?void 0:F.activePanel,ie=(F==null?void 0:F.activeGroup)||(Y==null?void 0:Y.group);if(!F||!Y||!ie)return;let Se=D($);!Se&&(B!=null&&B.createGroupIfMissing)&&(Se=F.addGroup({referenceGroup:ie,direction:$})),Se&&(Y.api.moveTo({group:Se,position:"center"}),Y.group.model.openPanel(Y),Y.api.setActive())},[D]),{isMac:ve,tabShortcuts:Ie,shortcutListening:Ae,setShortcutListening:We,saveShortcuts:ze}=Hi({sortedTabKeys:e.map($=>$.tabKey),onFocus:Ne,onSelectTab:ke}),Ke=a.useCallback(()=>{var F;const $=b.current;if(!$)return;const B=$.activePanel;if(B){if(Ft(B.id)){const Y=((F=B.params)==null?void 0:F.routeId)||B.id.slice(7),ie=Bt(e,Y);ie!=null&&ie.tabKey&&We(ie.tabKey);return}X.has(B.id)&&We(B.id)}},[X,ke,We,e]),qe=a.useCallback($=>{const B=[];return $.metaKey&&B.push(ve?"⌘":"Meta"),$.ctrlKey&&B.push("Ctrl"),$.altKey&&B.push(ve?"⌥":"Alt"),$.shiftKey&&$.key.length!==1&&B.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes($.key)?null:(B.push(Vi($.key)),B.join("+"))},[ve]),Ye=a.useCallback($=>{var B,F;switch($){case"splitActiveTabRight":G("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":G("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const Y=ce();Y&&me(Y);return}case"popoutActiveTab":{const Y=ce();Y&&V(Y);return}case"dockActiveTab":{const Y=ce();if(!Y)return;re(Y)?oe(Y):se(Y)&&ee(Y);return}case"focusLeftPane":ge("left");return;case"focusRightPane":ge("right");return;case"focusUpPane":ge("above");return;case"focusDownPane":ge("below");return;case"moveActiveTabToLeftPane":G("left");return;case"moveActiveTabToRightPane":G("right");return;case"moveActiveTabToUpPane":G("above");return;case"moveActiveTabToDownPane":G("below");return;case"selectPreviousGroupTab":ye(-1);return;case"selectNextGroupTab":ye(1);return;case"setActiveTabShortcut":Ke();return;case"hideCurrentTab":{const Y=(F=(B=b.current)==null?void 0:B.activePanel)==null?void 0:F.id;Y&&!Ft(Y)&&Z(Y);return}default:return}},[ye,ee,ge,me,ce,Z,se,re,oe,G,V,Ke]);a.useEffect(()=>{if(!T)return;const $=T.sourceDocument,B=$.defaultView??window,F=Y=>{const ie=$.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(Y.target)||M(null)};return B.addEventListener("mousedown",F,!0),B!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{B.removeEventListener("mousedown",F,!0),B!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[T]);const ft=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:X,hasDetachedConversationPanels:Te,ides:r,isStandalone:l,hasRegisteredMachines:m,liveSessionInboxState:xe,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:Z,userName:u,scrollToBottomRequest:f,tabShortcuts:Ie,openTabContextMenu:({x:$,y:B,tabKey:F,sourceDocument:Y})=>M({x:$,y:B,tabKey:F,sourceDocument:Y??document}),popoutTab:V,moveTabBackToMain:oe,isTabInPopout:re,floatTab:me,isTabFloating:se}),[n,s,X,Te,r,l,m,xe,o,c,i,Z,u,f,Ie,V,oe,re,me,se]),$e=a.useCallback($=>{if(!$)return!1;const B=b.current;if(!B)return!1;const F=B.getPanel($);return F?(F.group.model.openPanel(F),F.api.setActive(),k==null||k(),!0):!1},[k]),lt=a.useCallback(()=>{if(h.current)return!1;const $=$e(W.current);return $&&(h.current=!0),$},[$e]),ot=a.useCallback(()=>{var B;const $=b.current;$&&pm(K,{activeTabId:((B=$.activePanel)==null?void 0:B.id)??null,layout:$.toJSON()})},[K]),Ze=a.useCallback(()=>{hm(K,z.current)},[K]),ht=a.useCallback($=>{var Y,ie,Se,U;const B=b.current;if(!B)return{kind:"grid"};const F=B.toJSON();for(const de of F.floatingGroups||[])if((ie=(Y=de.data)==null?void 0:Y.views)!=null&&ie.includes($)&&de.position)return{kind:"floating",position:de.position};for(const de of F.popoutGroups||[])if((U=(Se=de.data)==null?void 0:Se.views)!=null&&U.includes($))return{kind:"popout",position:de.position,popoutUrl:de.url};return{kind:"grid"}},[]),ut=a.useCallback($=>{const B=b.current;if(!B)return;const F=B.getPanel($),Y=z.current[$];if(!F||!Y||Y.kind==="grid")return;if(F.group.model.location.type===Y.kind){delete z.current[$],Ze();return}if(Y.kind==="floating"){B.addFloatingGroup(F,{x:Y.position.left??24,y:Y.position.top??24,width:Y.position.width,height:Y.position.height}),delete z.current[$],Ze();return}delete z.current[$],Ze()},[Ze]);a.useEffect(()=>(C==null||C({setShortcutForActiveTab:Ke,restoreHiddenTabToSavedLocation:ut,resetAllPanelsToMain:fe,activatePreviousTabInGroup:()=>ye(-1),activateNextTabInGroup:()=>ye(1),floatActiveTab:()=>{const $=ce();$&&me($)},popoutActiveTab:()=>{const $=ce();$&&V($)},dockActiveTab:()=>{const $=ce();$&&(re($)?oe($):se($)&&ee($))},splitActiveTabRight:()=>G("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>G("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ge("left"),focusRightPane:()=>ge("right"),focusUpPane:()=>ge("above"),focusDownPane:()=>ge("below"),moveActiveTabToLeftPane:()=>G("left"),moveActiveTabToRightPane:()=>G("right"),moveActiveTabToUpPane:()=>G("above"),moveActiveTabToDownPane:()=>G("below")}),()=>C==null?void 0:C(null)),[ye,ee,me,ge,ce,se,re,G,oe,V,C,fe,ut,Ke]);const ue=a.useCallback(()=>{const $=w.current;if(!$)return;const B=$.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of B)F.setAttribute("data-adhdev-force-hidden","true")},[]),Oe=a.useCallback(()=>{const $=w.current;if(!$)return;const B=$.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of B)F.removeAttribute("data-adhdev-force-hidden")},[]),et=a.useCallback(()=>{const $=w.current;if(!$)return;const B=$.querySelectorAll(".dv-drop-target-container");for(const ie of B)ie.remove();const F=$.querySelectorAll(".dv-drop-target-dropzone");for(const ie of F)ie.remove();const Y=$.querySelectorAll(".dv-drop-target");for(const ie of Y)ie.classList.remove("dv-drop-target")},[]),Ge=a.useCallback(()=>{_(!1),H(!1),Oe(),ue(),et(),!(typeof window>"u")&&(P.current!=null&&window.clearTimeout(P.current),window.requestAnimationFrame(()=>{ue(),et()}),P.current=window.setTimeout(()=>{ue(),et(),P.current=null},80))},[Oe,ue,et]),Ct=a.useCallback($=>{var F;b.current=$.api;const B=fm(K);W.current=(B==null?void 0:B.activeTabId)??null,B!=null&&B.layout&&$.api.fromJSON(B.layout,{reuseExistingPanels:!1}),y.current=!!(B!=null&&B.layout)&&!p&&e.length===0,y.current||(po($.api,e),xo($.api,e,g)),$.api.totalPanels===0&&e.length>0?uf($.api,e,d):!y.current&&!$e(d)&&lt(),j.current=!0,$.api.onDidActivePanelChange(Y=>{var Se;if(W.current=(Y==null?void 0:Y.id)??null,h.current=!0,ne(),Y&&Ft(Y.id)){const U=((Se=Y.params)==null?void 0:Se.routeId)||Y.id.slice(7),de=Bt(e,U);L((de==null?void 0:de.tabKey)??null),ot();return}if(L((Y==null?void 0:Y.id)??null),ot(),!Y)return;const ie=X.get(Y.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&R(ie.routeId,"focus_session",{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),$.api.onDidLayoutChange(()=>{ot(),ne(),A(Y=>Y+1)}),$.api.onWillDragPanel(()=>{_(!0),H(!1),ue()}),$.api.onWillDragGroup(()=>{_(!0),H(!1),ue()}),$.api.onWillShowOverlay(()=>{Oe(),H(!0)}),$.api.onDidMovePanel(Ge),$.api.onDidDrop(Ge),$.api.onDidAddGroup(Y=>{requestAnimationFrame(()=>{var ie,Se;try{const U=(ie=Y.element)==null?void 0:ie.ownerDocument;if(!U||U===document)return;(Se=U.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const de=document.documentElement.getAttribute("data-theme");de&&U.documentElement.setAttribute("data-theme",de),U.body.className=document.body.className;const Re=document.documentElement.getAttribute("style");Re&&U.documentElement.setAttribute("style",Re)}catch{}ne(),A(U=>U+1)})}),L(((F=$.api.activePanel)==null?void 0:F.id)??null)},[$e,Ge,Oe,X,p,K,ue,et,L,ot,d,g,R,ne,e]);a.useLayoutEffect(()=>{const $=b.current;if(!$||!j.current||y.current&&!p)return;y.current&&(y.current=!1);const B=I.current,F=new Set(B),Y=e.map(Le=>Le.tabKey),ie=new Set(Y);let Se=!1;for(const Le of B)ie.has(Le)||(z.current[Le]=ht(Le),Se=!0);Se&&Ze(),po($,e),xo($,e,g);const U=Y.filter(Le=>!F.has(Le));let de=!1;for(const Le of U){const He=$.getPanel(Le),Fe=z.current[Le];if(!He||!Fe||Fe.kind==="grid")continue;if(He.group.model.location.type===Fe.kind){delete z.current[Le],de=!0;continue}if(Fe.kind==="floating"){$.addFloatingGroup(He,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete z.current[Le],de=!0;continue}}if(de&&Ze(),I.current=Y,d&&$e(d))return;!$.activePanel&&$.panels[0]&&($.panels[0].group.model.openPanel($.panels[0]),$.panels[0].api.setActive()),!!($.activePanel&&$.getPanel($.activePanel.id))||lt()},[$e,lt,p,Ze,ht,d,g,e]),a.useEffect(()=>{j.current&&$e(d)},[$e,d]),a.useEffect(()=>{if(!O||typeof window>"u")return;const $=()=>Ge();return window.addEventListener("pointerup",$),window.addEventListener("mouseup",$),window.addEventListener("dragend",$),()=>{window.removeEventListener("pointerup",$),window.removeEventListener("mouseup",$),window.removeEventListener("dragend",$)}},[Ge,O]),a.useEffect(()=>()=>{typeof window>"u"||P.current!=null&&window.clearTimeout(P.current)},[]),a.useEffect(()=>{const $=F=>{const Y=F.target;if(!Y)return;const ie=Y.querySelector("[data-tab-key]")||Y.closest("[data-tab-key]");if(ie){const Se=ie.getAttribute("data-tab-key");if(Se&&F.dataTransfer){const U=Y.closest(".dv-tab")||ie.closest(".dv-tab")||ie;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Se),U instanceof HTMLElement&&F.dataTransfer.setDragImage(U,Math.max(12,Math.round(U.clientWidth/2)),Math.max(10,Math.round(U.clientHeight/2)))}}};window.addEventListener("dragstart",$);const B=fo(b.current);for(const F of B)F.addEventListener("dragstart",$);return()=>{window.removeEventListener("dragstart",$);for(const F of B)F.removeEventListener("dragstart",$)}},[q]),a.useEffect(()=>{var B;const $=(B=w.current)==null?void 0:B.querySelector(".adhdev-dockview");$ instanceof HTMLElement&&hr($,N),te(),ne(),ae()},[ne,ae,te,N]),a.useEffect(()=>{ne(),ae()},[ne,ae]),a.useEffect(()=>{const $=B=>{if(B.defaultPrevented||Ae)return;const F=qe(B);if(!F)return;const Y=B.metaKey||B.ctrlKey||B.altKey;Dn(B.target)&&!Y||Pr(ve).setActiveTabShortcut!==F||(B.preventDefault(),B.stopPropagation(),Ke())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[qe,ve,Ae,Ke]),a.useEffect(()=>{const $=w.current;if(!$)return;const B=F=>{var de,Re;if(!F.isTrusted)return;const Y=(Re=(de=F.target)==null?void 0:de.closest)==null?void 0:Re.call(de,".dv-scrollable");if(!Y)return;F.preventDefault(),F.stopPropagation();const ie=Math.abs(F.deltaX),Se=Math.abs(F.deltaY),U=ie>Se?F.deltaX:F.deltaY;Y.dispatchEvent(new WheelEvent("wheel",{deltaY:U,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return $.addEventListener("wheel",B,{passive:!1,capture:!0}),()=>$.removeEventListener("wheel",B,{capture:!0})},[]),a.useEffect(()=>{const $=fo(b.current);if($.length===0)return;const B=$.map(F=>{let Y=[],ie=null;const Se=()=>{ie!=null&&F.clearTimeout(ie),ie=null,Y=[]},U=()=>{ie!=null&&F.clearTimeout(ie),ie=F.setTimeout(()=>{ie=null,Y=[]},1200)},de=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const He=qe(Le);if(!He)return;const Fe=Oi();for(const[tt,Ue]of Object.entries(Fe))if(e.some(Ee=>Ee.tabKey===tt)&&Ue===He){Le.preventDefault(),ke(tt);return}},Re=Le=>{if(Le.defaultPrevented||Ae)return;const He=qe(Le);if(!He)return;const Fe=Le.metaKey||Le.ctrlKey||Le.altKey;if(Dn(Le.target)&&!Fe)return;const tt=Pr(ve),Ue=Object.entries(tt).filter(([pe,_e])=>!!_e&&(pe==="splitActiveTabRight"||pe==="splitActiveTabDown"||pe==="floatActiveTab"||pe==="popoutActiveTab"||pe==="dockActiveTab"||pe==="focusLeftPane"||pe==="focusRightPane"||pe==="focusUpPane"||pe==="focusDownPane"||pe==="moveActiveTabToLeftPane"||pe==="moveActiveTabToRightPane"||pe==="moveActiveTabToUpPane"||pe==="moveActiveTabToDownPane"||pe==="selectPreviousGroupTab"||pe==="selectNextGroupTab"||pe==="setActiveTabShortcut"||pe==="hideCurrentTab")),Ee=Fe?[He]:[...Y.slice(-1),He].slice(-2),yt=Ee.join(" "),Be=Ee[Ee.length-1],E=Ue.find(([,pe])=>pe===yt);if(E){Le.preventDefault(),Se(),Ye(E[0]);return}if(Ue.some(([,pe])=>pe.startsWith(`${yt} `))){Le.preventDefault(),Y=Ee,U();return}const le=Ue.find(([,pe])=>pe===Be);if(le){Le.preventDefault(),Se(),Ye(le[0]);return}if(Ue.some(([,pe])=>pe.startsWith(`${Be} `))){Le.preventDefault(),Y=[Be],U();return}Se()};return F.addEventListener("keydown",de),F.addEventListener("keydown",Re),()=>{Se(),F.removeEventListener("keydown",de),F.removeEventListener("keydown",Re)}});return()=>{for(const F of B)F()}},[qe,ve,q,ke,Ae,Ye,e]);const bt=N==="light"?kn:Nn,gt=((Q=(Nt=(mt=b.current)==null?void 0:mt.activePanel)==null?void 0:Nt.group.element)==null?void 0:Q.ownerDocument)??document;return t.jsxs(Gi.Provider,{value:ft,children:[t.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Sc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${O?" is-dragging-dockview":""}${S?" is-showing-dockview-overlay":""}`,components:{conversation:mf,remote:ff},defaultTabComponent:xf,watermarkComponent:pf,onReady:Ct,singleTabMode:"default",tabAnimation:"smooth",theme:bt,popoutUrl:"/popout.html"})}),T&&zs.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:T.x,top:T.y},children:[re(T.tabKey)?t.jsxs(t.Fragment,{children:[se(T.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:()=>{ee(T.tabKey),M(null)},children:[t.jsx(Na,{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:v.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:()=>{oe(T.tabKey),M(null)},children:[t.jsx(il,{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:v.dockActiveTab||""})]})]}):se(T.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:()=>{ee(T.tabKey),M(null)},children:[t.jsx(Na,{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:v.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:()=>{me(T.tabKey),M(null)},children:[t.jsx(ll,{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:v.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:()=>{V(T.tabKey),M(null)},children:[t.jsx(ol,{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:v.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:$=>{$.stopPropagation(),We(T.tabKey),M(null)},children:[t.jsx(cl,{size:13,className:"shrink-0 opacity-70"})," ",Ie[T.tabKey]?`Change shortcut (${Ie[T.tabKey]})`:"Set shortcut"]}),Ie[T.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 $={...Ie};delete $[T.tabKey],ze($),M(null)},children:[t.jsx(kt,{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:()=>{Z(T.tabKey),M(null)},children:[t.jsx($o,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),T.sourceDocument.body),Ae&&zs.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:()=>We(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:$=>$.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. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+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"})]})}),gt.body)]})}const qi="adhdev-recent-launch-args-v1",bf=8;function gf(e){return String(e||"").trim().replace(/\s+/g," ")}function Yi(e,s){return`${e.trim()}::${s.trim()}`}function Xi(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(qi)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function yf(e){if(!(typeof window>"u"))try{window.localStorage.setItem(qi,JSON.stringify(e))}catch{}}function Qi(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Xi().byKey[Yi(r,n)])==null?void 0:i.items)||[]}function Ji(e,s,r){var u;const n=String(e||"").trim(),o=String(s||"").trim(),i=gf(r);if(!n||!o||!i)return;const c=Xi(),l=Yi(n,o),m=((u=c.byKey[l])==null?void 0:u.items)||[],p=[i,...m.filter(x=>x!==i)].slice(0,bf);c.byKey[l]={items:p},yf(c)}function vf(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function ua(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 Zi(e){var o;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=ua((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||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function ec(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ys(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 pn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function wf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ho(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function bo(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 jf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function kf(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 Nf(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 Sf({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var q;const[l,m]=a.useState(n||((q=e[0])==null?void 0:q.id)||null),[p,u]=a.useState(""),[x,v]=a.useState(null),[C,L]=a.useState(!1);a.useEffect(()=>{var A;m(n||((A=e[0])==null?void 0:A.id)||null)},[n,e]);const d=a.useMemo(()=>e.find(A=>A.id===l)||e[0]||null,[l,e]),g=a.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const P=wf(A.daemonId||A.id);return!!(d!=null&&d.id)&&P===d.id}),[d==null?void 0:d.id,r]),k=Ai(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),f=k.diagnostics,N=k.loading,R=k.applyDiagnostics,b=a.useMemo(()=>{const A=new Map;for(const P of g){const K=s.find(z=>z.sessionId===P.sessionId||z.routeId===P.id);P.sessionId&&K&&A.set(P.sessionId,K)}return A},[g,s]),w=a.useCallback(async()=>{if(d!=null&&d.id){L(!0);try{const A=await o(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),P=pn(A);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Could not load hosted runtime diagnostics");R(P.diagnostics||P.result||null),u("")}catch(A){const P=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";u(P)}finally{L(!1)}}},[d==null?void 0:d.id,R,o]);a.useEffect(()=>{!(d!=null&&d.id)||f||N||C||w()},[d==null?void 0:d.id,f,N,w,C]);const j=a.useCallback(async(A,P)=>{if(!(d!=null&&d.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
55
+ This will terminate the hosted runtime.`))return;const K=`${A}:${P.sessionId}`;v(K);try{const z=await o(d.id,A,{sessionId:P.sessionId}),X=pn(z);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const xe=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${xe}: ${P.displayName}`,"success"),await w()}catch(z){const X=z instanceof Error?z.message:"Session host action failed";u(X),nt.showToast(X,"warning")}finally{v(z=>z===K?null:z)}},[d==null?void 0:d.id,w,o]),y=a.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
56
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){v("session_host_prune_duplicate_sessions");try{const P=await o(d.id,"session_host_prune_duplicate_sessions",{}),K=pn(P);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Duplicate prune failed");const z=K.result||{},X=Array.isArray(z.prunedSessionIds)?z.prunedSessionIds.length:0,xe=typeof z.duplicateGroupCount=="number"?z.duplicateGroupCount:0;nt.showToast(`Pruned ${X} duplicate runtime(s) across ${xe} group(s)`,"success"),await w()}catch(P){const K=P instanceof Error?P.message:"Duplicate prune failed";u(K),nt.showToast(K,"warning")}finally{v(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[d==null?void 0:d.id,w,o]),h=a.useMemo(()=>[...(f==null?void 0:f.sessions)||[]].sort((A,P)=>(P.lastActivityAt||0)-(A.lastActivityAt||0)),[f==null?void 0:f.sessions]),W=a.useMemo(()=>f!=null&&f.liveRuntimes||f!=null&&f.recoverySnapshots||f!=null&&f.inactiveRecords?{liveRuntimes:(f==null?void 0:f.liveRuntimes)||[],recoverySnapshots:(f==null?void 0:f.recoverySnapshots)||[],inactiveRecords:(f==null?void 0:f.inactiveRecords)||[]}:Zi(h),[f==null?void 0:f.inactiveRecords,f==null?void 0:f.liveRuntimes,f==null?void 0:f.recoverySnapshots,h]),I=W.liveRuntimes,T=W.recoverySnapshots,M=W.inactiveRecords,O=a.useMemo(()=>Nf(I),[I]),_=a.useMemo(()=>[...(f==null?void 0:f.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[f==null?void 0:f.recentLogs]),S=a.useMemo(()=>[...(f==null?void 0:f.recentTransitions)||[]].slice(-3).reverse(),[f==null?void 0:f.recentTransitions]),H=(A,P)=>{var V,oe;const K=b.get(A.sessionId),z=g.find(re=>re.sessionId===A.sessionId),X=x===`session_host_resume_session:${A.sessionId}`,xe=x===`session_host_restart_session:${A.sessionId}`,Te=x===`session_host_stop_session:${A.sessionId}`,Ne=ua(A.meta),we=typeof((V=A.meta)==null?void 0:V.runtimeRecoveryError)=="string"?String(A.meta.runtimeRecoveryError):"",te=P==="recovery"?"Recover":"Resume",ae=ec(P);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:A.displayName||(z==null?void 0:z.runtimeDisplayName)||(z==null?void 0:z.cliName)||A.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${kf(A.lifecycle)}`,children:A.lifecycle}),Ne&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Ne})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(z==null?void 0:z.runtimeWorkspaceLabel)||A.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:A.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((oe=A.writeOwner)==null?void 0:oe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:jf(A.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(On,{size:11})," ",A.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",bo(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:"",` · Next: ${ae}`]}),we&&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:we})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[K&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(K),c()},children:"Open chat"}),P==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_resume_session",A)},children:X?`${te}ing…`:te}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_restart_session",A)},children:xe?"Restarting…":"Restart"}),P==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.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:()=>{j("session_host_stop_session",A)},children:Te?"Stopping…":"Stop"})]})]},A.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:A=>A.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(Ht,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.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:()=>{w()},disabled:N||C,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Is,{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(kt,{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(A=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${A.id===(d==null?void 0:d.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>m(A.id),children:A.label},A.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:[p&&!f&&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(is,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:p})]})]})}),f&&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:f.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:T.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:bo(f.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:ho(f.hostStartedAt)})]})]}),_&&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(is,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:_.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($r,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:x==="session_host_prune_duplicate_sessions",onClick:()=>{y()},children:x==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${O}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[g.length," dashboard session",g.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:ys("live")}),I.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:I.map(A=>H(A,"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:ys("recovery")}),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 recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:T.map(A=>H(A,"recovery"))})]}),M.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:ys("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:M.map(A=>H(A,"inactive"))})]}),S.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:S.map(A=>{const P=h.find(K=>K.sessionId===A.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:(P==null?void 0:P.displayName)||A.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:ho(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Bs({title:e,description:s,action:r,children:n,className:o="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),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:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function tc({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:o,onOpenHistory:i,onClearSelection:c}){const l=n?$i(n):null;return t.jsxs(Bs,{title:"Saved history",description:Zn(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:o,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:tu()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] 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 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function xn(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 br(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Cf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:m,sendDaemonCommand:p,onOpenConversation:u}){var mt,Nt;const x=tr(),v=a.useMemo(()=>[...e].sort(Fn),[e]),[C,L]=a.useState(((mt=v[0])==null?void 0:mt.id)||""),d=a.useMemo(()=>v.find(Q=>Q.id===C)||v[0],[C,v]),g=a.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[d]),k=(d==null?void 0:d.defaultWorkspaceId)||null,[f,N]=a.useState(""),[R,b]=a.useState(""),[w,j]=a.useState(xn(v[0])),[y,h]=a.useState(""),[W,I]=a.useState(""),[T,M]=a.useState([]),[O,_]=a.useState(""),[S,H]=a.useState([]),[q,A]=a.useState(!1),[P,K]=a.useState(""),[z,X]=a.useState(!1),[xe,Te]=a.useState(()=>xt()),[Ne,we]=a.useState(!1),[te,ae]=a.useState(null),[V,oe]=a.useState(!1),[re,Z]=a.useState(""),[me,se]=a.useState(!1),[ce,ee]=a.useState(""),[fe,ne]=a.useState([]),[ke,ye]=a.useState(!1),[D,ge]=a.useState(""),[G,ve]=a.useState(!1),Ie=a.useRef(null),Ae=a.useRef(0);a.useEffect(()=>{var Q;!C&&((Q=v[0])!=null&&Q.id)&&L(v[0].id)},[C,v]),a.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||x(d.id,{minFreshMs:3e4}).catch(()=>{})},[x,d]);const We=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Q=>Q.category==="cli"&&Q.installed!==!1),[d]),ze=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Q=>Q.category==="acp"&&Q.installed!==!1),[d]),Ke=a.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[d]),qe=a.useMemo(()=>w==="cli"?We.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):w==="acp"?ze.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):Ke,[ze,w,We,Ke]);a.useEffect(()=>{var $;if(!d)return;if(Ie.current!==d.id){Ie.current=d.id,N(k||(($=g[0])==null?void 0:$.id)||"__home__"),b(""),j(xn(d)),h(""),I(""),_(""),H([]),K(""),Te(xt()),Z("");return}N(B=>{var F;return B==="__custom__"||B==="__home__"||g.some(Y=>Y.id===B)?B:k||((F=g[0])==null?void 0:F.id)||"__home__"}),j(B=>B==="ide"&&Ke.length>0||B==="cli"&&We.length>0||B==="acp"&&ze.length>0?B:xn(d))},[ze.length,We.length,k,Ke.length,d,g]),a.useEffect(()=>{var Q;w&&(qe.some($=>$.id===y)||h(((Q=qe[0])==null?void 0:Q.id)||""))},[w,qe,y]);const Ye=a.useCallback(async(Q,$)=>{const B=Ae.current+1;return Ae.current=B,A(!0),K(""),m(Q,$).then(F=>{Ae.current===B&&H(F)}).catch(F=>{Ae.current===B&&(H([]),K(F instanceof Error?F.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===B&&A(!1)})},[m]),ft=a.useCallback((Q,$)=>{M(Qi(Q,$))},[]);a.useEffect(()=>{if(_(""),Te(xt()),!d||!y||w==="ide"?M([]):ft(d.id,y),w!=="cli"){H([]),K(""),A(!1);return}if(!d||!y){H([]),K(""),A(!1);return}Ye(d.id,y)},[w,ft,Ye,d,y]),a.useEffect(()=>{if(!O)return;const Q=S.find($=>$.providerSessionId===O);Q!=null&&Q.canResume||_("")},[S,O]);const $e=f==="__custom__"?R.trim():f==="__home__"?"":((Nt=g.find(Q=>Q.id===f))==null?void 0:Nt.path)||"",lt=a.useMemo(()=>d?r.filter(Q=>Q.id!==d.id&&Q.daemonId===d.id).map(Q=>Q.workspace):[],[r,d]),ot=a.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(Q=>Q.workspace),[d]),Ze=a.useCallback(Q=>{const $=String(Q.workspace||"").trim();if(!$)return;const B=g.find(F=>br(F.path)===br($));if(B){N(B.id),b("");return}N("__custom__"),b($)},[g]),ht=a.useCallback(Q=>{const $=String(Q.workspace||"").trim();if(!$)return{workspaceId:null,workspacePath:null};const B=g.find(F=>br(F.path)===br($));return B?{workspaceId:B.id,workspacePath:null}:{workspaceId:null,workspacePath:$}},[g]),ut=a.useMemo(()=>S.find(Q=>Q.providerSessionId===O)||null,[S,O]),ue=a.useMemo(()=>{var $;if(w!=="cli"||!d||!y)return null;const Q=(($=We.find(B=>B.type===y))==null?void 0:$.displayName)||y;return{routeId:d.id,daemonId:d.id,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:y,status:"idle",title:Q,messages:[],ideType:y,workspaceName:$e,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${y}`,machineName:At(d,{fallbackId:d.id})}},[w,We,$e,d,O,y]),Oe=a.useCallback(()=>{var $;if(!d)return;N("__custom__"),se(!0),ge("");const Q=zr(d.platform,Ur(R.trim(),$e,lt,ot,d.defaultWorkspacePath,($=g.find(B=>B.id===k))==null?void 0:$.path,g.map(B=>B.path)));ye(!0),o(d.id,Q).then(B=>{ee(B.path),b(B.path),ne(B.directories)}).catch(B=>{ge(B instanceof Error?B.message:"Could not load folder")}).finally(()=>ye(!1))},[R,k,ot,lt,o,$e,d,g]),et=a.useCallback(Q=>{d&&(ye(!0),ge(""),o(d.id,Q).then($=>{ee($.path),b($.path),ne($.directories)}).catch($=>{ge($ instanceof Error?$.message:"Could not load folder")}).finally(()=>ye(!1)))},[o,d]),Ge=a.useCallback(async()=>{if(!d||!$e)return;ve(!0),Z("");const Q=await i(d.id,$e);if(ve(!1),!Q.ok){Z(Q.error||"Could not save workspace");return}Z("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,$e,d]),Ct=a.useCallback(async()=>{if(!d||!w||!y)return;oe(!0),Z("");const Q=W.trim()?W.trim().split(/\s+/).filter(Boolean):[],$=w==="ide"?await c(d.id,y,{workspacePath:$e||null}):await l(d.id,w,y,{workspaceId:f!=="__home__"&&f!=="__custom__"?f:null,workspacePath:f==="__custom__"&&$e||null,resumeSessionId:w==="cli"&&O?O:null,cliArgs:Q});if(oe(!1),!$.ok){Z($.error||"Could not start session");return}w!=="ide"&&W.trim()&&(Ji(d.id,y,W),ft(d.id,y)),n()},[w,W,ft,n,c,l,$e,d,O,y,f]),bt=w?ui(w,w==="cli"&&!!O):"Start",gt=w?mi(w,w==="cli"&&!!O):"Starting…";return d?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(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4",children:[t.jsx(Bs,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:Q=>L(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:V,children:v.map(Q=>t.jsx("option",{value:Q.id,children:At(Q,{fallbackId:Q.id})},Q.id))})}),w==="cli"&&t.jsx(Bs,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:V||!d,onClick:()=>we(!0),children:[t.jsx(Ht,{size:14}),Zd()]})}),t.jsxs(Bs,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Oe,disabled:V,children:"Browse…"}),children:[t.jsxs("select",{value:f,onChange:Q=>{const $=Q.target.value;N($),$==="__custom__"?Oe():Z("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),g.map(Q=>t.jsxs("option",{value:Q.id,children:[Q.id===k?"⭐ ":"",Kr(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:f==="__home__"?"Launch without a workspace.":$e||"Select a workspace folder."}),f==="__custom__"&&$e&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Oe,disabled:V,children:[t.jsx(vs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,disabled:V||G,children:G?"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:We.length>0},{id:"ide",label:"IDE",enabled:Ke.length>0},{id:"acp",label:"ACP",enabled:ze.length>0}].map(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${w===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(Q.id),disabled:!Q.enabled||V,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:w==="ide"?"Choose IDE":w==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>h(Q.id),disabled:V,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)),qe.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."})]})]}),w!=="ide"&&t.jsxs(Bs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:W,onChange:Q=>I(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:V}),T.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:T.map(Q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>I(Q),disabled:V,title:Q,children:Q},Q))})]}),w==="cli"&&t.jsx(tc,{busy:V,savedSessionsLoading:q,savedSessionsError:P,selectedSession:ut,onRefresh:()=>{!d||!y||Ye(d.id,y)},onOpenHistory:()=>{!d||!y||(X(!0),Ye(d.id,y))},onClearSelection:()=>_("")}),re&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:re})]}),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:V,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:Ct,disabled:V||!w||!y||f==="__custom__"&&!$e,children:[t.jsx(Un,{size:14}),V?gt:bt]})]})]})}),me&&t.jsx(Vr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:fe,busy:ke,error:D,onClose:()=>se(!1),onNavigate:et,onConfirm:Q=>{b(Q),ee(Q),N("__custom__"),se(!1)}}),z&&ue&&t.jsx(sa,{activeConv:ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:S,isSavedSessionsLoading:q,isResumingSavedSessionId:te,savedHistoryFilters:xe,onSavedHistoryFiltersChange:Te,onClose:()=>X(!1),onNewChat:()=>{_(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!y||Ye(d.id,y)},onResumeSavedSession:Q=>{if(!d||!y||te||!Q.canResume)return;const $=ht(Q);_(Q.providerSessionId),Ze(Q),ae(Q.providerSessionId),X(!1),oe(!0),Z(""),l(d.id,"cli",y,{workspaceId:$.workspaceId,workspacePath:$.workspacePath,resumeSessionId:Q.providerSessionId}).then(B=>{if(!B.ok){Z(B.error||"Could not resume session");return}n()}).finally(()=>{oe(!1),ae(B=>B===Q.providerSessionId?null:B)})}}),Ne&&d&&t.jsx(Sf,{machineCards:[{id:d.id,label:At(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Wi(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:Q=>{we(!1),n(),u(Q)},onClose:()=>we(!1)})]}):null}function If(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 Af(e){return e instanceof Error?e.message:String(e||"")}function Tf(e){const s=Af(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Mf({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:m,activeCliViewMode:p,onSetActiveCliViewMode:u,mobileChatConversations:x,hiddenConversations:v,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:k,isStandalone:f,initialDataLoaded:N,userName:R,requestedMobileTabKey:b,onRequestedMobileTabConsumed:w,requestedMachineId:j,onRequestedMachineConsumed:y,requestedMobileSection:h,onRequestedMobileSectionConsumed:W,containerRef:I,isSplitMode:T,numGroups:M,groupSizes:O,groupedConvs:_,clearedTabs:S,focusedGroup:H,setFocusedGroup:q,moveTabToGroup:A,splitTabRelative:P,closeGroup:K,handleResizeStart:z,groupActiveTabIds:X,setGroupActiveTabIds:xe,groupTabOrders:Te,setGroupTabOrders:Ne,toggleHiddenTab:we,visibleConversations:te,requestedDesktopTabKey:ae,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:oe,onHideConversation:re,onShowHiddenConversation:Z,onShowAllHiddenConversations:me,scrollToBottomRequest:se,machineEntries:ce,onBrowseMachineDirectory:ee,onSaveMachineWorkspace:fe,onLaunchMachineIde:ne,onLaunchMachineProvider:ke,onListMachineSavedSessions:ye}){const D=st.useRef(null),[ge,G]=st.useState(!1),[ve,Ie]=st.useState(!1),[Ae,We]=st.useState(!1),[ze,Ke]=st.useState(!1),qe=st.useCallback(U=>{var de;zs.flushSync(()=>{Z(U)}),(de=D.current)==null||de.restoreHiddenTabToSavedLocation(U.tabKey)},[Z]),[Ye,ft]=st.useState(!1),[$e,lt]=st.useState("quickstart"),[ot,Ze]=st.useState("workspace"),ht=!e&&!s,ut=st.useCallback(U=>{G(U),U&&Ie(!1)},[]),ue=st.useCallback(U=>{Ie(U),U&&G(!1)},[]),Oe=st.useCallback(()=>{var de;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((de=D.current)==null||de.resetAllPanelsToMain(),Ie(!1))},[]),et=st.useCallback(()=>{lt(te.length===0?"quickstart":"shortcuts"),Ze("workspace"),We(!0),G(!1),Ie(!1)},[te.length]),Ge=st.useCallback(async U=>{var Fe;if(!r)return;const de=(Fe=r.modalButtons)==null?void 0:Fe[U];if(!de)return;const Re=Qs(r);if(!Re)return;const Le=de.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),He=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Le);try{await d(Re,"resolve_action",{button:de,action:He?"approve":"reject",buttonIndex:U,...gs(r)})}catch(tt){Tf(tt)||console.error("[Shortcut approval] Failed:",tt)}},[r,d]),{isMac:Ct,actionDefinitions:bt,actionShortcuts:gt,shortcutListening:mt,shortcutListeningDraft:Nt,setShortcutListening:Q,setShortcutListeningDraft:$,saveShortcuts:B}=cf({enabled:ht&&!Ae,onTrigger:U=>{var de,Re,Le,He,Fe,tt,Ue,Ee,yt,Be,E,J,le,Me,pe,_e;if(U==="openShortcutHelp"){et();return}if(U==="hideCurrentTab"){r&&re(r);return}if(U==="toggleHiddenTabs"){ue(!ve);return}if(U==="openHistoryForActiveTab"){r&&!Ve(r)&&c(r);return}if(U==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ve(r)&&l(r);return}if(U==="splitActiveTabRight"){(de=D.current)==null||de.splitActiveTabRight();return}if(U==="splitActiveTabDown"){(Re=D.current)==null||Re.splitActiveTabDown();return}if(U==="floatActiveTab"){(Le=D.current)==null||Le.floatActiveTab();return}if(U==="popoutActiveTab"){(He=D.current)==null||He.popoutActiveTab();return}if(U==="dockActiveTab"){(Fe=D.current)==null||Fe.dockActiveTab();return}if(U==="focusLeftPane"){(tt=D.current)==null||tt.focusLeftPane();return}if(U==="focusRightPane"){(Ue=D.current)==null||Ue.focusRightPane();return}if(U==="focusUpPane"){(Ee=D.current)==null||Ee.focusUpPane();return}if(U==="focusDownPane"){(yt=D.current)==null||yt.focusDownPane();return}if(U==="moveActiveTabToLeftPane"){(Be=D.current)==null||Be.moveActiveTabToLeftPane();return}if(U==="moveActiveTabToRightPane"){(E=D.current)==null||E.moveActiveTabToRightPane();return}if(U==="moveActiveTabToUpPane"){(J=D.current)==null||J.moveActiveTabToUpPane();return}if(U==="moveActiveTabToDownPane"){(le=D.current)==null||le.moveActiveTabToDownPane();return}if(U==="triggerPrimaryApprovalAction"){Ge(0);return}if(U==="triggerSecondaryApprovalAction"){Ge(1);return}if(U==="triggerTertiaryApprovalAction"){Ge(2);return}if(U==="setActiveTabShortcut"){(Me=D.current)==null||Me.setShortcutForActiveTab();return}if(U==="selectPreviousGroupTab"){(pe=D.current)==null||pe.activatePreviousTabInGroup();return}if(U==="selectNextGroupTab"){(_e=D.current)==null||_e.activateNextTabInGroup();return}!r||!Xe(r)||Ve(r)||U==="toggleCliView"&&u(p==="chat"?"terminal":"chat")}}),F=st.useCallback(()=>{We(!1),Q(null),$([])},[Q,$]),Y=st.useMemo(()=>ot==="all"?bt:bt.filter(U=>If(U)===ot),[bt,ot]),ie=st.useCallback(()=>{const U=Object.fromEntries(bt.map(de=>[de.id,""]));B(U)},[bt,B]),Se=st.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const U=Object.fromEntries(bt.map(de=>[de.id,de.defaultShortcut]));B(U)},[bt,B]);return st.useEffect(()=>{const U=de=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?de.metaKey&&de.key.toLowerCase()==="w":de.ctrlKey&&de.key.toLowerCase()==="w")&&(de.preventDefault(),r&&re&&re(r))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[r,re]),st.useEffect(()=>{if(!Ae||mt)return;const U=de=>{de.key==="Escape"&&(de.preventDefault(),F())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[F,Ae,mt]),st.useEffect(()=>{if(!ht){ft(!1);return}ft(!0);const U=window.setTimeout(()=>{ft(!1)},1e4);return()=>window.clearTimeout(U)},[ht]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(qd,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:te,hiddenConversations:v,onOpenHistory:c,onOpenConversation:qe,onHideConversation:re,onShowConversation:qe,onShowAllHidden:me,onResetPanelsToMain:Oe,inboxOpen:ge,onInboxOpenChange:ut,hiddenOpen:ve,onHiddenOpenChange:ue,onOpenNewSession:s?void 0:()=>Ke(!0),actionShortcuts:gt,onOpenRemote:()=>{!r||Xe(r)||Ve(r)||l(r)},onStopCli:m,activeCliViewMode:p,onSetCliViewMode:u}),e?t.jsx(Ym,{conversations:x,hiddenConversations:v,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:k,isStandalone:f,userName:R,requestedActiveTabKey:b,onRequestedActiveTabConsumed:w,requestedMachineId:j,onRequestedMachineConsumed:y,requestedMobileSection:h,onRequestedMobileSectionConsumed:W,onOpenHistory:c,onOpenRemote:l,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:qe,onShowAllHiddenConversations:me,onOpenNewSession:()=>Ke(!0)}):s?t.jsx(rf,{containerRef:I,isSplitMode:T,numGroups:M,groupSizes:O,groupedConvs:_,clearedTabs:S,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:k,isStandalone:f,hasRegisteredMachines:ce.length>0,userName:R,focusedGroup:H,setFocusedGroup:q,moveTabToGroup:A,splitTabRelative:P,closeGroup:K,handleResizeStart:z,groupActiveTabIds:X,setGroupActiveTabIds:xe,groupTabOrders:Te,setGroupTabOrders:Ne,toggleHiddenTab:we,allowTabShortcuts:!1}):t.jsx(hf,{visibleConversations:te,clearedTabs:S,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:k,isStandalone:f,hasRegisteredMachines:ce.length>0,initialDataLoaded:N,userName:R,toggleHiddenTab:we,actionShortcuts:gt,registerActionHandlers:U=>{D.current=U},onActiveTabChange:oe,requestedActiveTabKey:ae,onRequestedActiveTabConsumed:V,scrollToBottomRequest:se}),ze&&t.jsx(Cf,{machines:ce,conversations:x,ides:C,onClose:()=>Ke(!1),onBrowseDirectory:ee,onSaveWorkspace:fe,onLaunchIde:ne,onLaunchProvider:ke,onListSavedSessions:ye,sendDaemonCommand:d,onOpenConversation:U=>{Ke(!1),Z(U),oe(U.tabKey)}}),Ae&&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:F,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:U=>U.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:F,"aria-label":"Close dashboard guide",children:t.jsx(kt,{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(U=>t.jsx("button",{type:"button",className:`btn btn-sm ${$e===U.id?"btn-primary":"btn-secondary"}`,onClick:()=>lt(U.id),children:U.label},U.id))}),$e==="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 ",Ct?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),$e==="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."]})]})]})]}),$e==="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(U=>t.jsx("button",{type:"button",className:`btn btn-sm ${ot===U.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ze(U.id),children:U.label},U.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:Y.map(U=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${mt===U.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:U.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:U.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:U.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:mt===U.id?Nt.length>0?`${Nt.join(" ")} ...`:"Listening...":gt[U.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Q(U.id),$([])},children:mt===U.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const de={...gt};de[U.id]="",B(de)},children:"Disable"})]})]})},U.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ct?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:et,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 ${Ye?"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:"?"}),Ye&&t.jsx("span",{children:"Guide"})]})]})}const hn=[{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 Lf({onClose:e}){const[s,r]=a.useState(0),n=hn[s],o=s===hn.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(kt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:hn.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:`
57
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
58
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
59
+ `})]})}function _f({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,l=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:l?"var(--status-warning)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&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 Rf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,l]=a.useState(()=>i||"native"),m=a.useMemo(()=>pi(s),[s]),p=a.useMemo(()=>e?ra(e,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,m,r]),u=a.useMemo(()=>p.find(g=>g.streamSource==="native"),[p]),x=a.useMemo(()=>p.filter(g=>g.streamSource==="agent-stream"),[p]),v=a.useMemo(()=>e?Bt(p,e.id):null,[p,e]);a.useEffect(()=>{i&&l(i)},[i]),a.useEffect(()=>{if(i||!v)return;const g=v.streamSource==="native"?"native":v.tabKey;!g||c===g||c==="native"&&l(g)},[c,v,i]),a.useEffect(()=>{var g;c!=="native"&&(x.some(k=>k.tabKey===c)||l(((g=x[0])==null?void 0:g.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(u||x[0]&&l(x[0].tabKey))},[c,u,x]);const C=a.useMemo(()=>c==="native"&&u?u:x.find(g=>g.tabKey===c)||v||u||x[0],[c,u,v,x]),L=a.useMemo(()=>x.map(g=>({tabKey:g.tabKey,title:ii(g)||o,status:g.status})),[x,o]),d=a.useCallback(g=>{if(g)return p.find(k=>k.sessionId===g||k.routeId===g||k.tabKey===g)},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:C,conversations:p,extensionTabs:L,hasExtensions:L.length>0,resolveConversationByTarget:d}}function Pf({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:m,isStandalone:p,userName:u,onOpenHistory:x,onConversationChange:v,onClose:C}){const[L,d]=a.useState("split"),[g,k]=a.useState(()=>Ot(e)?"native":e.tabKey),f=a.useRef(null),N=a.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),R=a.useMemo(()=>rt((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:b,extensionTabs:w,hasExtensions:j}=Rf({ideData:N,allIdes:r,connectionStates:n,localUserMessages:i,ideName:R||"IDE",preferredTabKey:Ot(e)?void 0:e.tabKey}),y=a.useMemo(()=>N?Bt(b,N.id):null,[N,b]);a.useEffect(()=>{const A=f.current,P={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(f.current=P,!(A&&A.routeId===P.routeId&&A.tabKey===P.tabKey&&A.streamSource===P.streamSource)){if(Ot(e)){k("native");return}k(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),a.useEffect(()=>{if(g==="native"){if(b.some(A=>A.streamSource==="native"))return;(y==null?void 0:y.streamSource)==="agent-stream"&&k(y.tabKey);return}if(!b.some(A=>A.tabKey===g)){if((y==null?void 0:y.streamSource)==="agent-stream"){k(y.tabKey);return}k("native")}},[b,g,y]);const h=a.useMemo(()=>g==="native"?b.find(A=>A.streamSource==="native")||e:b.find(A=>A.tabKey===g)||e,[e,b,g]),W=Ti(h),I=a.useMemo(()=>W.status||W.modalMessage||W.modalButtons?{...h,...W.status?{status:W.status}:{},...W.modalMessage!==void 0?{modalMessage:W.modalMessage}:{},...W.modalButtons!==void 0?{modalButtons:W.modalButtons}:{}}:h,[h,W]),T=Ar(I),M=Hr({sendDaemonCommand:c,activeConv:I,setLocalUserMessages:l,setActionLogs:m,isStandalone:p}),{connScreenshot:O,screenshotUsage:_,handleRemoteAction:S}=Ui({doId:T,targetSessionId:Yn(I),connState:I.connectionState||"new",viewMode:L}),H=a.useMemo(()=>o.filter(A=>A.routeId===I.tabKey),[o,I.tabKey]);a.useEffect(()=>{v==null||v(I)},[I,v]),a.useEffect(()=>{const A=P=>{P.key==="Escape"&&C()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[C]);const q=a.useCallback(A=>{A.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:C,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:q,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(Tt,{size:16})}),t.jsx("span",{className:"truncate",children:Or(h)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:C,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(A=>{const P=L===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${P?"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:()=>d(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?t.jsx(Gc,{size:15}):t.jsx(Tt,{size:15})},A)})}),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(h),title:"Chat History",children:[t.jsx(Hn,{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:C,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${L==="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:[L!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${L==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(_f,{hasExtensions:j,ideName:R||"IDE",activeChatTab:g,extensionTabs:w,onSelectTab:k}),t.jsx(zo,{activeConv:I,onModalButton:M.handleModalButton}),t.jsx(Tn,{activeConv:I,ideEntry:N,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:H,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${L==="split"?"order-1 md:order-2":""}`,children:t.jsx(Ho,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:O,screenshotUsage:_,transportType:I.transport,onAction:S})})]})]})})}function Df({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Od(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 Ef({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:m,onNewHistoryChat:p,onSwitchHistorySession:u,onRefreshHistory:x,onResumeSavedHistorySession:v,remoteDialogConv:C,remoteDialogIdeEntry:L,connectionStates:d,actionLogs:g,localUserMessages:k,sendDaemonCommand:f,setLocalUserMessages:N,setActionLogs:R,isStandalone:b,userName:w,onOpenRemoteHistory:j,onRemoteConversationChange:y,onCloseRemoteDialog:h,cliStopDialogOpen:W,cliStopTargetConv:I,onCancelCliStop:T,onStopCliNow:M,onSaveCliAndStop:O,toasts:_,onDismissToast:S,onClickToast:H,showOnboarding:q,onCloseOnboarding:A}){var z;const[P,K]=st.useState(()=>xt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(sa,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:P,onSavedHistoryFiltersChange:K,onClose:m,onNewChat:p,onSwitchSession:u,onRefreshHistory:x,onResumeSavedSession:v}),C&&t.jsx(Pf,{activeConv:C,ideEntry:L,ides:r,connectionStates:d,actionLogs:g,localUserMessages:k,sendDaemonCommand:f,setLocalUserMessages:N,setActionLogs:R,isStandalone:b,userName:w,onOpenHistory:j,onConversationChange:y,onClose:h}),W&&I&&(Xe(I)||Ve(I))&&t.jsx(Df,{activeConv:I,canSaveAndStop:Xe(I)&&!Ve(I)&&!!((z=I.resume)!=null&&z.supported),onCancel:T,onStopNow:M,onSaveAndStop:O}),t.jsx(fi,{toasts:_,onDismiss:S,onClickToast:H}),q&&t.jsx(Lf,{onClose:A})]})}function $f({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(Is,{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 l=At(c,{fallbackId:c.id}),m=n[c.id],p=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"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:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),u&&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:u?"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:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:u?"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(kt,{size:16})})]})}function Bf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function go(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Kf(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 Of(){var ha,ba,ga,ya,va;const{sendCommand:e}=Rt(),s=tr(),r=Wn(),n=Cs(),[o,i]=Cc(),c=o.get("activeTab"),l=((ha=r.state)==null?void 0:ha.openRemoteForTabKey)||null,m=((ba=r.state)==null?void 0:ba.openMachineId)||null,p=((ga=r.state)==null?void 0:ga.mobileSection)||null,u=ri(),x=u.ides||[],v=u.initialLoaded??!0,{updateRouteChats:C,setToasts:L}=u,[d,g]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),k=u.toasts||[],f=u.wsStatus||"connected",N=u.isConnected??!0,R=u.connectionStates||{},b=u.showReconnected||!1,{groupAssignments:w,setGroupAssignments:j,focusedGroup:y,setFocusedGroup:h,groupActiveTabIds:W,setGroupActiveTabIds:I,groupTabOrders:T,setGroupTabOrders:M,groupSizes:O,setGroupSizes:_,isMobile:S,hasHydratedStoredLayout:H,hydrateStoredLayout:q}=gm(),[A,P]=a.useState(!1),[K,z]=a.useState(!1),[X,xe]=a.useState(null),[Te,Ne]=a.useState([]),[we,te]=a.useState(!1),[ae,V]=a.useState(null),[oe]=a.useState(()=>Ii()),[re,Z]=a.useState([]),[me,se]=a.useState({}),[ce,ee]=a.useState({}),[fe,ne]=a.useState({}),[ke,ye]=a.useState(null),[D,ge]=a.useState(null),[G,ve]=a.useState(null),Ie=a.useRef(null);Js("Dashboard",{ideCount:x.length,toastCount:k.length,focusedGroup:y,groupCount:Object.keys(w).length,localMessageTabs:Object.keys(me).length,actionLogCount:re.length});const Ae=x.find(be=>be.type==="adhdev-daemon"),We=a.useMemo(()=>x.filter(be=>be.type==="adhdev-daemon").sort(Fn),[x]),ze=!!Ae;a.useEffect(()=>{!Ae||!(!Ae.detectedIdes||!Ae.availableProviders||!Ae.recentLaunches||!Ae.workspaces)||s(Ae.id,{minFreshMs:3e4}).catch(()=>{})},[Ae,s]);const Ke=(Ae==null?void 0:Ae.terminalBackend)||null,qe=Ae?At(Ae,{fallbackId:Ae.id}):null,Ye=(Ae==null?void 0:Ae.id)||null,ft=a.useMemo(()=>Xu(x,ce),[x,ce]),{hiddenTabs:$e,hideTab:lt,toggleTab:ot,showTab:Ze,showAllTabs:ht}=Yu(),{chatIdes:ut,conversations:ue,visibleConversations:Oe,visibleTabKeys:et,resolveConversationBySessionId:Ge,resolveConversationByTarget:Ct}=am({ides:ft,connectionStates:R,localUserMessages:me,clearedTabs:fe,hiddenTabs:$e});a.useEffect(()=>{Object.keys(ce).length!==0&&ee(be=>{let Ce=!1;const je={...be};for(const[he,Pe]of Object.entries(be)){const Qe=Ja(x,he);(Qe===null||Qe===Pe)&&(delete je[he],Ce=!0)}return Ce?je:be})},[x,ce]);const bt=a.useMemo(()=>Zs(x),[x]),gt=a.useRef(null),{containerRef:mt,normalizedGroupAssignments:Nt,numGroups:Q,isSplitMode:$,groupedConvs:B,moveTabToGroup:F,closeGroup:Y,handleResizeStart:ie,splitTabRelative:Se}=Cm({groupAssignments:w,setGroupAssignments:j,setFocusedGroup:h,setGroupActiveTabIds:I,setGroupTabOrders:M,groupSizes:O,setGroupSizes:_,isMobile:S,visibleConversations:Oe,visibleTabKeys:et}),U=a.useMemo(()=>{var Ce,je;if(!S){if(ke){const he=ue.find(Pe=>Pe.tabKey===ke);if(he)return he}return Oe[0]}const be=W[y];if(be){const he=ue.find(Pe=>Pe.tabKey===be);if(he)return he}return((Ce=B[y])==null?void 0:Ce[0])||((je=B[0])==null?void 0:je[0])},[ke,S,W,y,ue,B,Oe]);a.useEffect(()=>{if(S){gt.current=null;return}if(!(U!=null&&U.sessionId)){gt.current=null;return}const be=`${U.tabKey}:${U.sessionId}`;if(gt.current===be)return;const Ce=()=>{if(document.visibilityState!=="visible"||gt.current===be)return;gt.current=be;const je=Gs(U,bt),he=Math.max(Date.now(),Gt(U),je.lastUpdated||0);e(U.daemonId||U.routeId,"mark_session_seen",{sessionId:U.sessionId,seenAt:he}).catch(()=>{})};if(document.visibilityState==="visible"){const je=setTimeout(Ce,1500),he=()=>{document.visibilityState!=="visible"&&clearTimeout(je)};return document.addEventListener("visibilitychange",he),()=>{clearTimeout(je),document.removeEventListener("visibilitychange",he)}}else{const je=()=>{document.visibilityState==="visible"&&(setTimeout(Ce,800),document.removeEventListener("visibilitychange",je))};return document.addEventListener("visibilitychange",je),()=>{document.removeEventListener("visibilitychange",je)}}},[U,S,bt,e]);const{requestedDesktopTabKey:de,requestedMobileTabKey:Re,consumeRequestedActiveTab:Le}=om({isMobile:S,urlActiveTab:c,resolveConversationBySessionId:Ge,setSearchParams:i}),{remoteDialogConv:He,remoteDialogIdeEntry:Fe,remoteDialogActiveConv:tt,setRemoteDialogActiveConv:Ue,openRemoteDialog:Ee,closeRemoteDialog:yt}=wm({isMobile:S,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:de,conversations:ue,ides:x,resolveConversationByTarget:Ct}),Be=tt||He||U,E=!!Be&&Xe(Be)&&!Ve(Be),J=a.useMemo(()=>{if(!Be||!E)return null;const be=Be.daemonId||Be.routeId||"",Ce=It(Be);return`${be}:${Ce}`},[Be,E]),le=a.useMemo(()=>Oe,[Oe]),Me=S&&oe==="chat",pe=a.useMemo(()=>ue.filter(be=>$e.has(be.tabKey)),[ue,$e]),_e=a.useCallback(be=>{const Ce=new URLSearchParams(o);Ce.set("activeTab",be),i(Ce,{replace:!0})},[o,i]),it=a.useCallback(async(be,Ce)=>Fr(e,be,Ce),[e]),Mt=a.useCallback(async(be,Ce)=>{if(!Ce.trim())return{ok:!1,error:"Choose a workspace path first."};try{const je=await e(be,"workspace_add",{path:Ce.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,Ce,je)=>{var he;try{const Pe={ideType:Ce,enableCdp:!0};(he=je==null?void 0:je.workspacePath)!=null&&he.trim()&&(Pe.workspace=je.workspacePath.trim());const Qe=await e(be,"launch_ide",Pe);return!(Qe!=null&&Qe.success)&&(Qe==null?void 0:Qe.success)!==void 0?{ok:!1,error:(Qe==null?void 0:Qe.error)||"Could not launch IDE"}:(ve({machineId:be,kind:"ide",providerType:Ce,workspacePath:(je==null?void 0:je.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Pe){return{ok:!1,error:Pe instanceof Error?Pe.message:"Could not launch IDE"}}},[e]),Ts=a.useCallback(async(be,Ce,je,he)=>{var Qe,Ms,us;const Pe=Date.now();try{const Pt={cliType:je};(Qe=he==null?void 0:he.workspacePath)!=null&&Qe.trim()?Pt.dir=he.workspacePath.trim():he!=null&&he.workspaceId&&(Pt.workspaceId=he.workspaceId),(Ms=he==null?void 0:he.resumeSessionId)!=null&&Ms.trim()&&(Pt.resumeSessionId=he.resumeSessionId.trim()),Array.isArray(he==null?void 0:he.cliArgs)&&he.cliArgs.length>0&&(Pt.cliArgs=he.cliArgs),(us=he==null?void 0:he.initialModel)!=null&&us.trim()&&(Pt.initialModel=he.initialModel.trim());const vt=await e(be,"launch_cli",Pt),St=(vt==null?void 0:vt.result)||vt,Ls=(St==null?void 0:St.sessionId)||(St==null?void 0:St.id);return vt!=null&&vt.success&&Ls?(_e(Ls),{ok:!0}):vt!=null&&vt.success?(ve({machineId:be,kind:Ce,providerType:je,workspacePath:(he==null?void 0:he.workspacePath)||null,resumeSessionId:(he==null?void 0:he.resumeSessionId)||null,startedAt:Pe}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||(St==null?void 0:St.error)||`Could not launch ${Ce.toUpperCase()} session`}}catch(Pt){return Wf(Pt)?(ve({machineId:be,kind:Ce,providerType:je,workspacePath:(he==null?void 0:he.workspacePath)||null,resumeSessionId:(he==null?void 0:he.resumeSessionId)||null,startedAt:Pe}),{ok:!0}):{ok:!1,error:Pt instanceof Error?Pt.message:`Could not launch ${Ce.toUpperCase()} session`}}},[_e,e]),sc=a.useCallback(async(be,Ce)=>{if(!be||!Ce)return[];try{const je=await e(be,"list_saved_sessions",{providerType:Ce,kind:"cli",limit:30}),he=(je==null?void 0:je.result)??je;return Array.isArray(he==null?void 0:he.sessions)?he.sessions:[]}catch(je){return console.error("List saved sessions failed",je),[]}},[e]);a.useEffect(()=>{var he;if(!G)return;const be=go(G.workspacePath),Ce=x.find(Pe=>{var vt,St,Ls,wa;if(!Pe||Pe.type==="adhdev-daemon"||Bf(Pe.daemonId||Pe.id)!==G.machineId||(Ys(Pe)?"cli":bs(Pe)?"acp":"ide")!==G.kind||String(Pe.agentType||Pe.type||"")!==G.providerType)return!1;if(G.resumeSessionId)return String(Pe.providerSessionId||"")===G.resumeSessionId;if(be){const Yr=go(Pe.workspace||Pe.runtimeWorkspaceLabel);return Yr?Yr===be:!1}return Number(Pe.lastUpdated||Pe._lastUpdate||Pe.timestamp||((wa=(Ls=(St=(vt=Pe.activeChat)==null?void 0:vt.messages)==null?void 0:St.at)==null?void 0:Ls.call(St,-1))==null?void 0:wa.timestamp)||0)>=G.startedAt-5e3});if(!Ce)return;const je=typeof Ce.sessionId=="string"&&Ce.sessionId?Ce.sessionId:typeof Ce.instanceId=="string"&&Ce.instanceId?Ce.instanceId:(he=ue.find(Pe=>Pe.routeId===Ce.id))==null?void 0:he.sessionId;je&&(ve(null),_e(je))},[ue,_e,x,G]),a.useEffect(()=>{if(!G)return;const be=window.setTimeout(()=>{ve(Ce=>!Ce||Ce.startedAt!==G.startedAt?Ce:null)},45e3);return()=>window.clearTimeout(be)},[G]),Qu({visibleConversations:Oe,clearedTabs:fe,setClearedTabs:ne,setActionLogs:Z}),im({ides:x,sendDaemonCommand:e,setToasts:L,setLocalUserMessages:se,resolveConversationByTarget:Ct});const{isRefreshingHistory:rc,handleRefreshHistory:nc}=eo({sendDaemonCommand:e,activeConv:U,chats:(ya=x.find(be=>be.id===(U==null?void 0:U.routeId)))==null?void 0:ya.chats,updateRouteChats:C,setToasts:L,setLocalUserMessages:se,setClearedTabs:ne}),{isCreatingChat:ac,isRefreshingHistory:oc,handleSwitchSession:ic,handleNewChat:cc,handleRefreshHistory:lc}=eo({sendDaemonCommand:e,activeConv:Be,chats:(va=x.find(be=>be.id===(Be==null?void 0:Be.routeId)))==null?void 0:va.chats,updateRouteChats:C,setToasts:L,setLocalUserMessages:se,setClearedTabs:ne}),qr=a.useCallback(async()=>{if(!(!Be||!E||we)){te(!0);try{const be=Be.daemonId||Be.routeId,Ce=It(Be),je=await e(be,"list_saved_sessions",{agentType:Ce,providerType:Ce,kind:"cli",limit:50}),he=(je==null?void 0:je.result)??je;Ne(Array.isArray(he==null?void 0:he.sessions)?he.sessions:[])}catch(be){console.error("Refresh saved sessions failed",be),Ne([])}finally{te(!1)}}},[Be,we,E,e]);a.useEffect(()=>{if(!A){Ie.current=null;return}if(!E){Ie.current=null,Ne([]),te(!1);return}!J||we||Ie.current!==J&&(Ie.current=J,qr())},[qr,A,we,E,J]);const dc=a.useCallback(async be=>{if(!Be||!E||!be.providerSessionId||!be.workspace)return;const Ce=Be.daemonId||Be.routeId,je=It(Be);try{V(be.providerSessionId);const he=await e(Ce,"launch_cli",{cliType:je,dir:be.workspace,resumeSessionId:be.providerSessionId,initialModel:qo(be.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Pe=(he==null?void 0:he.result)??he,Qe=typeof(Pe==null?void 0:Pe.sessionId)=="string"?Pe.sessionId:typeof(Pe==null?void 0:Pe.id)=="string"?Pe.id:"";Qe&&i(Ms=>{const us=new URLSearchParams(Ms);return us.set("activeTab",Qe),us},{replace:!0}),P(!1)}catch(he){console.error("Resume saved session failed",he)}finally{V(null)}},[Be,E,e,i]);vm({urlActiveTab:S&&!Me?c:null,conversations:ue,resolveConversationBySessionId:Ge,normalizedGroupAssignments:Nt,hasHydratedStoredLayout:S&&!Me?H:!0,hydrateStoredLayout:S&&!Me?q:()=>{},setGroupActiveTabIds:I,setFocusedGroup:h,setSearchParams:i,historyModalOpen:A,activeConv:U,isRefreshingHistory:rc,ides:x,handleRefreshHistory:nc});const ma=a.useCallback(async(be,Ce)=>{const je=Ce||X||U;if(!je||!Xe(je)&&!Ve(je))return;const he=It(je),Pe=je.routeId||je.daemonId||"";try{await e(Pe,"stop_cli",{cliType:he,targetSessionId:je.sessionId,mode:be})}catch(Qe){console.error("Stop CLI failed:",Qe)}},[U,X,e]),uc=a.useCallback(async be=>{const Ce=be||U;!Ce||!Xe(Ce)&&!Ve(Ce)||(xe(Ce),z(!0))},[U]),mc=a.useMemo(()=>!U||!Xe(U)||Ve(U)?null:js(U),[U]),fc=a.useCallback(async be=>{if(!U||!Xe(U)||Ve(U))return;const Ce=js(U);if(Ce===be)return;const je=U.sessionId;je&&ee(he=>({...he,[je]:be}));try{await e(qt(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:It(U),mode:be})}catch(he){je&&ee(Pe=>{const Qe={...Pe};return Ce===Ja(x,je)?delete Qe[je]:Qe[je]=Ce,Qe}),Kf(he)?console.warn("Skipped CLI view mode switch:",he instanceof Error?he.message:String(he)):console.error("Failed to switch CLI view mode:",he)}},[U,x,e]),{versionMismatchDaemons:pc,hasRequiredVersionDaemons:fa,appVersion:xc,versionBannerDismissed:hc,setVersionBannerDismissed:bc,upgradingDaemons:gc,handleBannerUpgrade:yc}=Im({ides:x,sendDaemonCommand:e}),pa=a.useCallback(be=>{ye(be.tabKey),i(Ce=>{const je=new URLSearchParams(Ce),he=fd(be);return he?je.set("activeTab",he):je.delete("activeTab"),je},{replace:!0})},[i]),xa=a.useCallback(be=>{Ze(be.tabKey),pa(be)},[pa,Ze]),vc=a.useCallback(be=>{lt(be.tabKey)},[lt]);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(Ud,{wsStatus:f,showReconnected:b}),t.jsx(zd,{terminalBackend:Ke,isStandalone:ze,machineLabel:qe,machineKey:Ye}),(!hc||fa)&&t.jsx($f,{daemons:pc,targetVersion:xc,required:fa,upgradingDaemons:gc,onUpgrade:yc,onDismiss:()=>bc(!0)}),t.jsx(Mf,{showMobileChatMode:Me,isMobile:S,activeConv:U,chatIdes:ut,wsStatus:f,isConnected:N,onOpenHistory:be=>{be&&Ue(be),P(!0)},onOpenRemote:Ee,onStopCli:uc,activeCliViewMode:mc,onSetActiveCliViewMode:fc,mobileChatConversations:le,ides:x,actionLogs:re,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:Z,isStandalone:ze,initialDataLoaded:v,userName:u.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Le,requestedMachineId:m,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:mt,isSplitMode:$,numGroups:Q,groupSizes:O,groupedConvs:B,clearedTabs:fe,focusedGroup:y,setFocusedGroup:h,moveTabToGroup:F,splitTabRelative:Se,closeGroup:Y,handleResizeStart:ie,groupActiveTabIds:W,setGroupActiveTabIds:I,groupTabOrders:T,setGroupTabOrders:M,toggleHiddenTab:ot,visibleConversations:Oe,hiddenConversations:pe,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:Le,onDesktopActiveTabChange:ye,onHideConversation:vc,onShowHiddenConversation:xa,onShowAllHiddenConversations:ht,scrollToBottomRequest:D,machineEntries:We,onBrowseMachineDirectory:it,onSaveMachineWorkspace:Mt,onLaunchMachineIde:pt,onLaunchMachineProvider:Ts,onListMachineSavedSessions:sc}),t.jsx("style",{children:`
60
+ body { overflow: hidden; overscroll-behavior: none; }
61
+ `}),t.jsx(Ef,{historyModalOpen:A,historyTargetConv:Be,ides:x,isHistoryCreatingChat:ac,isHistoryRefreshingHistory:E?!1:oc,savedHistorySessions:Te,isSavedHistoryLoading:we,isResumingSavedHistorySessionId:ae,onCloseHistory:()=>P(!1),onNewHistoryChat:cc,onSwitchHistorySession:ic,onRefreshHistory:E?qr:lc,onResumeSavedHistorySession:dc,remoteDialogConv:He,remoteDialogIdeEntry:Fe,connectionStates:R,actionLogs:re,localUserMessages:me,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:Z,isStandalone:ze,userName:u.userName,onOpenRemoteHistory:be=>{be&&Ue(be),P(!0)},onRemoteConversationChange:Ue,onCloseRemoteDialog:yt,cliStopDialogOpen:K,cliStopTargetConv:X,onCancelCliStop:()=>{z(!1),xe(null)},onStopCliNow:async()=>{z(!1),await ma("hard",X),xe(null)},onSaveCliAndStop:async()=>{z(!1),await ma("save",X),xe(null)},toasts:k,onDismissToast:be=>L(Ce=>Ce.filter(je=>je.id!==be)),onClickToast:be=>{if(be.targetKey){const Ce=Ct(be.targetKey);Ce&&(h(Nt.get(Ce.tabKey)??0),xa(Ce),ge({tabKey:Ce.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}g(!1)}})]})}function Hf({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[l,m]=a.useState(null),[p,u]=a.useState(null),[x,v]=a.useState(!1),[C,L]=a.useState(null),[d,g]=a.useState(!1),[k,f]=a.useState(""),N=a.useRef(null),R=a.useCallback(A=>{N.current=A},[]),b=a.useCallback((A,P,K=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:A,message:P}]),setTimeout(()=>{var z;return(z=o.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),K&&nt.showToast(P,A==="error"||A==="warn"?"warning":"success")},[o]),w=a.useCallback(A=>{const P=A instanceof Error?A.message:String(A||"");return P.includes("P2P command timeout")||P.includes("P2P not connected")||P.includes("P2P not available")},[]),j=a.useCallback(async(A,P)=>{var K;if(!e||l)return!1;m(A),b("info",`Launching ${rt(A)}${P!=null&&P.workspace?` in ${P.workspace}`:""}...`);try{const z={ideType:A,enableCdp:!0};(K=P==null?void 0:P.workspace)!=null&&K.trim()?z.workspace=P.workspace.trim():P!=null&&P.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",z);return b(X!=null&&X.success?"info":"error",X!=null&&X.success?`${rt(A)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(z){return b("error",`Launch error: ${z.message}`,!0),!1}finally{m(null)}},[e,l,b,r]),y=a.useCallback(async A=>{if(!e)return{success:!1};const{cliType:P,dir:K,workspaceId:z,useDefaultWorkspace:X,useHome:xe,argsStr:Te,model:Ne,resumeSessionId:we}=A;if(!P)return b("warn","Select a CLI or ACP provider first",!0),{success:!1};const te=Te?Te.split(/\s+/).filter(Boolean):void 0,ae=(K==null?void 0:K.trim())||(z?"(saved id)":X?"(default workspace)":xe?"(home)":"");b("info",`Launching ${P}${ae?` in ${ae}`:""}${Ne?` (model: ${Ne})`:""}...`),u(P);try{const V={cliType:P,cliArgs:te,initialModel:Ne||void 0};K!=null&&K.trim()?V.dir=K.trim():z?V.workspaceId=z:X?V.useDefaultWorkspace=!0:xe&&(V.useHome=!0),we&&(V.resumeSessionId=we);const oe=await r(e,"launch_cli",V),re=(oe==null?void 0:oe.result)||oe;return oe!=null&&oe.success?(b("info",`${P} launched`,!0),(re==null?void 0:re.launchSource)==="home"?b("info","📂 Running in home directory (explicit choice)"):(re==null?void 0:re.launchSource)==="defaultWorkspace"&&b("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:re==null?void 0:re.sessionId}):(b("error",`Failed: ${(oe==null?void 0:oe.error)||(re==null?void 0:re.error)}`,!0),(oe==null?void 0:oe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&L({cliType:P,argsStr:Te,model:Ne}),{success:!1,sessionId:re==null?void 0:re.sessionId})}catch(V){return w(V)?(b("warn",`${P} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(b("error",`Launch error: ${V.message}`,!0),{success:!1})}finally{u(null)}},[e,b,w,r]),h=a.useCallback(async(A,P,K,z)=>e?A?P.trim()?y({cliType:A,dir:P,argsStr:K,model:z}):(L({cliType:A,argsStr:K,model:z}),{success:!1}):(b("warn","Select a provider",!0),{success:!1}):{success:!1},[e,b,y]),W=a.useCallback(async(A,P,K)=>{if(e&&window.confirm(`Stop ${A}?
62
+ This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:A,dir:P,targetSessionId:K});z!=null&&z.success?b("info",`${A} stopped`,!0):b("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){b("error",`Stop failed: ${z.message}`,!0)}},[e,b,r]),I=a.useCallback(async A=>{try{await r(A.daemonId,"restart_ide",{ideType:A.type}),b("info",`${rt(A.type)} restart initiated`,!0)}catch(P){b("error",`Restart failed: ${P.message}`,!0)}},[b,r]),T=a.useCallback(async A=>{if(window.confirm(`Stop ${rt(A.type)}?
63
+ This will disconnect CDP and optionally kill the process.`))try{const P=await r(A.daemonId,"stop_ide",{ideType:A.type,killProcess:!0});P!=null&&P.success?b("info",`${rt(A.type)} stopped`,!0):b("error",`Stop failed: ${(P==null?void 0:P.error)||"Unknown error"}`,!0)}catch(P){b("error",`Stop failed: ${P.message}`,!0)}},[b,r]),M=a.useCallback(async()=>{if(e)try{const A=await r(e,"detect_ides",{});b("info",`Found ${((A==null?void 0:A.result)||[]).length} IDE(s)`,!0)}catch(A){b("error",`Detection failed: ${A.message}`,!0)}},[e,b,r]),O=a.useCallback(async A=>{if(!e||!A.trim())return!1;v(!0);try{const P=await r(e,"workspace_add",{path:A.trim()});return P!=null&&P.success?(b("info",`Workspace added: ${A.trim()}`),!0):(b("error",(P==null?void 0:P.error)||"workspace_add failed"),!1)}catch(P){return b("error",P.message),!1}finally{v(!1)}},[e,b,r]),_=a.useCallback(async A=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){v(!0);try{const P=await r(e,"workspace_remove",{id:A});P!=null&&P.success?b("info","Workspace removed",!0):b("error",(P==null?void 0:P.error)||"workspace_remove failed",!0)}catch(P){b("error",P.message,!0)}finally{v(!1)}}},[e,b,r]),S=a.useCallback(async A=>{var P;if(e){v(!0);try{const K=await r(e,"workspace_set_default",A===null?{clear:!0}:{id:A});if(K!=null&&K.success){b("info",A?"Default workspace updated":"Default workspace cleared",!0);const z=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";z&&((P=N.current)==null||P.call(N,z))}else b("error",(K==null?void 0:K.error)||"workspace_set_default failed",!0)}catch(K){b("error",K.message,!0)}finally{v(!1)}}},[e,b,r]),H=a.useCallback(async A=>{var K;if(!e||!A.trim())return;const P=A.trim();v(!0);try{const z=await r(e,"workspace_set_default",{path:P});z!=null&&z.success?(b("info","Default workspace set from history"),(K=N.current)==null||K.call(N,P)):b("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){b("error",z.message)}finally{v(!1)}},[e,b,r]),q=a.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:k}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:k})}catch(A){b("warn",`Live nickname updated, but account sync failed: ${A.message}`)}b("info",`Nickname set to "${k||"(cleared)"}"`),g(!1)}catch(A){b("error",`Failed: ${A.message}`)}},[e,k,s,b,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:x,launchPick:C,setLaunchPick:L,editingNickname:d,setEditingNickname:g,nicknameInput:k,setNicknameInput:f,addLog:b,handleLaunchIde:j,runLaunchCliCore:y,handleLaunchCli:h,handleStopCli:W,handleRestartIde:I,handleStopIde:T,handleDetectIdes:M,handleWorkspaceAdd:O,handleWorkspaceRemove:_,handleWorkspaceSetDefault:S,handleWorkspaceResumePath:H,handleSaveNickname:q,setOnDefaultWorkspaceChanged:R}}function Uf({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var I;const{workspaceBusy:l,handleWorkspaceAdd:m,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=i,[x,v]=a.useState(!1),[C,L]=a.useState(""),[d,g]=a.useState([]),[k,f]=a.useState(!1),[N,R]=a.useState(""),b=a.useCallback(async T=>{f(!0),R("");try{const M=await Fr(c,e,T);L(M.path),g(M.directories)}catch(M){R(M instanceof Error?M.message:"Could not load folder")}finally{f(!1)}},[e,c]),w=a.useCallback(()=>{v(!0);const T=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...o.map(O=>O.workspace)],M=zr(s.platform,Ur(T,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));b(M)},[o,n,r,b,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,y=s.availableMem??s.freeMem??s.totalMem,h=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/s.totalMem*100))):0,W=((I=s.loadavg)==null?void 0:I[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(ar,{icon:t.jsx(Bo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Tl(s.uptime):"Waiting…"}),t.jsx(ar,{icon:t.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(ar,{icon:t.jsx($r,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(ar,{icon:t.jsx(Xc,{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(Ta,{value:j?Math.min(Math.round(W/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${W.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Ta,{value:h,max:100,label:"Memory",color:"#3b82f6",detail:j?`${Zr(s.totalMem-y)} / ${Zr(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Zr(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(vs,{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:l,value:s.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.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:l,onClick:w,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=>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:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Kr(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(T.id),children:"Remove"})]},T.id))})]}),x&&t.jsx(Vr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:d,busy:k,error:N,confirmLabel:"Add workspace",onClose:()=>v(!1),onNavigate:T=>{b(T)},onConfirm:T=>{(async()=>{if(!T)return;await m(T)&&v(!1)})()}})]})}function zf(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 Ff(e,s,r){const n=[];for(const[o,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(m=>m.type===o);n.push({type:o,displayName:(l==null?void 0:l.displayName)||o,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[o]||{}})}return n}function bn(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function yo(e){if(!e||typeof e!="object")return null;if(bn(e))return e;const s=e,r=s.result;return bn(r)?r:bn(s.sourceConfig)?s.sourceConfig:null}function Vf(e){const s=e.trim();return s||null}const vo=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Gf=[{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 qf({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,l]=a.useState("codex-cli"),[m,p]=a.useState([]),[u,x]=a.useState(""),[v,C]=a.useState([]),[L,d]=a.useState(""),g=a.useRef(null),k=a.useRef(null),f=y=>{p(h=>h.includes(y)?h.filter(W=>W!==y):[...h,y])},N=()=>p([...vo]),R=()=>p([]);a.useEffect(()=>{var y;(y=g.current)==null||y.scrollIntoView({behavior:"smooth"})},[v]),a.useEffect(()=>()=>{k.current&&clearInterval(k.current)},[]);const b=a.useCallback(()=>{k.current&&clearInterval(k.current),k.current=setInterval(async()=>{try{const y=await r(e,"provider_auto_fix_status",{providerType:s.type});(y==null?void 0:y.running)===!1&&o==="running"&&(i("done"),C(h=>[...h,`
64
+ ✅ Auto-fix completed!`]),k.current&&clearInterval(k.current))}catch{}},3e3)},[e,s.type,r,o]),w=async()=>{if(m.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),d("");try{const y=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...u?{comment:u}:{}});y!=null&&y.success&&(y!=null&&y.started||y!=null&&y.running)?(C(h=>[...h,"✅ Agent started. Monitoring progress..."]),b()):(i("error"),d((y==null?void 0:y.error)||"Failed to start auto-fix"))}catch(y){i("error"),d((y==null?void 0:y.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),C(y=>[...y,`
65
+ ⚠️ Auto-fix cancelled.`]),i("done"),k.current&&clearInterval(k.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:y=>y.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:Gf.map(y=>t.jsxs("button",{onClick:()=>l(y.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===y.value?y.color+"66":"var(--border-subtle)",background:c===y.value?y.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===y.value?y.color:"var(--text-primary)"},children:y.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:y.desc})]},y.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:N,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:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:vo.map(y=>t.jsxs("button",{onClick:()=>f(y),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(y)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(y)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(y)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(y)?"☑ ":"☐ ",y]},y))})]}),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:u,onChange:y=>x(y.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:[v.map((y,h)=>t.jsx("div",{className:y.startsWith("✅")?"text-green-400":"",style:y.startsWith("❌")||y.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:y},h)),o==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:g})]}),L&&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:L})]})]}),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:w,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:j,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"),C([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Yf({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var b;const i=s.filter(w=>w.category==="ide"),[c,l]=a.useState(((b=i[0])==null?void 0:b.type)||""),[m,p]=a.useState(""),[u,x]=a.useState(""),[v,C]=a.useState(!1),[L,d]=a.useState(""),[g,k]=a.useState(!1),f=w=>{const j=w.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!u||u===N(m))&&x(N(j))},N=w=>w.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),R=async()=>{if(!(!m||!u||!c)){C(!0),d("");try{const w=await r(e,"provider_clone",{type:m,name:u,category:"ide",location:"user",cloneFrom:c});w!=null&&w.success||w!=null&&w.created?(k(!0),o==null||o(m)):d((w==null?void 0:w.error)||"Failed to create provider")}catch(w){d((w==null?void 0:w.message)||"Connection failed")}C(!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:w=>w.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:g?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(w=>t.jsxs("button",{onClick:()=>l(w.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===w.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===w.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:w.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===w.type?"#a78bfa":"var(--text-secondary)"},children:w.displayName})]},w.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:w=>f(w.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:u,onChange:w=>x(w.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"})]}),L&&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:L})]})}),t.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:g?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:R,disabled:!m||!u||v,className:"machine-btn",style:{background:m&&u?"rgba(34,197,94,0.12)":void 0,borderColor:m&&u?"rgba(34,197,94,0.3)":void 0,color:m&&u?"#86efac":void 0,opacity:!m||!u||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Xf({machineId:e,providers:s,sendDaemonCommand:r}){var I;const[n,o]=a.useState([]),[i,c]=a.useState(!1),[l,m]=a.useState(null),[p,u]=a.useState("all"),[x,v]=a.useState(null),[C,L]=a.useState(!1),[d,g]=a.useState(null),[k,f]=a.useState("normal"),[N,R]=a.useState(""),[b,w]=a.useState(!1),j=a.useCallback(async()=>{if(e)try{const T=await r(e,"get_provider_source_config",{}),M=yo(T);M&&(g(M),f(M.sourceMode),R(M.explicitProviderDir||""))}catch{}},[e,r]),y=a.useCallback(async()=>{if(e){c(!0);try{const T=await r(e,"get_provider_settings",{}),M=zf(T);if(M){const O=Ff(M,s);O.sort((_,S)=>_.category.localeCompare(S.category)||_.displayName.localeCompare(S.displayName)),o(O)}}catch{}c(!1)}},[e,s,r]);a.useEffect(()=>{n.length===0&&y(),d||j()},[]);const h=async(T,M,O)=>{m(`${T}.${M}`),o(_=>_.map(S=>S.type===T?{...S,values:{...S.values,[M]:O}}:S));try{const _=await r(e,"set_provider_setting",{providerType:T,key:M,value:O});_!=null&&_.success||y()}catch{y()}m(null)},W=async()=>{w(!0);try{const T=await r(e,"set_provider_source_config",{providerSourceMode:k,providerDir:Vf(N)}),M=yo(T);M?(g(M),f(M.sourceMode),R(M.explicitProviderDir||"")):await j(),await y()}catch{await j()}w(!1)};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(T=>t.jsx("button",{onClick:()=>u(T),className:`machine-btn text-[10px] px-2 py-0.5 ${p===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>L(!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:y,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:k,onChange:T=>f(T.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:N,onChange:T=>R(T.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void W(),disabled:b,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:b?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(d==null?void 0:d.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(d==null?void 0:d.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((I=d==null?void 0:d.providerRoots)==null?void 0:I.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(T=>T.category===p).length>1&&(()=>{const T=n.filter(S=>S.category===p),M=new Map;for(const S of T)for(const H of S.schema){if(H.type!=="boolean")continue;const q=M.get(H.key),A=!!(S.values[H.key]??H.default);q?(q.onCount+=A?1:0,q.total+=1):M.set(H.key,{label:H.label||H.key,onCount:A?1:0,total:1})}const O=[...M.entries()].filter(([,S])=>S.total===T.length);if(O.length===0)return null;const _=async(S,H)=>{for(const q of T)await h(q.type,S,H)};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 ",p.toUpperCase()," providers (",T.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([S,H])=>{const q=H.onCount===H.total,A=H.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:H.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",H.onCount,"/",H.total,")"]}),t.jsx("button",{onClick:()=>void _(S,!0),disabled:q,className:`machine-btn text-[9px] px-1.5 py-px ${q?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void _(S,!1),disabled:A,className:`machine-btn text-[9px] px-1.5 py-px ${A?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},S)})})]})})(),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(T=>p==="all"||T.category===p).map(T=>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:T.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:T.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:T.category==="acp"?"rgba(139,92,246,0.08)":T.category==="cli"?"rgba(59,130,246,0.08)":T.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:T.category==="acp"?"#a78bfa":T.category==="cli"?"#60a5fa":T.category==="ide"?"#86efac":"var(--status-warning)"},children:T.category}),T.category==="ide"&&t.jsx("button",{onClick:()=>v(s.find(M=>M.type===T.type)||{type:T.type,name:T.displayName,displayName:T.displayName,icon:T.icon,category:T.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:T.schema.map(M=>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:[M.label||M.key,l===`${T.type}.${M.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),M.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:M.description})]}),t.jsx("div",{className:"shrink-0",children:M.type==="boolean"?t.jsx("button",{onClick:()=>h(T.type,M.key,!(T.values[M.key]??M.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:T.values[M.key]??M.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:T.values[M.key]??M.default?21:3}})}):M.type==="number"?t.jsx("input",{type:"number",value:Number(T.values[M.key]??M.default??0)||0,min:M.min,max:M.max,onChange:O=>{const _=parseInt(O.target.value)||0;M.min!==void 0&&_<M.min||M.max!==void 0&&_>M.max||h(T.type,M.key,_)},className:"machine-input w-20 text-center text-[11px]"}):M.type==="select"&&M.options?t.jsx("select",{value:String(T.values[M.key]??M.default??""),onChange:O=>h(T.type,M.key,O.target.value),className:"machine-input text-[11px]",children:M.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(T.values[M.key]??M.default??""),onBlur:O=>h(T.type,M.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},M.key))})]},T.type))}),x&&t.jsx(qf,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>v(null)}),C&&t.jsx(Yf,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>L(!1),onCreated:()=>{L(!1),y()}})]})}const Qf=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Jf({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Zf(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function wo(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 ep({machineId:e,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,l]=a.useState([]),[m,p]=a.useState(0),[u,x]=a.useState(0),[v,C]=a.useState(!0),[L,d]=a.useState("debug"),[g,k]=a.useState("all"),f=a.useRef(null),N=a.useRef(!1),R=Zf(o,g);return a.useEffect(()=>{if(!e||!v)return;const b=async()=>{try{const[j,y]=await Promise.all([s(e,"get_logs",{count:200,minLevel:L,since:m}),s(e,"get_debug_trace",Jf({count:120,since:u,category:g}))]),h=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(h==null?void 0:h.logs)&&h.logs.length>0){n(T=>[...T,...h.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const I=Math.max(...h.logs.map(T=>T.ts));p(I)}const W=(y==null?void 0:y.result)||y;if(y!=null&&y.success&&Array.isArray(W==null?void 0:W.trace)){i(W.trace.slice(-120));const I=W.trace.reduce((T,M)=>Math.max(T,Number(M.ts||0)),u);I>u&&x(I)}}catch{}l(as.list({limit:120}))};b();const w=setInterval(b,3e3);return()=>clearInterval(w)},[e,v,m,u,L,g,s]),a.useEffect(()=>{if(v&&(r.length>0||o.length>0||c.length>0)){const b=N.current?"smooth":"instant";setTimeout(()=>{var w;(w=f.current)==null||w.scrollIntoView({behavior:b}),N.current=!0},50)}},[r.length,o.length,c.length,v]),a.useEffect(()=>{i([]),x(0)},[g]),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(b=>t.jsx("button",{onClick:()=>{d(b),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${L===b?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:b.toUpperCase()},b))]}),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=",R.length," web=",c.length]}),t.jsx("button",{onClick:()=>C(!v),className:`machine-btn ${v?"text-green-500 border-green-500/30":""}`,children:v?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),x(0),as.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((b,w)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:b.level==="error"?"#ef4444":b.level==="warn"?"var(--status-warning)":b.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(b.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:b.level==="error"?"ERR":b.level==="warn"?"WRN":b.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:b.message})]},`log-${w}`))]}),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.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",g==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:Qf.map(b=>t.jsx("button",{onClick:()=>k(b.value),className:`machine-btn text-[10px] px-2 py-0.5 ${g===b.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:b.label},b.value))})]}),R.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:g==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),R.map(b=>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(b.ts).toLocaleTimeString()}),t.jsx("span",{children:b.level.toUpperCase()}),t.jsxs("span",{children:[b.category,".",b.stage]}),b.interactionId&&t.jsxs("span",{children:["ix=",b.interactionId]})]}),t.jsx("div",{children:wo(b.payload)})]},b.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(b=>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(b.ts).toLocaleTimeString()}),t.jsx("span",{children:b.kind}),b.topic&&t.jsxs("span",{children:["topic=",b.topic]}),b.interactionId&&t.jsxs("span",{children:["ix=",b.interactionId]})]}),t.jsx("div",{children:wo(b.payload)})]},b.id))]})]}),t.jsx("div",{ref:f})]})}function gn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function yn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function jo(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 tp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function sp(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 rp(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 np({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[l,m]=a.useState(!1),p=Ai(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),u=p.diagnostics,x=p.loading,v=p.applyDiagnostics,C=a.useMemo(()=>vf({diagnostics:u,loading:x,refreshing:l,error:n}),[u,x,l,n]),L=a.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),d=a.useCallback(async()=>{if(e){m(!0);try{const I=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),T=gn(I);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");v(T.diagnostics||T.result||null),o("")}catch(I){const T=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";o(T)}finally{m(!1)}}},[v,e,r]);a.useEffect(()=>{!e||u||x||l||d()},[u,x,e,d,l]);const g=a.useCallback(async(I,T)=>{const M=`${I}:${T.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
66
+ This will terminate the hosted runtime.`))){c(M);try{const O=await r(e,I,{sessionId:T.sessionId}),_=gn(O);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Session host action failed");const S=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${S}: ${T.displayName}`,"success"),await d()}catch(O){const _=O instanceof Error?O.message:"Session host action failed";nt.showToast(_,"warning"),o(_)}finally{c(O=>O===M?null:O)}}},[e,d,r]),k=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
67
+ 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",{}),M=gn(T);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const O=M.result||{},_=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,S=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;nt.showToast(`Pruned ${_} duplicate runtime(s) across ${S} group(s)`,"success"),await d()}catch(T){const M=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(M,"warning"),o(M)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,d,r]),f=a.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,T)=>(T.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=a.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Zi(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),R=N.liveRuntimes,b=N.recoverySnapshots,w=N.inactiveRecords,j=a.useMemo(()=>rp(R),[R]),y=a.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),h=a.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),W=(I,T)=>{var K;const M=i===`session_host_resume_session:${I.sessionId}`,O=i===`session_host_restart_session:${I.sessionId}`,_=i===`session_host_stop_session:${I.sessionId}`,S=ua(I.meta),H=L.get(I.sessionId),q=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,A=T==="recovery"?"Recover":"Resume",P=ec(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:I.displayName||(H==null?void 0:H.cliName)||I.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${sp(I.lifecycle)}`,children:I.lifecycle}),S&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),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:I.workspaceLabel||(H==null?void 0:H.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((K=I.writeOwner)==null?void 0:K.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:tp(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(On,{size:11})," ",q]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",jo(I.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",P]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_resume_session",I)},children:M?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",I)},children:O?"Restarting…":"Restart"}),T==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.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:()=>{g("session_host_stop_session",I)},children:_?"Stopping…":"Stop"})]})]})},I.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(Ht,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:eu()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${C.toneClass}`,children:C.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:x||l,children:[t.jsx(Is,{size:13}),x||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&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(is,{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 need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&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:u.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:b.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:u.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:jo(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:yn(u.hostStartedAt)})]})]}),h&&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(is,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:h.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[yn(h.timestamp),h.sessionId?` · ${h.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($r,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ys("live")}),R.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:R.map(I=>W(I,"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(Ht,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ys("recovery")}),b.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:b.map(I=>W(I,"recovery"))})]}),w.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:ys("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:w.map(I=>W(I,"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"}),y.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:y.map(I=>{var M;const T=f.find(O=>O.sessionId===I.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)||((M=L.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",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:yn(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ap({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 vn({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 wn({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 op({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),m=r.slice(0,4),u=Os(e,"0.8.62");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:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(Ut,{size:13}),children:"Current Chats"}),t.jsx(wn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const v=Mn(x);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(x),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:at(x)}),v>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Wr(v)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ls(x)})]},x.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(Bo,{size:13}),children:"Recent Launches"}),t.jsx(wn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(x=>{const{metaText:v,updatedLabel:C}=Bi(x);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:()=>i(x),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:x.label}),C&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:v})]},x.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(is,{size:13}),children:"Daemon Update"}),t.jsx(wn,{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:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"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(Is,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function ip(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function cp(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const lp={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 gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function dp(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 jn({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:m,initialWorkspacePath:p}){const u=Cs(),{handleLaunchIde:x,handleStopCli:v,handleRestartIde:C,handleStopIde:L,handleDetectIdes:d,launchingIde:g,launchingAgentType:k,addLog:f}=c,[N,R]=a.useState(null),b=a.useCallback(E=>{E&&u(ip(E))},[u]),w=lp[e],j=e==="ide",y=e==="acp",h=a.useMemo(()=>n.filter(E=>E.category===e&&(e==="ide"||E.installed!==!1)),[e,n]),W=a.useMemo(()=>new Map(h.map(E=>[E.type,E.displayName||E.type])),[h]),[I,T]=a.useState(""),[M,O]=a.useState(""),[_,S]=a.useState([]),[H,q]=a.useState(""),[A,P]=a.useState(""),[K,z]=a.useState([]),[X,xe]=a.useState(!1),[Te,Ne]=a.useState(""),[we,te]=a.useState(!1),[ae,V]=a.useState(()=>xt()),[oe,re]=a.useState(null),[Z,me]=a.useState(p?"__custom__":m||s.defaultWorkspaceId||""),[se,ce]=a.useState(p||""),[ee,fe]=a.useState([]),[ne,ke]=a.useState(!1),[ye,D]=a.useState(""),[ge,G]=a.useState([]),[ve,Ie]=a.useState(!1),[Ae,We]=a.useState(""),ze=a.useRef(null),[Ke,qe]=a.useState(null),Ye=a.useRef("__home__"),[ft,$e]=a.useState("__home__"),[lt,ot]=a.useState(!1),Ze=a.useRef(0),ht=ee.filter(E=>!o.some(J=>J.type===E&&jt(J.status)!=="stopped")),ut=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!Z&&me(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(p){me("__custom__"),ce(p);return}m&&(me(m),ce(""))},[m,p]),a.useEffect(()=>{j||I&&(h.some(E=>E.type===I)||(T(""),P("")))},[h,j,I]);const ue=(()=>{if(Z==="__custom__")return se.trim();if(!Z)return"";const E=(s.workspaces||[]).find(J=>J.id===Z);return(E==null?void 0:E.path)||""})(),Oe=a.useCallback(E=>{const J=ut.current[E];J&&(clearTimeout(J),delete ut.current[E]),fe(le=>le.includes(E)?le.filter(Me=>Me!==E):le)},[]),et=a.useRef(new Set),Ge=a.useCallback(async E=>{if(l){Ie(!0),We("");try{const J=await Fr(l,r,E);D(J.path),ce(J.path),G(J.directories)}catch(J){We(J instanceof Error?J.message:"Could not load folder")}finally{Ie(!1)}}},[r,l]),Ct=a.useCallback(()=>{if(!l)return;me("__custom__"),ke(!0);const E=o.map(le=>le.workspace),J=zr(s.platform,Ur(se.trim(),ue,p,E,s.defaultWorkspacePath,(s.workspaces||[]).map(le=>le.path)));Ge(J)},[se,p,Ge,s.defaultWorkspacePath,s.platform,s.workspaces,o,ue,l]),bt=a.useCallback(E=>{const J=String(E.workspace||"").trim();if(!J)return;const le=(s.workspaces||[]).find(Me=>gr(Me.path)===gr(J));if(le){me(le.id),ce("");return}me("__custom__"),ce(J)},[s.workspaces]),gt=a.useCallback(E=>{const J=String(E.workspace||"").trim();if(!J)return{workspaceId:null,workspacePath:"",useHome:!0};const le=(s.workspaces||[]).find(Me=>gr(Me.path)===gr(J));return le?{workspaceId:le.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:J,useHome:!1}},[s.workspaces]),mt=a.useCallback(async E=>{if(!l||!E||e!=="cli"){z([]),xe(!1),Ne("");return}const J=Ze.current+1;Ze.current=J,xe(!0),Ne("");try{const le=await l(r,"list_saved_sessions",{providerType:E,kind:"cli",limit:30});if(Ze.current!==J)return;const Me=(le==null?void 0:le.result)??le;z(Array.isArray(Me==null?void 0:Me.sessions)?Me.sessions:[])}catch(le){if(Ze.current!==J)return;z([]),Ne(le instanceof Error?le.message:"Could not load saved sessions")}finally{Ze.current===J&&xe(!1)}},[e,r,l]),Nt=a.useMemo(()=>{if(e!=="cli"||!I)return null;const E=W.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:E,agentType:I,status:"idle",title:E,messages:[],ideType:I,workspaceName:ue,displayPrimary:E,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,W,ue,A,I]),Q=a.useCallback(E=>{if(e==="ide"||!E){S([]);return}S(Qi(r,E))},[e,r]);a.useEffect(()=>{if(P(""),Q(I),e!=="cli"||!I){z([]),Ne(""),xe(!1);return}mt(I)},[e,Q,mt,I]);const $=a.useMemo(()=>K.find(E=>E.providerSessionId===A)||null,[K,A]);a.useEffect(()=>{if(!A)return;const E=K.find(J=>J.providerSessionId===A);E!=null&&E.canResume||P("")},[K,A]);const B=a.useCallback((E,J)=>{ze.current=J,Ye.current=E.selectedWorkspaceKey||"__home__",$e(E.selectedWorkspaceKey||"__home__"),qe(E)},[]),F=a.useCallback(()=>{ze.current&&(ot(!0),ze.current().finally(()=>{ze.current=null,ot(!1),qe(null)}))},[]),Y=a.useCallback(E=>{if(!E)return;fe(le=>le.includes(E)?le:[...le,E]);const J=ut.current[E];J&&clearTimeout(J),ut.current[E]=setTimeout(()=>{fe(le=>le.includes(E)?le.filter(Me=>Me!==E):le),delete ut.current[E]},2e4)},[]);a.useEffect(()=>{for(const J of o)jt(J.status)!=="stopped"&&(ee.includes(J.type)&&!et.current.has(J.type)&&(et.current.add(J.type),f("info",`${W.get(J.type)||J.type} launched`,!0)),Oe(J.type));const E=new Set(o.filter(J=>jt(J.status)!=="stopped").map(J=>J.type));et.current.forEach(J=>{!ee.includes(J)&&!E.has(J)&&et.current.delete(J)})},[f,Oe,o,ee,W]),a.useEffect(()=>()=>{Object.values(ut.current).forEach(clearTimeout),ut.current={}},[]);const[ie,Se]=a.useState({}),[U,de]=a.useState(null);a.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const J=await l(r,"get_ide_extensions",{}),le=(J==null?void 0:J.result)||J;le!=null&&le.success&&(le!=null&&le.ideExtensions)&&Se(le.ideExtensions)}catch{}})()},[j,r,l]);const Re=E=>j?rt(E.type):e==="cli"?E.cliName:E.acpName,Le=j?s.detectedIdes||[]:[],He=a.useCallback(async E=>{const J=(E==null?void 0:E.type)||I,le=(E==null?void 0:E.workspacePath)??ue;if(j){await x(J,le?{workspace:le}:void 0)&&Y(J);return}const Me=await c.runLaunchCliCore({cliType:J,dir:E!=null&&E.workspaceId?void 0:le||void 0,workspaceId:(E==null?void 0:E.workspaceId)||void 0,useHome:(E==null?void 0:E.useHome)||!(E!=null&&E.workspaceId)&&!le,argsStr:(E==null?void 0:E.argsStr)??(M||void 0),model:(E==null?void 0:E.model)??(y&&H||void 0),resumeSessionId:(E==null?void 0:E.resumeSessionId)||!y&&e==="cli"&&J===I&&A||void 0});if(Me.success||Me.pending){const pe=(E==null?void 0:E.argsStr)??M;!j&&(pe!=null&&pe.trim())&&(Ji(r,J,pe),Q(J)),Y(J),Me.success&&Me.sessionId&&b(Me.sessionId)}},[c,x,y,j,M,H,Q,Y,r,b,ue,A,I]),Fe=ui(j?"ide":y?"acp":"cli",!j&&!y&&!!A),tt=mi(j?"ide":y?"acp":"cli",!j&&!y&&!!A),Ue=()=>{var pe;const E=j?rt(I):W.get(I)||I,J=!j&&!y&&!!A,{options:le,selectedKey:Me}=ns({machine:s,currentWorkspaceId:Z&&Z!=="__custom__"?Z:null,currentWorkspacePath:ue});B({title:J?ea(E):es("start-fresh",E),description:J?ta():ts("start-fresh"),confirmLabel:Fe,busyLabel:tt,workspaceOptions:le,selectedWorkspaceKey:Me,details:[{label:"Mode",value:w.label},{label:"Provider",value:E},...!j&&e==="cli"&&A?[{label:"Resume",value:((pe=K.find(_e=>_e.providerSessionId===A))==null?void 0:pe.title)||A}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...y&&H.trim()?[{label:"Model",value:H.trim()}]:[]]},async()=>{const _e=le.find(it=>it.key===Ye.current);_e!=null&&_e.workspaceId?(me(_e.workspaceId),ce("")):_e!=null&&_e.workspacePath?(me("__custom__"),ce(_e.workspacePath)):(me(""),ce("")),await He({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Ee=E=>{j?L(E):v(E.type,E.workspace,E.id)},yt=a.useCallback(async(E,J,le=!1)=>{if(E.mode===J){le&&E.sessionId&&b(E.sessionId);return}if(!l||!E.sessionId){le&&E.sessionId&&b(E.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:E.type,mode:J}),le&&b(E.sessionId)}catch(Me){dp(Me)?console.warn("Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},[r,b,l]),Be=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:Z,onChange:E=>{const J=E.target.value;if(me(J),J==="__custom__"&&l){Ct();return}J!=="__custom__"&&ce("")},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(E=>t.jsxs("option",{value:E.id,children:[E.id===s.defaultWorkspaceId?"⭐ ":"",Kr(E.path,E.label)]},E.id)),t.jsx("option",{value:"__custom__",children:l?"📁 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:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),Z==="__custom__"&&(l?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:Ct,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:E=>ce(E.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:Z==="__custom__"?ue?t.jsx("span",{className:"font-mono truncate block",title:ue,children:ue}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ue?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:Z===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ue,children:ue})]}):"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 ${w.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 ",w.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Le.length>0?Le.map(E=>{const J=o.find(it=>(it.type||"").toLowerCase()===(E.type||"").toLowerCase()&&jt(it.status)!=="stopped"),le=E.running||!!J,Me=!!J&&J.cdpConnected,pe=ee.includes(E.type||E.id||""),_e=I===(E.type||"");return t.jsxs("button",{onClick:()=>{if(Me&&J){const it=J.sessionId;it?u(`/dashboard?activeTab=${encodeURIComponent(it)}`,{state:{openRemoteForTabKey:it}}):u("/dashboard",{state:{openRemoteForTabKey:J.id}});return}pe||T(it=>it===(E.type||"")?"":E.type||"")},disabled:!!g||pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Me?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":_e?"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:g&&g!==E.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(E.type)}),le&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Me?"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:E.name||rt(E.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Me?"text-green-400":pe?"text-orange-400":_e?"text-accent-primary":"text-text-muted"}`,children:Me?"Open Session":pe?"Starting...":_e?"Configure":"Select"})]})]},E.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:d,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(Fc,{size:14})," Scan System"]})]}):h.length>0?h.map(E=>{const J=I===E.type,le=ee.includes(E.type),pe=!!o.find(_e=>_e.type===E.type&&jt(_e.status)!=="stopped");return t.jsxs("button",{onClick:()=>T(_e=>_e===E.type?"":E.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${J?"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:E.icon}),pe&&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:E.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${le?"text-orange-400":J?"text-accent-primary":"text-text-muted"}`,children:le?"Starting...":J?"Configure":"Select"})]})]},E.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."})]})}),I&&(j?Le.find(E=>E.type===I):h.find(E=>E.type===I))&&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:j?rt(I):W.get(I)||I})]}),Be,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!y&&e==="cli"&&t.jsx(tc,{busy:!!k||!!g||ee.includes(I),savedSessionsLoading:X,savedSessionsError:Te,selectedSession:$,onRefresh:()=>void mt(I),onOpenHistory:()=>{I&&(te(!0),mt(I))},onClearSelection:()=>P("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&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:H,onChange:E=>q(E.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:M,onChange:E=>O(E.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"}),_.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(E=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(E),title:E,children:E},E))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Ue,disabled:!!k||!!g||ee.includes(I),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:k===I||g===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ee.filter(E=>!o.some(J=>J.type===E&&jt(J.status)!=="stopped")).length,")"]}),o.length===0&&ht.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 ",w.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ht.map(E=>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(E)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?rt(E):W.get(E)||E}),t.jsx("div",{className:"text-[11px] text-text-muted",children:k===E?"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:${E}`)),o.map(E=>{const J=j?E:null,le=!j&&!y?E:null,Me=jt(E.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(E.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Re(E),(J==null?void 0:J.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",J.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:E.workspace||"—"}),(le==null?void 0:le.mode)&&t.jsx("span",{className:le.mode==="chat"?"text-violet-400":"text-text-secondary",children:le.mode==="chat"?"Chat view":"Terminal view"})]}),le&&(le.runtimeKey||le.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[le.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 ",le.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 pe;(pe=navigator.clipboard)==null||pe.writeText(`adhdev attach ${le.runtimeKey}`),R(le.runtimeKey||null),window.setTimeout(()=>{R(_e=>_e===le.runtimeKey?null:_e)},1200)},children:N===le.runtimeKey?"Copied":"Copy"})]}),le.runtimeWriteOwner&&t.jsx("span",{style:{color:le.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:le.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:cp(le.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 ${Me==="stopped"?"bg-red-500/[0.08] text-red-500":Me==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Me}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const pe=E.sessionId;if(pe){u(`/dashboard?activeTab=${encodeURIComponent(pe)}`,{state:{openRemoteForTabKey:pe}});return}u("/dashboard",{state:{openRemoteForTabKey:E.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(Tt,{size:13})}),t.jsx("button",{onClick:()=>{const pe=E.workspace||"",{options:_e,selectedKey:it}=ns({machine:s,currentWorkspacePath:pe});B({title:es("restart-ide",rt(E.type)),description:ts("restart-ide"),confirmLabel:Ns("restart-ide"),busyLabel:Ss("restart-ide"),workspaceOptions:_e,selectedWorkspaceKey:it,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:rt(E.type)}]},async()=>{const Mt=_e.find(Ts=>Ts.key===Ye.current),pt=(Mt==null?void 0:Mt.workspacePath)??"";if(pt&&pt!==pe){await He({type:E.type,workspacePath:pt});return}await C(E)})},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(Is,{size:14})})]}),y&&t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&b(pe)},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:!E.sessionId,children:t.jsx(Ut,{size:14})}),le&&Me!=="stopped"&&t.jsxs(t.Fragment,{children:[le.mode&&t.jsx(Qn,{mode:le.mode,onChange:pe=>void yt(le,pe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const pe=E.sessionId;pe&&b(pe)},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:!E.sessionId,children:le.mode==="chat"?t.jsx(Ut,{size:14}):t.jsx(Tt,{size:13})})]}),Me==="stopped"?t.jsx("button",{onClick:()=>{const pe=E.workspace||"",_e=j?rt(E.type):Re(E),{options:it,selectedKey:Mt}=ns({machine:s,currentWorkspacePath:pe});B({title:es("restart-stopped",_e),description:ts("restart-stopped"),confirmLabel:Ns("restart-stopped"),busyLabel:Ss("restart-stopped"),workspaceOptions:it,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:w.label},{label:"Provider",value:_e}]},async()=>{const pt=it.find(Ts=>Ts.key===Ye.current);await He({type:E.type,workspaceId:(pt==null?void 0:pt.workspaceId)??null,workspacePath:(pt==null?void 0:pt.workspacePath)??"",useHome:!(pt!=null&&pt.workspaceId)&&!(pt!=null&&pt.workspacePath)})})},disabled:ee.includes(E.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:ee.includes(E.type)?"⏳":t.jsx(Un,{size:14})}):t.jsx("button",{onClick:()=>Ee(E),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(kt,{size:14})})]})]}),J&&J.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:J.aiAgents.map(pe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Fo(pe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[pe.name," · ",jt(pe.status)]},pe.id))}),J&&(ie[J.type]||[]).length>0&&l&&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:(ie[J.type]||[]).map(pe=>t.jsxs("button",{disabled:U===`${J.type}.${pe.type}`,onClick:async()=>{const _e=`${J.type}.${pe.type}`;de(_e);try{await l(r,"set_ide_extension",{ideType:J.type,extensionType:pe.type,enabled:!pe.enabled}),Se(it=>({...it,[J.type]:(it[J.type]||[]).map(Mt=>Mt.type===pe.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}catch(it){console.error("Extension toggle failed:",it)}finally{de(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 ${pe.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 ${pe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),pe.name,t.jsx("span",{className:"text-[9px] font-normal",children:pe.enabled?"ON":"OFF"})]},pe.type))})]})]},E.id)})]}),ne&&l&&t.jsx(Vr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ye,directories:ge,busy:ve,error:Ae,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:E=>{Ge(E)},onConfirm:E=>{ce(E),me("__custom__"),ke(!1)}}),Ke&&t.jsx(la,{title:Ke.title,description:Ke.description,details:Ke.details,workspaceOptions:Ke.workspaceOptions,selectedWorkspaceKey:ft,onWorkspaceChange:E=>{Ye.current=E,$e(E)},confirmLabel:Ke.confirmLabel,busyLabel:Ke.busyLabel,busy:lt,onConfirm:F,onCancel:()=>{ze.current=null,qe(null)}}),we&&Nt&&t.jsx(sa,{activeConv:Nt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:K,isSavedSessionsLoading:X,isResumingSavedSessionId:oe,savedHistoryFilters:ae,onSavedHistoryFiltersChange:V,onClose:()=>te(!1),onNewChat:()=>{P(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{mt(I)},onResumeSavedSession:E=>{if(!E.canResume||oe)return;const J=gt(E);P(E.providerSessionId),bt(E),re(E.providerSessionId),te(!1),He({type:E.providerType,workspaceId:J.workspaceId,workspacePath:J.workspacePath,useHome:J.useHome,resumeSessionId:E.providerSessionId}).finally(()=>{re(le=>le===E.providerSessionId?null:le)})}})]})}const ko=[{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 up({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:l,initialCategory:m="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:x}){var d;const[v,C]=a.useState(m);a.useEffect(()=>{C(m)},[m]);const L=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:ko.map(g=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===g.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>C(g.id),children:[t.jsx("span",{children:g.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===g.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L[g.id]})]},g.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=ko.find(g=>g.id===v))==null?void 0:d.helper})]}),v==="ide"&&t.jsx(jn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u}),v==="cli"&&t.jsx(jn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u}),v==="acp"&&t.jsx(jn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u})]})}function mp({onNicknameSynced:e}={}){var Z,me,se,ce,ee,fe,ne,ke,ye;const{id:s}=Ic(),r=Cs(),n=Wn(),{sendCommand:o}=Rt(),i=tr(),c=ri(),l=c.ides||[],m=c.initialLoaded??!0,p=l.find(D=>D.id===s&&D.type==="adhdev-daemon"),u=l.some(D=>D.type==="adhdev-daemon"),[x,v]=a.useState("workspace"),[C,L]=a.useState("ide"),d=a.useRef(null),[g,k]=a.useState(null),f=a.useRef("__home__"),[N,R]=a.useState("__home__"),[b,w]=a.useState(!1),j=a.useRef(null);a.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Fu(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:15e3});const y=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},h=Hf({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:j});a.useEffect(()=>nt.onToast(ge=>{c.setToasts(ve=>{if(ve.some(We=>We.message===ge.message&&ge.timestamp-We.timestamp<3e3))return ve;const Ae={id:ge.id,message:ge.message,type:ge.type,timestamp:ge.timestamp,targetKey:ge.targetKey,actions:ge.actions};return[...ve.slice(-4),Ae]});const G=ge.duration||5e3;setTimeout(()=>c.setToasts(ve=>ve.filter(Ie=>Ie.id!==ge.id)),G)}),[c]);const W=(p==null?void 0:p.availableProviders)||[],I={};for(const D of W)I[D.type]=D.icon;const T=D=>I[D]||"",M=p?{id:p.id,hostname:Vo(p,{fallbackId:p.id}),platform:((Z=p.machine)==null?void 0:Z.platform)||"unknown",arch:((me=p.machine)==null?void 0:me.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((ce=p.machine)==null?void 0:ce.totalMem)||0,freeMem:(ee=p.machine)==null?void 0:ee.freeMem,availableMem:(fe=p.machine)==null?void 0:fe.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ke=p.machine)==null?void 0:ke.uptime,release:((ye=p.machine)==null?void 0:ye.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,O=l.filter(D=>D.daemonId===s&&D.type!=="adhdev-daemon").filter(D=>!Ys(D)&&!bs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Dl(D.aiAgents||(D.agents||[]).map(ge=>({id:ge.name,name:ge.name,status:ge.status,version:ge.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:s})),_=l.filter(D=>D.daemonId===s&&Ys(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:s})),S=l.filter(D=>D.daemonId===s&&bs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:s})),H=p?At(p,{fallbackId:s}):"",q="workspace",A=n.state,P=A==null?void 0:A.initialMachineTab,K=A==null?void 0:A.initialWorkspaceCategory,z=A==null?void 0:A.initialWorkspaceId,X=A==null?void 0:A.initialWorkspacePath,xe=P==="ides"||P==="clis"||P==="acps"?"workspace":P||q,Te=P==="ides"?"ide":P==="clis"?"cli":P==="acps"?"acp":K,Ne=[...O.map(D=>{var ge,G,ve,Ie,Ae;return{id:`ide:${D.type}:${D.workspace||""}`,label:((ge=D.activeChat)==null?void 0:ge.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ie=(ve=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:ve.at)==null?void 0:Ie.call(ve,-1))==null?void 0:Ae.timestamp)||0}}),..._.map(D=>{var ge,G,ve,Ie,Ae;return{id:`cli:${D.type}:${D.workspace||""}`,label:((ge=D.activeChat)==null?void 0:ge.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ie=(ve=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:ve.at)==null?void 0:Ie.call(ve,-1))==null?void 0:Ae.timestamp)||0}}),...S.map(D=>{var ge,G,ve,Ie,Ae;return{id:`acp:${D.type}:${D.workspace||""}`,label:((ge=D.activeChat)==null?void 0:ge.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Ae=(Ie=(ve=(G=D.activeChat)==null?void 0:G.messages)==null?void 0:ve.at)==null?void 0:Ie.call(ve,-1))==null?void 0:Ae.timestamp)||0}})].sort((D,ge)=>(ge.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),we=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:cs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):Ne,te=a.useMemo(()=>{var ge;const D=((ge=c.connectionStates)==null?void 0:ge[s||""])||void 0;return l.filter(G=>G.daemonId===s&&G.type!=="adhdev-daemon").flatMap(G=>ra(G,{},{connectionStates:s&&D?{[s]:D}:void 0,defaultConnectionState:D})).filter(G=>!(G.transport==="pty"&&G.mode==="terminal")).sort((G,ve)=>Mn(ve)-Mn(G))},[l,c.connectionStates,s]),ae=a.useCallback(D=>{const ge=D.sessionId||D.tabKey;ge&&r(`/dashboard?activeTab=${encodeURIComponent(ge)}`)},[r]),V=a.useCallback(()=>{d.current&&(w(!0),d.current().finally(()=>{d.current=null,w(!1),k(null)}))},[]),oe=a.useCallback(D=>{if(!M)return;const{options:ge,selectedKey:G}=ns({machine:M,currentWorkspacePath:D.workspace}),ve=async()=>{L(D.kind),v("workspace")};d.current=async()=>{const Ie=ge.find(ze=>ze.key===f.current),Ae=(Ie==null?void 0:Ie.workspacePath)??null,We=(Ie==null?void 0:Ie.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await h.handleLaunchIde(D.providerType,Ae?{workspace:Ae}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await h.runLaunchCliCore({cliType:D.providerType,dir:We?void 0:Ae||"",workspaceId:We||void 0,model:D.kind==="acp"&&qo(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await ve()},f.current=G,R(G),k({title:D.kind==="ide"?es("restart-ide",D.label):D.providerSessionId?ea(D.label):es("start-fresh",D.label),description:D.kind==="ide"?ts("restart-ide"):D.providerSessionId?ta():ts("start-fresh"),confirmLabel:D.kind==="ide"?Ns("restart-ide"):D.providerSessionId?Lr(!0):Ns("start-fresh"),busyLabel:D.kind==="ide"?Ss("restart-ide"):D.providerSessionId?Jn(!0):Ss("start-fresh"),workspaceOptions:ge,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[h,M]);if(a.useEffect(()=>{v(xe)},[q,xe,s]),a.useEffect(()=>{Te&&L(Te)},[Te,s]),!M)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:y,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 re=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:14})," Workspace"]}),count:O.length+_.length+S.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Er,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vc,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Uc,{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:y,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:[h.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:h.nicknameInput,onChange:D=>h.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&h.handleSaveNickname(),D.key==="Escape"&&h.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:h.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:()=>h.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:()=>{h.setEditingNickname(!0),h.setNicknameInput(M.machineNickname||"")},title:"Click to set nickname",children:H}),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:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:re.map(D=>t.jsxs("button",{onClick:()=>v(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.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(op,{machineEntry:p,providers:W,recentLaunches:we,currentConversations:te,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:oe,onOpenConversation:ae}),t.jsx(up,{machine:M,machineId:s,providers:W,ideSessions:O,cliSessions:_,acpSessions:S,actions:h,getIcon:T,initialCategory:C,initialWorkspaceId:z,initialWorkspacePath:X,sendDaemonCommand:o})]}),x==="providers"&&t.jsx(Xf,{machineId:s,providers:W,sendDaemonCommand:o}),x==="overview"&&t.jsx(Uf,{machineId:s,machine:M,ideSessions:O,cliSessions:_,acpSessions:S,actions:h,sendDaemonCommand:o}),x==="session-host"&&t.jsx(np,{machineId:s,cliSessions:_,sendDaemonCommand:o}),x==="logs"&&t.jsx(ep,{machineId:s,sendDaemonCommand:o})]})})}),h.launchPick&&M&&t.jsx(ap,{machine:M,launchPick:h.launchPick,actions:h}),g&&t.jsx(la,{title:g.title,description:g.description,details:g.details,workspaceOptions:g.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:D=>{f.current=D,R(D)},confirmLabel:g.confirmLabel,busyLabel:g.busyLabel,busy:b,onConfirm:V,onCancel:()=>{d.current=null,k(null)}}),t.jsx(fi,{toasts:c.toasts||[],onDismiss:D=>c.setToasts(ge=>ge.filter(G=>G.id!==D)),onClickToast:D=>{D.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(D.targetKey)}`)}}),t.jsx("style",{children:`
68
+ @keyframes toast-in {
69
+ from { opacity: 0; transform: translateX(40px); }
70
+ to { opacity: 1; transform: translateX(0); }
71
+ }
72
+ `})]})}class fp{constructor(){dt(this,"adapters",new Map);dt(this,"states",new Map);dt(this,"runtimeListeners",new Map);dt(this,"screenshotCallbacks",new Map);dt(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 Wt=new fp;function pp(){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 yr=pp(),No=3e3,xp=3e4;let $t=null,hp=0;const Dr=new Map;let Qt=null,Us=null;function So(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 bp(e){return e==="connected"?"connected":e}async function Sr(e,s,r){const n=mu(e,r||{}),o=$t;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++hp}_${Date.now()}`;return new Promise((c,l)=>{const m=setTimeout(()=>{Dr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Dr.set(i,{resolve:p=>{clearTimeout(m),c(p)},reject:p=>{clearTimeout(m),l(p)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function En(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class gp{constructor(s){dt(this,"daemonId");dt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN}get connectionState(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Sr(this.daemonId,s,r)}async sendInput(s,r){return Sr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Sr(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());Wt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(s){Qt&&(clearInterval(Qt),Qt=null)}}let _t=null;function yp(e){return(!_t||_t.daemonId!==e)&&(_t=new gp(e)),_t}function vp({children:e}){const s=a.useRef(Ir()),r=Ir();s.current=r;const{setUserName:n}=os(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,l]=a.useState("disconnected"),m=a.useCallback((d,g)=>{l(d),Us==null||Us(d,g)},[]),p=a.useRef(null),u=a.useRef(),x=a.useRef(No),v=a.useRef(!0),C=a.useRef(!1),L=a.useRef("initial_connect");return a.useEffect(()=>{v.current=!0,C.current=!1;function d(){var f,N;if(!v.current||((f=p.current)==null?void 0:f.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${yr}...`),$s("connect_attempt",{url:yr,reason:L.current,delayMs:x.current});let k;try{k=new WebSocket(yr)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),g();return}p.current=k,k.onopen=()=>{if(!v.current){k.close();return}m("connected"),x.current=No,$s("open",{url:yr,reason:L.current}),Vt.resubscribeAll({sendData:En}),console.log("[Standalone WS] Connected")},$t=k,k.onmessage=R=>{var b,w;try{const j=JSON.parse(R.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const y=Dr.get(j.requestId);y&&(Dr.delete(j.requestId),j.type==="error"?y.reject(new Error(((b=j.data)==null?void 0:b.message)||"Command failed")):y.resolve(j.data));return}if(j.type==="session_output"){const y=j.sessionId||j.cliId||j.cliType;y&&Wt.emitSessionOutput(y,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const y=j.update;y&&Vt.publish(y);return}if(j.type==="status"||j.type==="initial_state"){const y=j.data;if(!y)return;const{injectEntries:h,markLoaded:W,getIdes:I}=s.current,T=y.instanceId||"standalone",M=I().find(S=>S.id===T),O=yp(T);Wt.register(T,O),Wt.setState(T,"connected"),m("connected",T),Wt.emitStatus(T,y);const _=Tr(y,{daemonId:T,existingDaemon:M,existingEntries:I()});So("ws_status",{type:j.type,daemonId:T,sessions:(y.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(y.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),So("entries",{daemonId:T,entries:_.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),_.length>0&&h(_,{authoritativeDaemonIds:[T]}),W(),c.current!==T&&((w=i.current)==null||w.call(i),c.current=T,i.current=Vt.subscribe({sendData:En},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const H=s.current.getIdes(),q=H.find(P=>P.id===T),A=Tr(S.status,{daemonId:T,existingDaemon:q,existingEntries:H,timestamp:S.timestamp});A.length>0&&s.current.injectEntries(A),S.userName&&o.current&&o.current(S.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},k.onclose=R=>{v.current&&(_t==null||_t.stopScreenshots(),_t&&Wt.setState(_t.daemonId,"disconnected"),m("disconnected"),p.current=null,L.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,$s("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),g())},k.onerror=R=>{C.current||!v.current||(L.current="error",$s("error",{message:R instanceof Event?"event":String(R),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function g(){if(!v.current)return;clearTimeout(u.current);const k=x.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),$s("schedule_reconnect",{reason:L.current,delayMs:k}),u.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,xp),d()},k)}return d(),()=>{var k;v.current=!1,C.current=!0,(k=i.current)==null||k.call(i),i.current=null,c.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,$t=null),_t&&(_t.stopScreenshots(),Wt.unregister(_t.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function wp({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Us=(c,l)=>{r(c),l&&o(l)},()=>{Us=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",l=bp(s),m={};return n&&(m[n]=l),m.standalone=l,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(Dc,{connectionOverrides:i,children:t.jsx(vp,{children:e})})}const jp=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ro,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ht,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Er,{}),label:"Settings"}];function kp({children:e}){const s=Cs(),r=Wn(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=u=>{s(u),o(!1)},m=()=>{c(u=>{const x=!u;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},p=u=>`nav-item${r.pathname.startsWith(u)?" 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:u=>u.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(kt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:jp.map(u=>t.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>l(u.path),title:i?u.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:u.icon}),!i&&u.label]},u.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(Po,{})}),!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(Do,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.62"]}),t.jsx(Su,{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 Np=[{icon:t.jsx(Ht,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Eo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Fs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Po,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Sp=[{icon:t.jsx(Yc,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ro,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Br,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Hc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(On,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(zc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Cp=[{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 Ip(){return t.jsxs(yi,{icon:t.jsx(Do,{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.62"]}),children:[t.jsx(Dt,{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(Dt,{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:Np.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(Dt,{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:hi.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:gi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:bi.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-[11px] 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(Dt,{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:Sp.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(Dt,{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:Cp.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(vi,{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(al,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ap(){const{ides:e}=os(),s=e.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Rt(),{userName:o}=os(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const l=x=>{const v=x.target.value.trim();s!=null&&s.id&&v!==o&&n(s.id,"set_user_name",{userName:v}).catch(console.error)},[m,p]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=x=>{p(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return t.jsxs(yi,{icon:t.jsx(Er,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(yu,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Dt,{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.62"]}),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(Dt,{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(Dt,{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(Dt,{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(Ru,{})]}),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(Ou,{})]}),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(Uu,{})]})]})}),t.jsx(Dt,{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(Cu,{}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:u})]})}),t.jsx(Dt,{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(Oc,{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:l,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}Nu();Wu();const Tp=Lo({baseUrl:""});function Co(){const{ides:e,initialLoaded:s}=os();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(Sn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Sn,{to:"/dashboard",replace:!0})}function Mp(){const e=a.useMemo(()=>({sendCommand:Sr,sendData:En}),[]);return t.jsx(Ac,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Bc,{client:Tp,children:t.jsx(wp,{children:t.jsx(Kc,{value:e,children:t.jsx(kp,{children:t.jsxs(Tc,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(Of,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(Co,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(mp,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(Co,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(Ip,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(Ap,{})}),t.jsx(Yt,{path:"*",element:t.jsx(Sn,{to:"/dashboard",replace:!0})})]})})})})})})}$d({connectionManager:Wt});Mc(document.getElementById("root")).render(t.jsx(Mp,{}));