@adhdev/daemon-standalone 0.8.48 → 0.8.50

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.
@@ -1,71 +0,0 @@
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 Mi=Object.defineProperty;var Ai=(t,s,r)=>s in t?Mi(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var nt=(t,s,r)=>Ai(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as Ua,a as za,b as Ti,c as _i,u as fs,R as et,d as Ts,t as Pi,e as Li,D as Ri,f as Jr,g as Zr,h as un,i as Di,k as Ei,B as $i,l as Bi,m as Ft,N as Qr,n as Ki}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)}})();const Fa=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}),Va=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Un(t){var r,n;let s=0;return"activeChat"in t&&(s+=4),(r=t.childSessions)!=null&&r.length&&(s+=2),t.workspace&&(s+=1),t.machine&&(s+=1),(n=t.agents)!=null&&n.length&&(s+=1),s}function Ar(t,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},o=s.version??r.version??t.version,i=s.serverVersion??t.serverVersion??r.serverVersion,c=s.versionMismatch===!0||t.versionMismatch===!0,l=s.versionUpdateRequired===!0||t.versionUpdateRequired===!0,p=s.versionUpdateReason??t.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),p&&(n.versionUpdateReason=p),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(t){return Array.isArray(t)?t.map(cr):!t||typeof t!="object"?t:Object.fromEntries(Object.entries(t).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,cr(r)]))}function Wi(t,s){try{return JSON.stringify(cr(t))===JSON.stringify(cr(s))}catch{return!1}}function Os(t,s,r){return Wi(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function Oi(t,s,r){var p,x,m,h,y,S,I;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(u=>({...u,_lastUpdate:n}));const i=new Map;for(const u of s)i.set(u.id,u);for(const u of t){const b=i.get(u.id);if(!b){i.set(u.id,{...u,_lastUpdate:n});continue}const v=Un(u),d=Un(b);if(v>d){const N=(p=u.chats)!=null&&p.length?u.chats:b.chats,M=Ar(b,u,{...b,...u,chats:N,_lastUpdate:n});i.set(u.id,Os(b,M,n))}else if(v<d){const N={};if(u.status&&u.status!==b.status&&(N.status=u.status),u.cdpConnected!==void 0&&(N.cdpConnected=u.cdpConnected),(x=u.chats)!=null&&x.length&&!((m=b.chats)!=null&&m.length)&&(N.chats=u.chats),u.machineNickname!==void 0&&u.machineNickname!==b.machineNickname&&(N.machineNickname=u.machineNickname),u.version!==void 0&&(N.version=u.version),u.serverVersion!==void 0&&(N.serverVersion=u.serverVersion),u.versionMismatch===!0&&(N.versionMismatch=!0),Object.keys(N).length>0){const M=Ar(b,u,{...b,...N,_lastUpdate:b._lastUpdate});i.set(u.id,Os(b,M,n))}else Os(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const N=u.timestamp||n,M=b._lastUpdate||b.timestamp||0;if(N>=M){const k=(h=u.chats)!=null&&h.length?u.chats:b.chats,f=Ar(b,u,{...b,...u,chats:k,_lastUpdate:n});i.set(u.id,Os(b,f,n))}else(y=u.chats)!=null&&y.length&&!((S=b.chats)!=null&&S.length)&&i.set(u.id,{...b,chats:u.chats})}}const c=new Set(t.map(u=>u.id)),l=new Set;for(const u of t){const b=u.daemonId||((I=u.id)==null?void 0:I.split(":")[0]);b&&l.add(b)}for(const[u,b]of i){const v=b.daemonId||u.split(":")[0];if(!l.has(v))continue;if(o.has(v)&&!c.has(u)){i.delete(u);continue}const d=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(u)&&d>1e4||b.transport==="acp"&&!c.has(u)&&d>1e4||b.transport==="cdp-page"&&!c.has(u)&&d>3e4)&&i.delete(u)}for(const[u,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(u);return Array.from(i.values())}function Hi(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function Ui({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,l]=a.useState([]),[p,x]=a.useState(void 0),m=a.useRef(r);a.useEffect(()=>{m.current=r},[r]);const h=a.useCallback((v,d)=>{n(N=>{let M=!1;const k=N.map(f=>f.id!==v||f.chats===d?f:(M=!0,{...f,chats:d}));return M?k:N})},[]),y=a.useCallback((v,d)=>{n(N=>{const M=N.length===0?v:Oi(v,N,d);return Hi(N,M)?N:M})},[]),S=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:y,markLoaded:S,getIdes:()=>m.current}),[y,S]),u=s,b=a.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:o,toasts:c,setToasts:l,wsStatus:(u==null?void 0:u.wsStatus)??"connected",isConnected:(u==null?void 0:u.isConnected)??!0,connectionStates:(u==null?void 0:u.connectionStates)??{},connectionTransports:(u==null?void 0:u.connectionTransports)??{},showReconnected:(u==null?void 0:u.showReconnected)??!1,retryConnection:u==null?void 0:u.retryConnection,isP2PActive:(u==null?void 0:u.isP2PActive)??!1,p2pStates:(u==null?void 0:u.p2pStates)??{},userRole:u==null?void 0:u.userRole,userName:p,setUserName:x}),[r,h,o,c,u==null?void 0:u.wsStatus,u==null?void 0:u.isConnected,u==null?void 0:u.connectionStates,u==null?void 0:u.connectionTransports,u==null?void 0:u.showReconnected,u==null?void 0:u.retryConnection,u==null?void 0:u.isP2PActive,u==null?void 0:u.p2pStates,u==null?void 0:u.userRole,p]);return e.jsx(Va.Provider,{value:I,children:e.jsx(Fa.Provider,{value:b,children:t})})}function Qt(){return a.useContext(Fa)}function lr(){return a.useContext(Va)}function Ga(t){const{baseUrl:s,getToken:r,onUnauthorized:n}=t;function o(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const p=r==null?void 0:r(),x=o(l),m=l.startsWith("http")?new URL(x):new URL(x,typeof window<"u"?window.location.origin:"http://localhost");return p&&m.searchParams.set("token",p),!l.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(l,p={}){const x={"Content-Type":"application/json",...p.headers||{}},m=r==null?void 0:r();m&&(x.Authorization=`Bearer ${m}`);const h=o(l),y=new AbortController,S=setTimeout(()=>y.abort(),15e3);try{const I=await fetch(h,{...p,headers:x,signal:y.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const u=await I.json().catch(()=>({error:I.statusText}));throw new Error(u.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,p,x={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:p,payload:x})}),execTerminal:(l,p,x)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:p,name:x})}),sendAgentMessage:(l,p,x)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:p,message:x})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,p,x)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:p,action:x?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,p,x={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:p,payload:x})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const zi=Ga({baseUrl:"http://localhost:3847"}),Fi=a.createContext(zi);function Vi({client:t,children:s}){return e.jsx(Fi.Provider,{value:t,children:s})}const Gi={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},qa=a.createContext(Gi);function qi({value:t,children:s}){return e.jsx(qa.Provider,{value:t,children:s})}function St(){return a.useContext(qa)}const Ee={size:18};function Ya({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function pn({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ut({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),e.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),e.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),e.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function mn({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Yi({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Xi({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.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 Xa({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),e.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"}),e.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),e.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Ji({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.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"}),e.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),e.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),e.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),e.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function br({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.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 Ja({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),e.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Zi({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Kt({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.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 Nt({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function fn({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),e.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Qi({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function ps({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.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 xs({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function es({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.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"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function _s({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M12 22v-5"}),e.jsx("path",{d:"M9 8V2"}),e.jsx("path",{d:"M15 8V2"}),e.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Za({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Qa({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.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"}),e.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"}),e.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function eo({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function ec({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),e.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),e.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function gr({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"4 17 10 11 4 5"}),e.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function tc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function xn({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function sc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function to({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.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"}),e.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"}),e.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),e.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function rc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),e.jsx("path",{d:"M12 2v6"}),e.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function nc({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.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 ac({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),e.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 yr({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),e.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function oc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"5"}),e.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),e.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),e.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),e.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),e.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),e.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),e.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),e.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function ic({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function cc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function lc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function dc({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function uc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e.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 pc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.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"}),e.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"}),e.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 mc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),e.jsx("path",{d:"M13 2h9v9"}),e.jsx("path",{d:"M22 2L13 11"})]})}function fc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function xc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),e.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),e.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),e.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),e.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),e.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),e.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),e.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),e.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),e.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function hc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),e.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 zn({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),e.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Fn(t){return!!t&&typeof t=="object"&&"text"in t}function hn(t,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let o="";return typeof t=="string"?o=t:Array.isArray(t)?o=t.map(i=>typeof i=="string"?i:Fn(i)?String(i.text||""):"").join(r):Fn(t)?o=String(t.text||""):o=String(t||""),n?o.replace(/\s+/g," ").trim():o}function ts(t){return hn(t,{normalizeWhitespace:!0})}const Tr=new Map;function so(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function bc(t,s,r){return Number(t.receivedAt||r[ls(t,s)]||0)||0}function gc(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ls(t,s){const r=t,n=hn(t.content,{joiner:`
3
- `});return[t.id?`id:${t.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof t.index=="number"?`msgIndex:${t.index}`:"",t.role?`role:${t.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const Vn=5e3,yc=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(Ua,{remarkPlugins:[za],children:s.text}),e.jsx("span",{className:"action-time",children:so(s.timestamp)})]})},(t,s)=>t.log===s.log),vc=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var M,k,f;const p=(s.role||"").toLowerCase(),x=p==="user"||p==="human",m=s.kind||(p==="tool"?"tool":"standard"),h=hn(s.content,{joiner:`
4
- `});if(m==="thought"){const g=typeof((M=s.meta)==null?void 0:M.label)=="string"?s.meta.label:"Thought";return e.jsxs("div",{className:"self-start chat-msg-thought",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx(nc,{size:13}),e.jsx("span",{children:g})]}),e.jsx("div",{className:"chat-msg-body",children:h})]})}if(m==="tool")return e.jsxs("div",{className:"self-start chat-msg-tool",children:[e.jsx("span",{className:"tool-icon",children:"⏺"}),e.jsx("span",{className:"tool-text",children:h.split(`
5
- `)[0].slice(0,80)})]});if(m==="terminal"){const g=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",w=typeof((f=s.meta)==null?void 0:f.label)=="string"?s.meta.label:"Ran command";return e.jsxs("div",{className:"self-start chat-msg-terminal",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx("span",{children:g}),e.jsx("span",{children:w})]}),e.jsx("pre",{className:"chat-msg-body",children:h})]})}if(m==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:h.slice(0,100)});const y=s.meta,I=(typeof(y==null?void 0:y.renderMode)=="string"?y.renderMode.trim():"")==="preformatted",u=h,b=i&&!x&&!I&&u.length>Vn,v=b&&!c?u.slice(0,Vn):u,d=I,N=!d&&gc(v);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${x?"self-end":"self-start"}`,children:(u||x)&&e.jsxs("div",{className:`chat-bubble ${x?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${u?"mb-1.5":"mb-0"}`,children:[e.jsx("span",{className:"chat-sender",children:x?o||"You":s.senderName||n}),r!=null&&e.jsx("span",{className:"chat-time",children:so(r)})]}),u&&e.jsx("div",{className:"chat-markdown",children:d?e.jsx("pre",{className:"chat-preformatted",children:v}):N?e.jsx(Ua,{remarkPlugins:[za,Ti,_i],children:v}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),b&&e.jsx("button",{onClick:l,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(u.length/100)*100} chars) ↓`})]})})},(t,s)=>t.message===s.message&&t.receivedAt===s.receivedAt&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isTextExpanded===s.isTextExpanded),wc=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:p={},emptyState:x,onLoadMore:m,isLoadingMore:h,hasMoreHistory:y,hiddenLiveCount:S=0,loadError:I,scrollToBottomRequestNonce:u},b){var ae;const v=a.useRef(null),d=a.useRef(null),N=a.useRef(null),M=a.useRef(0),k=a.useRef(""),f=a.useRef(!1),g=a.useRef(null),w=a.useRef(!1),j=a.useRef(null),$=a.useRef(!1),[D,K]=a.useState(new Set),R=a.useRef(!1),z=a.useRef(!1),P=()=>{const W=v.current;return W?W.scrollHeight-W.scrollTop-W.clientHeight<200:!0},C=a.useCallback((W="auto")=>{const be=v.current;be&&be.scrollTo({top:be.scrollHeight,behavior:W})},[]),_=a.useCallback(()=>{const W=v.current;!W||!l||Tr.set(l,{top:W.scrollTop,fromBottom:Math.max(0,W.scrollHeight-W.scrollTop-W.clientHeight)})},[l]),G=a.useCallback(()=>{var ie;const W=v.current,be=(ie=window.getSelection)==null?void 0:ie.call(window);if(!W||!be||be.rangeCount===0||be.isCollapsed){$.current=!1;return}const X=be.anchorNode,J=be.focusNode;$.current=!!(X&&J&&W.contains(X)&&W.contains(J))},[]),T=a.useCallback((W="auto")=>{g.current!=null&&cancelAnimationFrame(g.current),g.current=requestAnimationFrame(()=>{g.current=null,C(W)})},[C]),E=s.length>0?`${s.length}:${(((ae=s[s.length-1])==null?void 0:ae.content)||"").length}`:"0:0";a.useEffect(()=>{const W=!f.current,be=k.current!==l;if(k.current=l,W||be){if(f.current=!0,R.current=!1,w.current=!0,!$.current){const J=l?Tr.get(l):null;J?requestAnimationFrame(()=>{const ie=v.current;if(!ie)return;const ne=Math.max(0,ie.scrollHeight-ie.clientHeight-J.fromBottom);ie.scrollTop=Number.isFinite(ne)?ne:J.top,z.current=!0}):T("auto")}M.current=s.length;return}s.length>M.current?!R.current&&!$.current&&T("auto"):P()&&!R.current&&!$.current&&T("auto"),M.current=s.length},[E,l,c,s.length,T]),a.useEffect(()=>{u&&(R.current=!1,w.current=!0,z.current=!0,j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{w.current=!1,j.current=null},180),$.current||T("auto"))},[T,u]),a.useEffect(()=>()=>{_(),g.current!=null&&cancelAnimationFrame(g.current),j.current!=null&&window.clearTimeout(j.current)},[_]),a.useEffect(()=>{const W=d.current;if(!W)return;const be=()=>{j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{w.current=!1,j.current=null},180)},X=new ResizeObserver(()=>{w.current&&($.current||(T("auto"),be()))});return X.observe(W),()=>{X.disconnect(),j.current!=null&&(window.clearTimeout(j.current),j.current=null)}},[T,l]),a.useImperativeHandle(b,()=>({scrollToBottom:(W="smooth")=>{C(W)}}),[C]),a.useEffect(()=>{const W=v.current;if(!W)return;let be;const X=()=>{clearTimeout(be),be=setTimeout(()=>{R.current=!P(),_()},50)};return W.addEventListener("scroll",X,{passive:!0}),()=>{W.removeEventListener("scroll",X),clearTimeout(be)}},[_]),a.useEffect(()=>(document.addEventListener("selectionchange",G),()=>document.removeEventListener("selectionchange",G)),[G]);const H=a.useRef(0),se=a.useRef(!1);a.useEffect(()=>{const W=v.current;if(!W||!se.current||H.current===0)return;const be=W.scrollHeight-H.current;be>0&&(W.scrollTop=be),_(),H.current=0,se.current=!1},[s.length,_]),a.useEffect(()=>{if(z.current||!l)return;const W=Tr.get(l),be=v.current;if(!W||!be)return;const X=Math.max(0,be.scrollHeight-be.clientHeight-W.fromBottom);be.scrollTop=Number.isFinite(X)?X:W.top,z.current=!0},[l,s.length]);const Y=()=>{const W=v.current;W&&(H.current=W.scrollHeight),se.current=!0,m==null||m()},oe=a.useMemo(()=>{const W=s.map((ie,ne)=>({type:"message",data:ie,index:ne,ts:bc(ie,ne,p)}));if(!r||r.length===0)return W;const be=[...r].sort((ie,ne)=>ie.timestamp-ne.timestamp).map((ie,ne)=>({type:"action",data:ie,index:ne,ts:ie.timestamp})),X=[];let J=0;for(const ie of W){for(;J<be.length&&ie.ts>0&&be[J].ts<ie.ts;)X.push(be[J++]);X.push(ie)}for(;J<be.length;)X.push(be[J++]);return X},[s,r,p]),je=S>0||!!y,V=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return e.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:d,className:"chat-container-content",children:[h&&e.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),je&&!h&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:Y,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${I&&S===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:V})}),oe.length===0&&!je&&(x||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(W=>{if(W.type==="action"){const ue=W.data;return e.jsx(yc,{log:ue},`action-${W.index}`)}const be=W.data,X=W.index,J=ls(be,X),ie=be.receivedAt||p[J],ne=`${l}-${J}`,he=D.has(ne);return e.jsx(vc,{message:be,receivedAt:ie,agentName:n,userName:o,isCliMode:i,isTextExpanded:he,onToggleTextExpanded:()=>K(ue=>{const fe=new Set(ue);return he?fe.delete(ne):fe.add(ne),fe})},`msg-${J}`)}),c&&e.jsx("div",{className:"self-start chat-typing-wrapper",children:e.jsxs("div",{className:"typing-indicator",children:[e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),e.jsx("div",{className:"min-h-10",ref:N})]})})}),jc=a.memo(wc,(t,s)=>t.messages===s.messages&&t.actionLogs===s.actionLogs&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isWorking===s.isWorking&&t.contextKey===s.contextKey&&t.receivedAtMap===s.receivedAtMap&&t.emptyState===s.emptyState&&t.onLoadMore===s.onLoadMore&&t.isLoadingMore===s.isLoadingMore&&t.hasMoreHistory===s.hasMoreHistory&&t.hiddenLiveCount===s.hiddenLiveCount&&t.loadError===s.loadError&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),kc="modulepreload",Nc=function(t){return"/"+t},Gn={},Sc=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(p=>{if(p=Nc(p),p in Gn)return;Gn[p]=!0;const x=p.endsWith(".css"),m=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const h=document.createElement("link");if(h.rel=x?"stylesheet":kc,x||(h.as="script"),h.crossOrigin="",h.href=p,l&&h.setAttribute("nonce",l),document.head.appendChild(h),x)return new Promise((y,S)=>{h.addEventListener("load",y),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${p}`)))})}))}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 qn=!1;const ro=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,l]=a.useState(null),p=a.useRef([]),x=a.useRef(!1),m=a.useRef(!1),h=a.useRef(!1),y=()=>{const S=i.current;if(S){x.current&&(S.clear(),x.current=!1);for(const I of p.current)S.write(I);p.current=[],m.current&&(S.fit(),m.current=!1),h.current&&(S.bumpResize(),h.current=!1)}};return a.useImperativeHandle(o,()=>({write:S=>{i.current?i.current.write(S):p.current.push(S)},clear:()=>{i.current?i.current.clear():(p.current=[],x.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(p.current=[],x.current=!0)},resize:(S,I)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(S,I)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():h.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const S=requestAnimationFrame(()=>{y()});return()=>cancelAnimationFrame(S)},[c]),a.useEffect(()=>{let S=!1;return Sc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(I=>{qn||(qn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||l(()=>I.GhosttyTerminalView)}).catch(I=>{console.error("[CliTerminal] failed to load terminal renderer",I)}),()=>{S=!0}},[]),c?e.jsx(c,{ref:i,onInput:t,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):e.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});ro.displayName="CliTerminal";function Hs({label:t,value:s,sub:r,icon:n}){return e.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:"text-base flex items-center",children:n}),e.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:t})]}),e.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Yn({value:t,max:s,label:r,color:n="#8b5cf6",detail:o,compact:i=!1}){const c=s>0?Math.min(Math.round(t/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex justify-between mb-0.5",children:[e.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),e.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),e.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex justify-between mb-1.5",children:[e.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),e.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),e.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),o&&e.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function Cc({cursorPos:t,viewportRef:s,imgRef:r}){var d;if(!t||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(d=s.current)==null?void 0:d.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,l=n.naturalHeight||o.height,p=c/l,x=o.width/o.height;let m,h,y,S;p>x?(m=o.width,h=o.width/p,y=0,S=(o.height-h)/2):(h=o.height,m=o.height*p,y=(o.width-m)/2,S=0);const I=o.left-i.left+y+m*t.nx,u=o.top-i.top+S+h*t.ny,b=Math.max(8,Math.min(i.width-8,I)),v=Math.max(8,Math.min(i.height-8,u));return e.jsxs("div",{style:{position:"absolute",left:b-8,top:v-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[e.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),e.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),e.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 Ic({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:p,isConnActive:x,zoom:m,isMobile:h,mobileFillZoom:y,onZoomOut:S,onZoomReset:I,onZoomIn:u,transportType:b,screenshotUsage:v,lastActionStatus:d}){return e.jsxs(e.Fragment,{children:[e.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:[e.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${t==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[e.jsx("span",{className:"text-sm",children:t==="mouse"?"🖱️":"👆"}),e.jsx("span",{className:`text-[10px] font-bold ${t==="mouse"?"text-blue-400":"text-slate-400"}`,children:t==="mouse"?"Mouse":"Touch"})]}),e.jsxs("div",{className:"relative",children:[e.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:e.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&e.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:e.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{p(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),e.jsx("div",{className:"relative",children:e.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:e.jsx("span",{className:"text-sm",children:"⚙️"})})}),e.jsx("div",{className:"w-px h-[18px] bg-white/10"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:x?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[e.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:x?"#22c55e":"#eab308",boxShadow:x?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),e.jsx("span",{className:"text-[8px] font-extrabold",style:{color:x?"#22c55e":"#eab308"},children:x?"Connected":"WS"})]}),m>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&e.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"}),b==="relay"&&e.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"}),v&&v.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),d&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:d})]})]}),o&&e.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:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(h?y:1)+.01?h?"FILL":"FIT":`${Math.round(m*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:N=>{N.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),I()},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:h?"FILL":"FIT"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),u()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Mc({waitingLabel:t,waitingHint:s,transportType:r}){return e.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[e.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:e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),e.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:t}),e.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&e.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Ac(){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 Xn(t){return t==null||typeof t=="number"||typeof t=="boolean"?t:typeof t=="string"?t.length>64?`${t.slice(0,61)}...`:t:Array.isArray(t)?`Array(${t.length})`:typeof t=="object"?"Object":typeof t}function Es(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!Ac())return;n.current+=1;const o=r.current;if(!o){console.debug(`[render-trace] ${t}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,Xn(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] ${t}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Xn(s[c])]))}),r.current=s})}function Tc({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:l,panYRef:p,setPanX:x,setPanY:m,setZoom:h,lastWheelTimeRef:y,onAction:S,setLastActionStatus:I,spawnRippleFromNormalized:u,clampPan:b,isMobile:v,mobileFillZoom:d}){const[N,M]=a.useState(null),k=a.useRef(null),f=a.useRef(null),g=a.useRef(null),w=a.useRef(!1),j=a.useRef(null),$=a.useRef(0),D=a.useRef(null),K=a.useRef(1),R=a.useRef({x:0,y:0}),z=a.useRef(!1),P=a.useRef(n),C=a.useRef(S),_=30,G=550,T=18,E=60,H=400,se=12,Y=()=>{if(k.current)return;const V={nx:.5,ny:.5};k.current=V,M(V)};return a.useEffect(()=>{P.current=n,n==="mouse"&&Y()},[n]),a.useEffect(()=>{C.current=S},[S]),a.useEffect(()=>{const V=t.current;if(!V)return;const ae=ne=>{if(!r.current)return null;const he=r.current.getBoundingClientRect();return!he.width||!he.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-he.left)/he.width)),ny:Math.max(0,Math.min(1,(ne.clientY-he.top)/he.height))}},W=(ne,he)=>{if(!r.current)return{dnx:0,dny:0};const ue=r.current,fe=ue.getBoundingClientRect(),te=ue.naturalWidth||fe.width,pe=ue.naturalHeight||fe.height,de=te/pe,ye=fe.width/fe.height;let we,L;return de>ye?(we=fe.width,L=fe.width/de):(L=fe.height,we=fe.height*de),{dnx:ne/we,dny:he/L}},be=(ne,he,ue)=>{if(ue<=1.05)return;const fe=-(ne-.5)*100,te=-(he-.5)*100,pe=b(fe,te,ue);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-p.current)>.1)&&(x(pe.x),m(pe.y),l.current=pe.x,p.current=pe.y)},X=ne=>{const he=s.current;if(he&&ne.target instanceof Node&&he.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const ue=ne.touches[0];f.current={x:ue.clientX,y:ue.clientY,time:Date.now()},g.current={x:ue.clientX,y:ue.clientY},z.current||(w.current=!1),j.current=setTimeout(()=>{if(!w.current&&!z.current)if(w.current=!0,P.current==="mouse"){const fe=k.current||{nx:.5,ny:.5};I("Right Click"),u(fe.nx,fe.ny,"right"),C.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=ae(ue);fe&&(I("Right Click"),u(fe.nx,fe.ny,"right"),C.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){j.current&&clearTimeout(j.current),w.current=!0,z.current=!0;const ue=ne.touches[1].clientX-ne.touches[0].clientX,fe=ne.touches[1].clientY-ne.touches[0].clientY;D.current=Math.sqrt(ue*ue+fe*fe),K.current=c.current,R.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},J=ne=>{const he=s.current;if(he&&ne.target instanceof Node&&he.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&g.current){const ue=ne.touches[0],fe=ue.clientX-g.current.x,te=ue.clientY-g.current.y;if(!w.current&&f.current){const pe=ue.clientX-f.current.x,de=ue.clientY-f.current.y;Math.sqrt(pe*pe+de*de)>8&&(w.current=!0,j.current&&clearTimeout(j.current))}if(w.current)if(P.current==="mouse"){const pe=W(fe,te),de=k.current||{nx:.5,ny:.5},ye=Math.max(0,Math.min(1,de.nx+pe.dnx)),we=Math.max(0,Math.min(1,de.ny+pe.dny));k.current={nx:ye,ny:we},M({nx:ye,ny:we}),I(`Cursor: ${Math.round(ye*100)}%, ${Math.round(we*100)}%`),be(ye,we,c.current);const L=Date.now();L-y.current>=30&&(y.current=L,C.current("input_mouseMoved",{nx:ye,ny:we}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const de=pe.clientWidth,ye=pe.clientHeight,we=l.current+fe/de*100,L=p.current+te/ye*100,ge=b(we,L,c.current);x(ge.x),m(ge.y),l.current=ge.x,p.current=ge.y}}else{const pe=ae(ue);if(pe){const de=Date.now();de-y.current>=40&&(y.current=de,I("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-te*2.5)}).catch(()=>{}))}}g.current={x:ue.clientX,y:ue.clientY};return}if(ne.touches.length===2&&D.current!==null){const ue=ne.touches[1].clientX-ne.touches[0].clientX,fe=ne.touches[1].clientY-ne.touches[0].clientY,pe=Math.sqrt(ue*ue+fe*fe)/D.current,de=(ne.touches[0].clientX+ne.touches[1].clientX)/2,ye=(ne.touches[0].clientY+ne.touches[1].clientY)/2,we=de-R.current.x,L=ye-R.current.y,ge=Math.abs(pe-1)>.03;if(P.current==="mouse"){if(ge){const F=Math.max(i,Math.min(5,K.current*pe));h(F),c.current=F}else if(Math.abs(we)>2||Math.abs(L)>2){const F=k.current||{nx:.5,ny:.5},me=Date.now();me-y.current>=30&&(y.current=me,I("Scroll"),C.current("input_wheel",{nx:F.nx,ny:F.ny,deltaX:Math.round(-we*3),deltaY:Math.round(-L*3)}).catch(()=>{}))}}else{const F=Math.max(i,Math.min(5,K.current*pe));h(F),c.current=F;const me=s.current;if(me&&F>1){const Ce=me.clientWidth,xe=me.clientHeight,Le=l.current+we/Ce*100,Be=p.current+L/xe*100,Fe=b(Le,Be,F);x(Fe.x),m(Fe.y),l.current=Fe.x,p.current=Fe.y}}R.current={x:de,y:ye}}},ie=ne=>{var he;if(j.current&&clearTimeout(j.current),D.current=null,ne.touches.length===1&&z.current){const ue=ne.touches[0];f.current={x:ue.clientX,y:ue.clientY,time:Date.now()},g.current={x:ue.clientX,y:ue.clientY},w.current=!0;return}if(ne.touches.length===0){if(z.current){z.current=!1,w.current=!1;return}if(ne.changedTouches.length===1){const ue=ne.changedTouches[0],fe=Date.now(),te=fe-(((he=f.current)==null?void 0:he.time)||0),pe=f.current?ue.clientX-f.current.x:0,de=f.current?ue.clientY-f.current.y:0,ye=Math.sqrt(pe*pe+de*de);if(P.current==="mouse"){if(te<_||te>G||ye>T){w.current=!1;return}const we=k.current||ae(ue);we&&(I(`Click: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),u(we.nx,we.ny,"left"),C.current("input_click",{...we}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(te<E||te>H||ye>se){w.current=!1;return}const we=ae(ue);if(!we)return;fe-$.current<300?(I("Double tap"),u(we.nx,we.ny,"double"),C.current("input_click",{...we,clickCount:2}).catch(()=>{}),$.current=0):(I(`Tap: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),u(we.nx,we.ny,"left"),C.current("input_click",{...we}).catch(()=>{}),$.current=fe)}}w.current=!1}};return V.addEventListener("touchstart",X,{passive:!1}),V.addEventListener("touchmove",J,{passive:!1}),V.addEventListener("touchend",ie,{passive:!1}),()=>{V.removeEventListener("touchstart",X),V.removeEventListener("touchmove",J),V.removeEventListener("touchend",ie),j.current&&clearTimeout(j.current)}},[t,s,r,i,c,l,p,x,m,h,y,I,u,b]),{cursorPos:N,cursorPosRef:k,handleToggleInputMode:()=>{o(V=>{const ae=V==="touch"?"mouse":"touch";return ae==="mouse"&&Y(),ae})},handleZoomReset:()=>{const V=v?d:1;h(V),c.current=V,x(0),m(0),l.current=0,p.current=0}}}function no({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),l=a.useRef(null),p=a.useRef(null),[x,m]=a.useState(null),[h,y]=a.useState(""),[,S]=a.useState(!1),[I,u]=a.useState([]),b=a.useRef(0),[v,d]=a.useState(!1),[N,M]=a.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[f,g]=a.useState(k?"mouse":"touch"),[w,j]=a.useState(1),$=a.useRef(!1),[D,K]=a.useState(1),[R,z]=a.useState(0),[P,C]=a.useState(0);Es("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:f,zoom:D,panX:R,panY:P,isMenuOpen:v,isImeOpen:N});const _=a.useRef(0),G=a.useRef(D),T=a.useRef(R),E=a.useRef(P);a.useEffect(()=>{G.current=D},[D]),a.useEffect(()=>{T.current=R},[R]),a.useEffect(()=>{E.current=P},[P]),a.useEffect(()=>{var te;(te=c.current)==null||te.focus()},[]);const H=r==="connected",se=n,Y=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",oe=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!k||$.current||!se)return;const te=p.current,pe=l.current;if(!te||!pe)return;const de=()=>{const ye=pe.clientWidth,we=pe.clientHeight,L=te.naturalWidth,ge=te.naturalHeight;if(!L||!ge||!ye||!we)return;const F=Math.min(ye/L,we/ge),Ce=Math.max(ye/L,we/ge)/F;Ce>1.01&&(j(Ce),K(Ce),G.current=Ce),$.current=!0};te.complete&&te.naturalWidth?de():te.addEventListener("load",de,{once:!0})},[se,k]);const je=.5;a.useEffect(()=>{D<=je&&(z(0),C(0))},[D,je]);const V=(te,pe,de)=>{if(de<=je)return{x:0,y:0};const ye=(de-1)/(2*de)*100,we=(de-1)/(2*de)*100;return{x:Math.max(-ye,Math.min(ye,te)),y:Math.max(-we,Math.min(we,pe))}},ae=(te,pe)=>{if(!p.current)return null;const de=p.current.getBoundingClientRect();return!de.width||!de.height?null:{nx:Math.max(0,Math.min(1,(te-de.left)/de.width)),ny:Math.max(0,Math.min(1,(pe-de.top)/de.height))}},W=(te,pe,de)=>{const ye=l.current;if(!ye)return;const we=ye.getBoundingClientRect(),L=++b.current;u(ge=>[...ge,{id:L,x:te-we.left,y:pe-we.top,type:de}]),setTimeout(()=>u(ge=>ge.filter(F=>F.id!==L)),600)},be=(te,pe,de)=>{const ye=p.current,we=l.current;if(!ye||!we)return;const L=ye.getBoundingClientRect(),ge=we.getBoundingClientRect(),F=ye.naturalWidth||L.width,me=ye.naturalHeight||L.height,Ce=F/me,xe=L.width/L.height;let Le,Be,Fe,st;Ce>xe?(Le=L.width,Be=L.width/Ce,Fe=0,st=(L.height-Be)/2):(Be=L.height,Le=L.height*Ce,Fe=(L.width-Le)/2,st=0);const ze=L.left-ge.left+Fe+Le*te,dt=L.top-ge.top+st+Be*pe,gt=++b.current;u(Ge=>[...Ge,{id:gt,x:ze,y:dt,type:de}]),setTimeout(()=>u(Ge=>Ge.filter(at=>at.id!==gt)),600)},X=async te=>{var de;const pe=ae(te.clientX,te.clientY);if(pe){m(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),W(te.clientX,te.clientY,"left"),(de=c.current)==null||de.focus();try{const ye=await t("input_click",{nx:pe.nx,ny:pe.ny});ye!=null&&ye.success||s(`❌ Click failed: ${ye==null?void 0:ye.error}`)}catch(ye){s(`❌ Click error: ${ye.message||ye}`)}}},J=async(te,pe,de,ye=0)=>{try{await t("input_key",{type:de?"char":"keyDown",key:te,code:pe,text:de?te:void 0,unmodifiedText:de?te:void 0,modifiers:ye})}catch(we){s(`❌ Key error: ${we.message||we}`)}},ie=async te=>{if(te.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(te.key)&&te.preventDefault();let de=0;te.altKey&&(de|=1),te.ctrlKey&&(de|=2),te.metaKey&&(de|=4),te.shiftKey&&(de|=8),m(`Key: ${te.key}`),await J(te.key,te.code,te.key.length===1,de)},ne=async te=>{if(te.key==="Enter"){if(te.nativeEvent.isComposing)return;if(h){const pe=h;y(""),m(`IME Sent: ${pe}`);try{const de=await t("input_type",{text:pe});de!=null&&de.success||s(`❌ IME error: ${de==null?void 0:de.error}`)}catch(de){s(`❌ IME error: ${de.message}`)}}else m("Key: Enter"),await J("Enter","Enter",!1)}};a.useEffect(()=>{const te=c.current;if(!te)return;const pe=de=>{var ye;if((ye=p.current)!=null&&ye.contains(de.target)){de.preventDefault();const we=Date.now();if(we-_.current<40)return;_.current=we;const L=ae(de.clientX,de.clientY);if(!L)return;m(`Scroll: ${Math.round(de.deltaY)}`),t("input_wheel",{nx:L.nx,ny:L.ny,deltaX:Math.round(de.deltaX),deltaY:Math.round(de.deltaY)}).catch(()=>{})}};return te.addEventListener("wheel",pe,{passive:!1}),()=>te.removeEventListener("wheel",pe)},[t]);const{cursorPos:he,handleToggleInputMode:ue,handleZoomReset:fe}=Tc({containerRef:c,viewportRef:l,imgRef:p,inputMode:f,setInputMode:g,minZoom:je,zoomRef:G,panXRef:T,panYRef:E,setPanX:z,setPanY:C,setZoom:K,lastWheelTimeRef:_,onAction:t,setLastActionStatus:m,spawnRippleFromNormalized:be,clampPan:V,isMobile:k,mobileFillZoom:w});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ie,onContextMenu:te=>te.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[e.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[se?e.jsx("img",{ref:p,src:se,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${D}) translate(${R}%, ${P}%)`,transformOrigin:"center center",cursor:f==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:X,onContextMenu:te=>te.preventDefault(),onDragStart:te=>te.preventDefault()}):e.jsx(Mc,{waitingLabel:Y,waitingHint:oe,transportType:i}),f==="mouse"&&se&&e.jsx(Cc,{cursorPos:he,viewportRef:l,imgRef:p}),I.map(te=>{const de={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[te.type];return e.jsxs("div",{style:{position:"absolute",left:te.x,top:te.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${de}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),e.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${de}, 0.9)`,boxShadow:`0 0 12px rgba(${de}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},te.id)})]}),e.jsx(Ic,{inputMode:f,onToggleInputMode:ue,isImeOpen:N,setIsImeOpen:M,isMenuOpen:v,setIsMenuOpen:d,imeText:h,setImeText:y,handleImeSubmit:ne,isConnActive:H,zoom:D,isMobile:k,mobileFillZoom:w,onZoomOut:()=>K(te=>Math.max(.5,te-.25)),onZoomReset:fe,onZoomIn:()=>K(te=>Math.min(5,te+.25)),transportType:i,screenshotUsage:o,lastActionStatus:x}),e.jsx("style",{children:`
6
- @keyframes slideUp {
7
- from { opacity: 0; transform: translateY(6px); }
8
- to { opacity: 1; transform: translateY(0); }
9
- }
10
- @keyframes slideUpSidebar {
11
- from { opacity: 0; transform: translateY(6px); }
12
- to { opacity: 1; transform: translateY(0); }
13
- }
14
- @keyframes click-ripple-ring {
15
- 0% { transform: scale(0.3); opacity: 1; }
16
- 100% { transform: scale(2.2); opacity: 0; }
17
- }
18
- @keyframes click-ripple-dot {
19
- 0% { transform: scale(1); opacity: 0.9; }
20
- 50% { transform: scale(1.8); opacity: 0.6; }
21
- 100% { transform: scale(0.5); opacity: 0; }
22
- }
23
- @keyframes remote-float {
24
- 0% { transform: translateY(0px); }
25
- 50% { transform: translateY(-7px); }
26
- 100% { transform: translateY(0px); }
27
- }
28
- `})]})}function bn(t,s={}){if(!t)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-t,c=Math.floor(i/1e3);if(c<o)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const p=Math.floor(l/60);if(p<24)return`${p}h${r}`;const x=Math.floor(p/24);return x<7?`${x}d${r}`:new Date(t).toLocaleDateString()}const ao=t=>bn(t);function _c(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function hs(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",o=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function $s(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,..._c(o)})};for(const n of t)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Ps(t,s){if(t.sessionId){const r=s.get(t.sessionId);if(r)return r}return{sessionId:t.sessionId||t.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Ls(t,s,r){const n=Ps(t,s),o=hs(t),i=o.isReconnecting,c=o.isConnecting,l=o.isGenerating,p=o.isWaiting,x=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||p,m=n.inboxBucket==="working"||l,h=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:h,requiresAction:x,isWorking:m,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:p,inboxBucket:x?"needs_attention":m?"working":h?"task_complete":"idle"}}function Pc(t,s,r){return Ls(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Lc(t,s,r){return Ps(t,r||new Map).surfaceHidden}function oo({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!hs(t).isWaiting||!t.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 e.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:[t.modalMessage&&e.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[e.jsx(es,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((l,p)=>{const x=c(l).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(x),h=/^(reject|deny|delete|remove|abort)/.test(x),y=r===l,S=r!==null;return e.jsx("button",{onClick:()=>i(l),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!y?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?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:y?"⏳ ...":c(l)},p)})})]})]})}const It=new Map;function Jn({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:l,acpModes:p}){var je;const{sendCommand:x}=St(),m=!!(l||p),h=`${t}:${s||n}`,y=It.get(h),[S,I]=a.useState(!1),[u,b]=a.useState(!1),[v,d]=a.useState((y==null?void 0:y.models)||[]),[N,M]=a.useState((y==null?void 0:y.modes)||[]),k=V=>V?typeof V=="string"?V:typeof V=="object"?V.name||V.id||JSON.stringify(V):String(V):"",[f,g]=a.useState(k(i)),[w,j]=a.useState(k(c)),[$,D]=a.useState(!1),[K,R]=a.useState(!1),z=a.useRef(0),P=V=>V.map(ae=>typeof ae=="string"?ae:(ae==null?void 0:ae.name)||(ae==null?void 0:ae.id)||String(ae));a.useEffect(()=>{if(l){const V=l.find(ae=>ae.category==="model");if(V){const ae=P(V.options.map(be=>be.value));d(ae),V.currentValue&&g(k(V.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,models:ae})}}if(p&&p.length>0){const V=P(p.map(W=>W.id));M(V);const ae=It.get(h)||{models:[],modes:[]};It.set(h,{...ae,modes:V})}else if(l){const V=l.find(ae=>ae.category!=="model");if(V){const ae=P(V.options.map(be=>be.value));M(ae),V.currentValue&&j(k(V.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,modes:ae})}}},[l,p,h]),a.useEffect(()=>{I(!1),b(!1),g(k(i)),j(k(c));const V=It.get(h);V?(d(V.models),M(V.modes)):(d([]),M([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>z.current&&g(k(i))},[i]),a.useEffect(()=>{c&&Date.now()>z.current&&j(k(c))},[c]);const C=a.useCallback(async(V,ae={})=>{const W={...ae,...s&&{targetSessionId:s}};return await x(t,V,W)},[t,s,x]),_=async()=>{var V,ae;if(v.length>0){I(!S);return}if(m){I(!0);return}D(!0);try{const W=await C("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.models)||((V=W==null?void 0:W.result)==null?void 0:V.models)||[],X=P(be);d(X),W!=null&&W.current&&g(k(W.current)),(ae=W==null?void 0:W.result)!=null&&ae.current&&g(k(W.result.current));const J=It.get(h)||{models:[],modes:[]};It.set(h,{...J,models:X}),I(!0)}catch{}finally{D(!1)}},G=async()=>{var V,ae;if(N.length>0){b(!u);return}if(m){b(!0);return}R(!0);try{const W=await C("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.modes)||((V=W==null?void 0:W.result)==null?void 0:V.modes)||[],X=P(be);M(X),W!=null&&W.current&&j(k(W.current)),(ae=W==null?void 0:W.result)!=null&&ae.current&&j(k(W.result.current));const J=It.get(h)||{models:[],modes:[]};It.set(h,{...J,modes:X}),b(!0)}catch{}finally{R(!1)}},T=async V=>{I(!1);const ae=f;g(V),z.current=Date.now()+5e3;try{const W=m?await C("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:V}):await C("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:V});if((W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change model")}catch(W){console.warn("Model change failed",W),g(ae),z.current=0}},E=m&&!(p&&p.length>0)&&(l==null?void 0:l.some(V=>V.category!=="model")),H=E?(je=l==null?void 0:l.find(V=>V.category!=="model"))==null?void 0:je.configId:void 0,se=async V=>{b(!1);const ae=w;j(V),z.current=Date.now()+5e3;try{let W;if(m&&E&&H?W=await C("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:H,value:V}):m?W=await C("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:V}):W=await C("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:V}),(W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change mode")}catch(W){console.warn("Mode change failed",W),j(ae),z.current=0}},oe={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"}[n]||"#94a3b8";return e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-[var(--surface-primary)]",children:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:oe},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),e.jsxs("div",{className:"relative",children:[e.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:S?`${oe}55`:"transparent",border:"1px solid",color:f?"var(--text-primary)":"var(--text-muted)"},onClick:_,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),$?"...":f||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),S&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(!1)}),e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:"SELECT MODEL"}),v.map(V=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:V===f?`${oe}18`:"transparent",color:V===f?oe:"var(--text-secondary)",fontWeight:V===f?600:400,borderLeft:V===f?`2px solid ${oe}`:"2px solid transparent"},onMouseEnter:ae=>{ae.currentTarget.style.background=`${oe}12`},onMouseLeave:ae=>{ae.currentTarget.style.background=V===f?`${oe}18`:"transparent"},onClick:()=>T(V),children:V},V))]})]})]}),e.jsxs("div",{className:"relative",children:[e.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:u?`${oe}55`:"transparent",border:"1px solid",color:w?"var(--text-primary)":"var(--text-muted)"},onClick:G,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:E?"🧠":"⚡"}),K?"...":w||(E?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),u&&N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>b(!1)}),e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:E?"SELECT THINKING LEVEL":"SELECT MODE"}),N.map(V=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:V===w?`${oe}18`:"transparent",color:V===w?oe:"var(--text-secondary)",fontWeight:V===w?600:400,borderLeft:V===w?`2px solid ${oe}`:"2px solid transparent"},onMouseEnter:ae=>{ae.currentTarget.style.background=`${oe}12`},onMouseLeave:ae=>{ae.currentTarget.style.background=V===w?`${oe}18`:"transparent"},onClick:()=>se(V),children:V},V))]})]})]})]})}const Zn=new Map,Rc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Dc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:l,serverMode:p,acpConfigOptions:x,acpModes:m}){const{sendCommand:h}=St(),y=`${t}:${s||n}`,S=Rc[n]||"#94a3b8",[I,u]=a.useState({}),b=a.useRef(0),v={};for(const _ of i||[])_.defaultValue!==void 0&&(v[_.id]=_.defaultValue);const d={...v,...l?{model:l}:{},...p?{mode:p}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&u({})},[c]);const[N,M]=a.useState(Zn.get(y)||{}),[k,f]=a.useState(null),[g,w]=a.useState(null),j=a.useCallback(async(_,G={})=>{const T={...G,...s&&{targetSessionId:s}};return await h(t,_,T)},[t,s,h]),$=a.useCallback(async(_,G={},T)=>{const E=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const H=await j("invoke_provider_script",{...E,scriptName:_,...G});return(H==null?void 0:H.success)===!1&&T?await j(T,{...E,...G}):H}catch(H){if(!T)throw H;return await j(T,{...E,...G})}},[j,n,r]);if(!i||i.length===0)return e.jsx(Jn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:l,serverMode:p,acpConfigOptions:x,acpModes:m});const D=i.filter(_=>_.placement==="bar").sort((_,G)=>(_.order??50)-(G.order??50));if(D.length===0)return e.jsx(Jn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:l,serverMode:p,acpConfigOptions:x,acpModes:m});const K=async _=>{var T,E,H;if(k===_.id){f(null);return}if((((T=_.options)==null?void 0:T.map(se=>se.value))||N[_.id]||[]).length>0){f(_.id);return}if(_.dynamic&&_.listScript){w(_.id);try{const se=Us(_.listScript),Y=await $(_.listScript,{},se),je=((Y==null?void 0:Y.models)||(Y==null?void 0:Y.modes)||((E=Y==null?void 0:Y.result)==null?void 0:E.models)||((H=Y==null?void 0:Y.result)==null?void 0:H.modes)||(Y==null?void 0:Y.options)||[]).map(V=>typeof V=="string"?V:(V==null?void 0:V.name)||(V==null?void 0:V.id)||(V==null?void 0:V.value)||String(V));M(V=>{const ae={...V,[_.id]:je};return Zn.set(y,ae),ae}),f(_.id)}catch{}finally{w(null)}}},R=async(_,G)=>{f(null),u(T=>({...T,[_.id]:G})),b.current=Date.now()+5e3;try{if(!_.setScript)return;await $(_.setScript,{model:_.id==="model"?G:void 0,mode:_.id==="mode"?G:void 0,value:G},Us(_.setScript))}catch{}},z=async _=>{var Y;const G=((Y=_.options)==null?void 0:Y.map(oe=>oe.value))||N[_.id]||[];if(G.length===0)return;const T=String(d[_.id]||""),H=(G.indexOf(T)+1)%G.length,se=G[H];if(typeof se=="string"){u(oe=>({...oe,[_.id]:se})),b.current=Date.now()+5e3;try{if(!_.setScript)return;await $(_.setScript,{value:se},Us(_.setScript))}catch{}}},P=async _=>{const T=!d[_.id];u(E=>({...E,[_.id]:T})),b.current=Date.now()+5e3;try{if(!_.setScript)return;await $(_.setScript,{value:T},Us(_.setScript))}catch{}},C=async _=>{if(_.invokeScript){if(_.confirmMessage){const G=[_.confirmTitle,_.confirmMessage,_.confirmLabel].filter(E=>typeof E=="string"&&E.trim().length>0);if(!window.confirm(G.join(`
29
-
30
- `)))return}try{await $(_.invokeScript)}catch{}}};return e.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:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:S},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),D.map(_=>{var se;const G=String(d[_.id]||""),T=k===_.id,E=g===_.id,H=((se=_.options)==null?void 0:se.map(Y=>Y.value))||N[_.id]||[];switch(_.type){case"select":return e.jsxs("div",{className:"relative",children:[e.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:T?`${S}55`:"transparent",border:"1px solid",color:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(_),children:[_.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),E?"...":G||_.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),T&&H.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>f(null)}),e.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:[e.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()}),H.map(Y=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:Y===G?`${S}18`:"transparent",color:Y===G?S:"var(--text-secondary)",fontWeight:Y===G?600:400,borderLeft:Y===G?`2px solid ${S}`:"2px solid transparent"},onMouseEnter:oe=>{oe.currentTarget.style.background=`${S}12`},onMouseLeave:oe=>{oe.currentTarget.style.background=Y===G?`${S}18`:"transparent"},onClick:()=>R(_,Y),children:Y},Y))]})]})]},_.id);case"cycle":return e.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:G?"var(--text-primary)":"var(--text-muted)"},onClick:()=>z(_),title:`Click to cycle: ${H.join(" → ")}`,children:[_.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),G||_.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},_.id);case"toggle":return e.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:G?`${S}44`:"transparent",background:G?`${S}14`:"var(--surface-tertiary)",color:G?S:"var(--text-muted)"},onClick:()=>P(_),children:[_.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.label]},_.id);case"action":return e.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:()=>C(_),children:[_.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.resultDisplay==="inline"&&G?`${_.label}: ${G}`:_.label]},_.id);case"display":return e.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:G?"var(--text-primary)":"var(--text-muted)"},children:[_.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),G?`${_.label}: ${G}`:_.label]},_.id);default:return null}})]})}function Us(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const Ec=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[l,p]=a.useState("");a.useEffect(()=>{p("")},[s]),a.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const x=()=>{const m=l.trim();!m||n||(p(""),o(m))};return e.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:e.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:l,onChange:m=>p(m.target.value),onPaste:m=>{const h=m.clipboardData.getData("text");h&&p(y=>y+h),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),x()}},onBlur:m=>{if(window.innerWidth<768){const h=m.relatedTarget;if((h==null?void 0:h.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))"}})}),e.jsx("button",{onClick:x,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:e.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:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var $c=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Bc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function xt(t,s){if(Bc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":$c.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 io(t){return xt(t)==="generating"}function Ze(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Kc(t){if(t<60)return`${Math.round(t)}s`;const s=Math.floor(t/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 _r(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function vr(t,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof t=="string"?t.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function Wc(t){if(t.length>16&&/^[a-f0-9]+$/i.test(t))return`Machine-${t.substring(0,8)}`;if(t.includes("_")){const s=t.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return t}function Oc(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Hc(t){return Wc(t.trim().replace(/\.local$/i,""))}function Uc(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function co(t,s={}){var o,i;const r=[t.hostname,(o=t.machine)==null?void 0:o.hostname,(i=t.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Oc(c));if(r&&r!=="Unknown")return Hc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function kt(t,s={}){return Uc(t)||co(t,s)}function Rs(t){return t.transport==="pty"}function ds(t){return t.transport==="acp"}function Qn(t,s){return Ze(t)}function ea(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Ze(r||"").trim().toLowerCase();return n===o||n===i||n===c}function zc(t){return xt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Fc(t){if(!Array.isArray(t)||t.length<=1)return t;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of t){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=xt(n.status);if(!i){s.set(o,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),p=r.indexOf(c||"idle");p>=0&&(l<0||p<l)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Vc(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Gc(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Vc(s.receivedAt)||0}function qc(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function en(t){return Math.max(qc(t),Gc(t.activeChat))}function Yc(t,s,r,n,o,i){const c=s-t;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:o.localeCompare(i)}function gn(t,s){return Yc(en(t),en(s),kt(t,{fallbackId:t.id}),kt(s,{fallbackId:s.id}),t.id,s.id)}const Xe=t=>t.transport==="pty",ms=(t,s)=>Xe(t)?t.mode||"terminal":"chat",lo=(t,s)=>Xe(t)&&ms(t)==="terminal",Ve=t=>t.transport==="acp";function Bt(t){return t.streamSource!=="agent-stream"}function zt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function uo(t){return t.machineName||""}function dr(t){return zt(t)}function jt(t){return t.agentType||""}function yn(t){return t.hostIdeType||""}function wr(t){return t.displayPrimary||t.agentName||"Agent"}function vn(t){return[t.displaySecondary,uo(t)].filter(Boolean)}function Bs(t){return t.agentName||Ze(jt(t))}function Xc(t){var s,r;if(!Bt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Ze(yn(t)||jt(t))}function wn(t){return Bt(t)?t.sessionId:t.nativeSessionId}function ta(t){return Bt(t)?"native":t.tabKey}function Jc(t){return t.sessionId}function Zc(t,s){if(s)return Bt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function Qc(t,s){const r=jt(t),n=Bt(t)?s!=null&&s.type?Ze(s.type):Ze(yn(t)||r):Bs(t);return{isNativeConversation:Bt(t),isCli:Xe(t),isAcp:Ve(t),isCliTerminal:lo(t),providerType:r,displayLabel:n,targetEntry:Zc(t,s)}}function po({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=fs(),c=zt(t),l=uo(t),p=t.transport==="cdp-page"||t.transport==="cdp-webview",x=t.streamSource==="agent-stream"&&!!t.agentName,m=!x&&(t.transport==="pty"||t.transport==="acp"),h=Bs(t),y=Xc(t),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const u=wn(t);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[p&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:y,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:y})]}):e.jsxs("span",{className:"conversation-meta-chip",title:y,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:y})]})),x&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(_s,{size:12}),e.jsx("span",{children:h})]}),m&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(_s,{size:12}),e.jsx("span",{children:h})]}),l&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:l,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:l})]}):e.jsxs("span",{className:"conversation-meta-chip",title:l,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:l})]}))]})}function sa(t,s){return`${t}:${s}`}function el(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function zs(t,s){el()&&console.debug(`[subscription-manager] ${t}`,s)}class tl{constructor(){nt(this,"active",new Map)}subscribe(s,r,n,o){var l;const i=sa(n.topic,n.key),c=this.active.get(i);if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const p={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,p),zs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),(l=s.sendData)==null||l.call(s,r,n)}return()=>{var m;const p=this.active.get(i);if(!p||(p.handlers.delete(o),p.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};zs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(m=s.sendData)==null||m.call(s,r,x)}}publish(s){const r=sa(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,n.handlers.forEach(o=>{o(s)}))}resubscribeAll(s){var r;zs("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);zs("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const Ot=new tl;function sl(t,s){const r=new Map;for(const n of t||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,currentModel:n.currentModel,currentPlan:n.currentPlan,currentAutoApprove:n.currentAutoApprove,controlValues:n.controlValues,providerControls:n.providerControls,acpConfigOptions:n.acpConfigOptions,acpModes:n.acpModes,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Fs(t,s){return{...t,parentId:t.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:t.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??t.providerType,workspace:t.workspace??(s==null?void 0:s.workspace)??null,capabilities:t.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:t.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:t.currentModel??(s==null?void 0:s.currentModel),currentPlan:t.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:t.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:t.controlValues??(s==null?void 0:s.controlValues),providerControls:t.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:t.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:t.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:t.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:t.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:t.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:t.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:t.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:t.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function rl(t){const s=[],r=new Map;for(const n of t)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 ur(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,l=c||t.timestamp||Date.now(),p=t.sessions||[],{topLevel:x,childrenByParent:m}=rl(p),h=sl(i,n),y=t.machine?{...(o==null?void 0:o.machine)||{},...t.machine}:o==null?void 0:o.machine,S=x.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),I=x.filter(b=>b.kind==="agent"&&b.transport==="pty"),u=x.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...t.version&&{version:t.version},...y&&{machine:y,platform:y.platform},...t.instanceId&&{instanceId:t.instanceId},...t.machineNickname!==void 0&&{machineNickname:t.machineNickname},...t.p2p&&{p2p:t.p2p},...t.workspaces&&{workspaces:t.workspaces},...t.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:t.defaultWorkspaceId},...t.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:t.defaultWorkspacePath},...t.terminalSizingMode!==void 0&&{terminalSizingMode:t.terminalSizingMode},...t.recentLaunches&&{recentLaunches:t.recentLaunches},...t.terminalBackend&&{terminalBackend:t.terminalBackend},...t.detectedIdes&&{detectedIdes:t.detectedIdes},...t.availableProviders&&{availableProviders:t.availableProviders},cdpConnected:S.some(b=>!!b.cdpConnected)});for(const b of S){const v=h.get(b.id),d=Fs(b,v),N=(m.get(b.id)||[]).map(M=>Fs(M,h.get(M.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:d.parentId,sessionKind:d.kind,transport:d.transport,sessionCapabilities:d.capabilities,type:d.providerType,status:d.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:d.workspace,terminals:0,childSessions:N,agents:N.map(M=>({id:M.id,name:M.providerName||M.providerType,type:M.providerType,status:M.status})),activeChat:d.activeChat,chats:[],cdpConnected:d.cdpConnected,...d.currentModel!==void 0&&{currentModel:d.currentModel},...d.currentPlan!==void 0&&{currentPlan:d.currentPlan},...d.currentAutoApprove!==void 0&&{currentAutoApprove:d.currentAutoApprove},...d.lastMessagePreview!==void 0&&{lastMessagePreview:d.lastMessagePreview},...d.lastMessageRole!==void 0&&{lastMessageRole:d.lastMessageRole},...d.lastMessageAt!==void 0&&{lastMessageAt:d.lastMessageAt},...d.lastMessageHash!==void 0&&{lastMessageHash:d.lastMessageHash},lastUpdated:d.lastUpdated,unread:d.unread,lastSeenAt:d.lastSeenAt,inboxBucket:d.inboxBucket,surfaceHidden:d.surfaceHidden,...d.controlValues!==void 0&&{controlValues:d.controlValues},...d.providerControls!==void 0&&{providerControls:d.providerControls},timestamp:l})}for(const b of I){const v=h.get(b.id),d=Fs(b,v);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:d.parentId,sessionKind:d.kind,transport:d.transport,sessionCapabilities:d.capabilities,type:d.providerType,agentType:d.providerType,status:d.status||"running",daemonId:n,instanceId:b.id,cliName:d.providerName||d.providerType,mode:d.mode||(v==null?void 0:v.mode)||"terminal",workspace:d.workspace||"",activeChat:d.activeChat,...d.resume!==void 0&&{resume:d.resume},...d.runtimeKey!==void 0&&{runtimeKey:d.runtimeKey},...d.runtimeDisplayName!==void 0&&{runtimeDisplayName:d.runtimeDisplayName},...d.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:d.runtimeWorkspaceLabel},...d.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:d.runtimeWriteOwner},...d.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:d.runtimeAttachedClients},...d.lastMessagePreview!==void 0&&{lastMessagePreview:d.lastMessagePreview},...d.lastMessageRole!==void 0&&{lastMessageRole:d.lastMessageRole},...d.lastMessageAt!==void 0&&{lastMessageAt:d.lastMessageAt},...d.lastMessageHash!==void 0&&{lastMessageHash:d.lastMessageHash},lastUpdated:d.lastUpdated,unread:d.unread,lastSeenAt:d.lastSeenAt,inboxBucket:d.inboxBucket,surfaceHidden:d.surfaceHidden,...d.controlValues!==void 0&&{controlValues:d.controlValues},...d.providerControls!==void 0&&{providerControls:d.providerControls},timestamp:l,_isCli:!0})}for(const b of u){const v=h.get(b.id),d=Fs(b,v);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:d.parentId,sessionKind:d.kind,transport:d.transport,sessionCapabilities:d.capabilities,type:d.providerType,agentType:d.providerType,status:d.status||"running",daemonId:n,instanceId:b.id,cliName:d.providerName||d.providerType,mode:"chat",workspace:d.workspace||"",activeChat:d.activeChat,...d.runtimeKey!==void 0&&{runtimeKey:d.runtimeKey},...d.runtimeDisplayName!==void 0&&{runtimeDisplayName:d.runtimeDisplayName},...d.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:d.runtimeWorkspaceLabel},...d.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:d.runtimeWriteOwner},...d.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:d.runtimeAttachedClients},...d.currentModel!==void 0&&{currentModel:d.currentModel},...d.currentPlan!==void 0&&{currentPlan:d.currentPlan},...d.lastMessagePreview!==void 0&&{lastMessagePreview:d.lastMessagePreview},...d.lastMessageRole!==void 0&&{lastMessageRole:d.lastMessageRole},...d.lastMessageAt!==void 0&&{lastMessageAt:d.lastMessageAt},...d.lastMessageHash!==void 0&&{lastMessageHash:d.lastMessageHash},lastUpdated:d.lastUpdated,unread:d.unread,lastSeenAt:d.lastSeenAt,inboxBucket:d.inboxBucket,surfaceHidden:d.surfaceHidden,...d.acpConfigOptions!==void 0&&{acpConfigOptions:d.acpConfigOptions},...d.acpModes!==void 0&&{acpModes:d.acpModes},...d.controlValues!==void 0&&{controlValues:d.controlValues},...d.providerControls!==void 0&&{providerControls:d.providerControls},timestamp:l,_isAcp:!0})}return r}const Pr=new Map,Lr=new Map,Rr=new Set,Ns=new Map,nl=1200;function al(t){if(!t||typeof t!="object")return null;const s=t,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 ra(t,s){const r=Ns.get(t);!r||r.size===0||(Ns.delete(t),r.forEach(n=>n(s)))}function ol(t,s){return new Promise(r=>{const n=Ns.get(t)||new Set;Ns.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Ns.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Ks(){const{sendCommand:t,sendData:s}=St(),{injectEntries:r,getIdes:n}=lr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=Lr.get(o)||0;if(!(i!=null&&i.force)&&Rr.has(o)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const p=Pr.get(o);if(p)return p;const x=(async()=>{if(s&&!Rr.has(o)&&(Rr.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const b=n(),v=b.find(N=>N.id===o),d=ur(u.status,{daemonId:o,existingDaemon:v,existingEntries:b,timestamp:u.timestamp});d.length>0&&r(d),Lr.set(o,Date.now()),ra(o,!0)}),!(i!=null&&i.force)&&await ol(o,nl)))return;const m=await t(o,"get_status_metadata"),h=al(m);if(!h)return;const y=n(),S=y.find(u=>u.id===o),I=ur(h,{daemonId:o,existingDaemon:S,existingEntries:y,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),Lr.set(o,Date.now()),ra(o,!0)})().finally(()=>{Pr.delete(o)});return Pr.set(o,x),x},[n,r,t,s])}function ss(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function mo(t,s){if(!t||!s)return!1;if(t===s||t.id&&s.id&&String(t.id)===String(s.id)||t._localId&&s._localId&&String(t._localId)===String(s._localId))return!0;const r=String(t.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=ts(t.content),i=ts(s.content);if(!o||o!==i)return!1;const c=ss(t),l=ss(s);return c&&l?Math.abs(c-l)<=15e3:!!t._localId!=!!s._localId}function na(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),ss(t)&&(s+=1),s}function il(t,s){const r=na(t),n=na(s);return n!==r?n>r?s:t:ts(s.content).length>=ts(t.content).length?s:t}function Ss(t){const s=[];for(const r of t){const n=s.findIndex(o=>mo(o,r));if(n>=0){s.splice(n,1,il(s[n],r));continue}s.push(r)}return s}function aa(t){return[...t].sort((s,r)=>{const n=ss(s),o=ss(r);return n&&o&&n!==o?n-o:0})}function oa(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${ts(t==null?void 0:t.content).slice(0,100)}`}function ia(t,s){const r=t.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>mo(i,n));return o>=0?(r.splice(o,1),!1):!0})}function cl(t,s){const r=new Set(s.map(n=>oa(n)));return t.filter(n=>!r.has(oa(n)))}function ll(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function dl(t){let s=2166136261;for(const r of t){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 ca(t,s){const r=t[t.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",t.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function fo(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return dl([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function ul(t){return{knownMessageCount:t.length,lastMessageSignature:fo(t[t.length-1])}}function pl(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return Ss([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return Ss([...t.slice(0,n),...r])}case"full":default:return r}}const ml=60,la=60;function tn({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:p=!1,scrollToBottomRequestNonce:x,isInputActive:m=!0}){var ae,W,be,X;const h=a.useRef(new Map),y=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:I,sendData:u}=St(),b=Ks();Es("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const v=et.useMemo(()=>hs(t),[t.status,t.connectionState]),d=a.useRef(new Map),N=a.useCallback(J=>(d.current.has(J)||d.current.set(J,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:ml}),d.current.get(J)),[]),M=a.useCallback((J,ie)=>{const ne=N(J);d.current.set(J,{...ne,...ie}),k(he=>he+1)},[N]),[,k]=a.useState(0),f=t.tabKey,g=N(f),w=g.messages,j=g.hasMore,$=g.error,D=y.current.get(f),K=t.messages.filter(J=>!!(J!=null&&J._localId)),R=D?Ss([...D,...K]):t.messages,z=Math.max(0,R.length-g.visibleLiveCount),P=wr(t),C=dr(t),_=t.sessionId||"",G=t.providerSessionId||_,T=a.useMemo(()=>Qc(t,s),[t,s]),[E,H]=a.useState(!1);a.useEffect(()=>{const J=T.targetEntry;C&&(!J||J.providerControls===void 0||J.controlValues===void 0||T.isAcp&&(J.acpConfigOptions===void 0||J.acpModes===void 0))&&b(C,{minFreshMs:3e4}).catch(()=>{})},[C,T.isAcp,(ae=T.targetEntry)==null?void 0:ae.providerControls,(W=T.targetEntry)==null?void 0:W.controlValues,(be=T.targetEntry)==null?void 0:be.acpConfigOptions,(X=T.targetEntry)==null?void 0:X.acpModes,b]),a.useEffect(()=>{if(!C||!_||!u)return;const J=y.current.get(f)||[],ie=S.current.get(f),ne=ie&&ie.knownMessageCount?ie:ul(J),he=`daemon:${C}:session:${_}`;return Ot.subscribe({sendData:u},C,{type:"subscribe",topic:"session.chat_tail",key:he,params:{targetSessionId:_,historySessionId:G,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:la}}},fe=>{const te=y.current.get(f)||[],pe=pl(te,fe),de=Math.max(pe.length,Number(fe.totalMessages||0));S.current.set(f,{knownMessageCount:de,lastMessageSignature:typeof fe.lastMessageSignature=="string"?fe.lastMessageSignature:fo(pe[pe.length-1])}),ca(te)!==ca(pe)&&(y.current.set(f,pe),k(we=>we+1))})},[C,G,u,_,f]);const se=a.useCallback(async()=>{if(E)return;const J=t.tabKey,ie=N(J);if(R.length>ie.visibleLiveCount){M(J,{visibleLiveCount:Math.min(R.length,ie.visibleLiveCount+la),error:null});return}H(!0),M(J,{error:null});try{const ne=dr(t);if(!ne){M(J,{hasMore:!1});return}const he=jt(t),ue=await I(ne,"chat_history",{agentType:he,offset:ie.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),fe=ll(ue),te=fe.messages||[];if(te.length>0){const pe=N(J);M(J,{messages:[...te,...pe.messages],offset:pe.offset+te.length,hasMore:!!fe.hasMore})}else M(J,{hasMore:!!fe.hasMore})}catch(ne){const he=(ne==null?void 0:ne.message)||"";he.includes("P2P not available")||he.includes("channel not open")||he.includes("P2P not connected")||he.includes("timeout")?M(J,{error:"Connection not ready — tap to retry"}):M(J,{hasMore:!1,error:"Failed to load history"})}finally{H(!1)}},[E,t,R.length,I,N,M]),{allMessages:Y,receivedAtMap:oe}=a.useMemo(()=>{const J=z>0?R.slice(-g.visibleLiveCount):R;if(w.length===0){const ue=aa(Ss(J)),fe={};return ue.forEach((te,pe)=>{const de=`${t.tabKey}:${ls(te,pe)}`;let ye=ss(te)||h.current.get(de)||0;ye||(ye=Date.now(),h.current.set(de,ye)),fe[ls(te,pe)]=ye}),{allMessages:ue,receivedAtMap:fe}}const ie=cl(w,J),ne=aa(Ss([...ie,...J])),he={};return ne.forEach((ue,fe)=>{const te=`${t.tabKey}:${ls(ue,fe)}`;let pe=ss(ue)||h.current.get(te)||0;pe||(pe=Date.now(),h.current.set(te,pe)),he[ls(ue,fe)]=pe}),{allMessages:ne,receivedAtMap:he}},[t.tabKey,z,w,R,g.visibleLiveCount]),je=a.useMemo(()=>c.filter(J=>J.routeId===t.tabKey).sort((J,ie)=>J.timestamp-ie.timestamp),[c,t.tabKey]),V=a.useMemo(()=>{if(R.length===0){if(t.connectionState==="connecting"||t.connectionState==="new")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[e.jsx("div",{className:"connecting-logo-float",children:e.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:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",e.jsx("span",{className:"connecting-dots"})]}),e.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((v.isGenerating||t.status==="streaming")&&H(!1),t.status==="not_monitored")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(_s,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ps,{size:14})," Open ",P," Panel"]})}),e.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(t.status==="panel_hidden")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(Za,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ps,{size:14})," Open ",P," Panel"]})}),e.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(t.status==="idle"&&!E)return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),e.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[t.connectionState,t.status,o,i,E,R.length,P,v.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&e.jsx(po,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(jc,{messages:Y,actionLogs:je,agentName:Bs(t)||P||"Agent",userName:l,isCliMode:T.isCli||T.isAcp,isWorking:v.isGenerating,contextKey:t.tabKey,receivedAtMap:oe,onLoadMore:se,isLoadingMore:E,hasMoreHistory:j,hiddenLiveCount:z,loadError:$??void 0,emptyState:V,scrollToBottomRequestNonce:x}),m&&!T.isCliTerminal&&(()=>{var J,ie,ne,he,ue,fe;return e.jsx(Dc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:T.providerType,displayLabel:T.displayLabel,controls:(J=T.targetEntry)==null?void 0:J.providerControls,controlValues:(ie=T.targetEntry)==null?void 0:ie.controlValues,serverModel:((ne=T.targetEntry)==null?void 0:ne.currentModel)||void 0,serverMode:((he=T.targetEntry)==null?void 0:he.currentPlan)||void 0,acpConfigOptions:T.isAcp?(ue=T.targetEntry)==null?void 0:ue.acpConfigOptions:void 0,acpModes:T.isAcp?(fe=T.targetEntry)==null?void 0:fe.acpModes:void 0})})(),!T.isCliTerminal&&e.jsx(Ec,{contextKey:t.tabKey,panelLabel:P,isSending:n,onSend:r,isActive:m})]})}let xo=Qt;function ho(){return xo()}class fl{constructor(){nt(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 bo=new fl;class xl{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 tt=new xl;function hl(t){t.dashboardWS&&(bo=t.dashboardWS),t.connectionManager&&(tt=t.connectionManager),t.useDaemonsHook&&(xo=t.useDaemonsHook)}function Qe(t){return wr(t)}function rs(t){return vn(t).join(" · ")}function go(t){if(t.lastMessagePreview)return t.lastMessagePreview;const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=ts(s==null?void 0:s.content);return r||(t.title?t.title:rs(t)||"No messages yet")}function yo(t,s){const{isReconnecting:r,isConnecting:n}=hs(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function bl(t,s){const r=["Chat",...vn(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function Yt(t){return yo(t)||rs(t)}function gl(t){return`${Qe(t)} · ${go(t)}`}function yl(t){const s=yn(t)||jt(t);return`${Qe(t)} — ${Ze(s)}`}function vl(t){return Bs(t)||"CLI"}function vo(t){return t.title||Bs(t)||t.routeId}function wo(t){return t?`Remote · ${Qe(t)||t.workspaceName||"Session"}`:"Remote"}function wl({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var E;const{ides:c}=Qt(),l=a.useRef(null),{sendCommand:p,sendData:x}=St(),[m,h]=a.useState(""),[y,S]=a.useState(!1),[I,u]=a.useState(1),b=a.useRef(!1),v=a.useRef(0),d=a.useRef(!1),N=a.useRef(""),M=a.useRef(null),k=a.useRef(!1),f=a.useRef(null),g=t.tabKey,w=t.sessionId||"",j=t.daemonId||((E=t.routeId)==null?void 0:E.split(":")[0])||t.routeId||"",$=c.find(H=>H.id===j&&H.type==="adhdev-daemon"),D=($==null?void 0:$.terminalSizingMode)==="fit"?"fit":"measured",K=.6,R=1.15,z=()=>{if(typeof window>"u")return 1;const H=window.innerWidth||0;return H<=360?.68:H<=390?.74:H<=430?.82:H<=480?.9:1},P=()=>{var H,se;v.current=0,d.current=!1,N.current="",M.current=null,k.current=!1,f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),S(!1),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},C=()=>{var H,se;v.current=0,d.current=!1,N.current="",M.current=null,k.current=!1,f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),S(!0),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},_=()=>{var se;if(f.current=null,!i)return;const H=N.current;H&&(N.current="",(se=r.current)==null||se.write(H))},G=H=>{H&&(N.current+=H,i&&f.current===null&&(f.current=requestAnimationFrame(_)))},T=(H,se=0,Y,oe)=>{var je,V,ae,W,be;se>0&&v.current>=se||se===0&&d.current||(v.current=se,S(!0),typeof Y=="number"&&typeof oe=="number"&&Y>0&&oe>0&&((V=(je=r.current)==null?void 0:je.resize)==null||V.call(je,Y,oe)),(W=(ae=r.current)==null?void 0:ae.reset)==null||W.call(ae),H&&((be=r.current)==null||be.write(H)))};return a.useEffect(()=>{P()},[w]),a.useEffect(()=>{var se;if(!w)return;const H=((se=tt.onRuntimeEvent)==null?void 0:se.call(tt,w,Y=>{if(!(!Y||Y.sessionId!==w)){if(Y.type==="runtime_snapshot"){if(!i){M.current={text:Y.text||"",seq:Y.seq||0,cols:Y.cols,rows:Y.rows};return}T(Y.text||"",Y.seq||0,Y.cols,Y.rows);return}if(Y.type==="session_output"){d.current=!0,typeof Y.seq=="number"&&(v.current=Math.max(v.current,Y.seq)),y||S(!0),typeof Y.data=="string"&&G(Y.data);return}if(Y.type==="session_cleared"){if(!i){k.current=!0,N.current="",M.current=null;return}C()}}}))||(()=>{});return()=>{H()}},[j,w,r,i,y]),a.useEffect(()=>{var se,Y,oe;if(!w)return;j&&((se=tt.getState)==null?void 0:se.call(tt,j))==="connected"&&(S(!0),(Y=tt.requestRuntimeSnapshot)==null||Y.call(tt,j,w).catch(()=>{}));const H=(oe=tt.onStateChange)==null?void 0:oe.call(tt,(je,V)=>{var ae;je!==j||V!=="connected"||(S(!0),(ae=tt.requestRuntimeSnapshot)==null||ae.call(tt,j,w).catch(()=>{}))});return()=>{H==null||H()}},[j,w,r]),a.useEffect(()=>{s&&P()},[s,g,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const H=()=>{b.current||u(z())};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),a.useEffect(()=>{var se;if(!i){(se=l.current)==null||se.blur();return}k.current&&(k.current=!1,C());const H=M.current;H&&(M.current=null,T(H.text,H.seq,H.cols,H.rows)),N.current&&f.current===null&&(f.current=requestAnimationFrame(_)),requestAnimationFrame(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})},[i]),a.useEffect(()=>()=>{f.current!==null&&(cancelAnimationFrame(f.current),f.current=null)},[]),a.useEffect(()=>{const H=se=>{var oe;const Y=se.detail;Y!=null&&Y.sessionId&&Y.sessionId!==w||y&&((oe=r.current)==null||oe.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",H),()=>{window.removeEventListener("adhdev:fit-cli-terminal",H)}},[y,w,r]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[e.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[e.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:()=>{b.current=!0,u(H=>Math.max(K,Number((H-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),e.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:()=>{b.current=!0,u(H=>Math.min(R,Number((H+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),e.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:e.jsx("div",{style:{width:`${100/I}%`,height:`${100/I}%`,transform:`scale(${I})`,transformOrigin:"top left"},children:e.jsx(ro,{ref:r,readOnly:!y||!i,sizingMode:D,onInput:H=>{y&&(x!=null&&x(j,{type:"pty_input",targetSessionId:w,data:H})||p(j,"pty_input",{targetSessionId:w,data:H}).catch(console.error))}})})}),!y&&e.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"})]}),e.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:e.jsxs("div",{className:"flex gap-2.5 items-center",children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:l,type:"text",placeholder:`Send message to ${Qe(t)}...`,value:m,disabled:!y||!i||o,onChange:H=>h(H.target.value),onPaste:H=>{const se=H.clipboardData.getData("text");se&&h(Y=>Y+se),H.preventDefault()},onKeyDown:H=>{if(H.key!=="Enter")return;if(H.nativeEvent.isComposing){H.preventDefault();return}H.preventDefault();const se=m.trim();!y||!se||o||(h(""),n(se))},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))"}})}),e.jsx("button",{onClick:()=>{const H=m.trim();!y||!H||o||(h(""),n(H))},disabled:!y||!i||!m.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function jl({wsStatus:t,showReconnected:s,loginUrl:r}){const n=t==="disconnected"||t==="reconnecting"||t==="offline"||t==="auth_failed",o=t==="auth_failed"?"red":t==="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 e.jsxs(e.Fragment,{children:[n&&e.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:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:t==="auth_failed"?.6:1,animation:t==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:t==="auth_failed"?"grayscale(1)":void 0}}),t==="offline"&&"Network offline — waiting for connection...",t==="disconnected"&&"Reconnecting to server...",t==="reconnecting"&&"Reconnecting to server...",t==="auth_failed"&&(r?e.jsxs(e.Fragment,{children:["Session expired."," ",e.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&t==="connected"&&e.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:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function kl({terminalBackend:t,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!t?null:`adhdev:terminal-backend-banner:dismissed:${n}:${t.backend}`,[n,t]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!t||t.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",p=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return e.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:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[e.jsxs("span",{children:[l," is using `xterm` fallback."]}),e.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),e.jsx("button",{type:"button",onClick:p,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 jn({mode:t,onChange:s,compact:r=!1}){const n=r?14:15;return e.jsx("button",{type:"button",onClick:()=>s(t==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:t==="chat"?"Switch to Terminal view":"Switch to Chat view",children:t==="chat"?e.jsx(gr,{size:n}):e.jsx(Kt,{size:n})})}function Nl(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Ht(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return t.lastMessageAt||Nl(s==null?void 0:s.receivedAt)||0}function sn(t,s=0){return Ht(t)||t.lastUpdated||s||0}function jo(t){return Ht(t)||t.lastUpdated||0}function pr(t,s,r=jo){const n=r(s)-r(t);if(n!==0)return n;const o=(t.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=t.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=t.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:t.tabKey.localeCompare(s.tabKey)}function rn(t){var r;const s=xt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Sl(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!rn(t)&&!t.title.trim()}function Cl(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(rn(r))-Number(rn(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:pr(s,r)})[0]||null}function Dt(t,s){const r=t.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=Cl(o);return n?i&&Sl(n)?i:n:i||r[0]||null}function da({value:t}){return t?e.jsx("span",{className:"dashboard-header-shortcut-pill",children:t}):null}function ua({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=vn(t),i=bn(Ht(t)),c=[...o,i].filter(Boolean);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:wr(t)}),(r||c.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function Il({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:p,onSetCliViewMode:x,onOpenConversation:m,onHideConversation:h,hiddenConversations:y=[],onShowConversation:S,onShowAllHidden:I,onResetPanelsToMain:u,inboxOpen:b,onInboxOpenChange:v,hiddenOpen:d,onHiddenOpenChange:N,onOpenNewSession:M,actionShortcuts:k}){const{ides:f,p2pStates:g={}}=Qt(),w=!!t&&Xe(t)&&!Ve(t),j=!!t&&Ve(t),$=p||(t?lo(t)?"terminal":"chat":null),[D,K]=a.useState(!1),R=a.useRef(null),z=a.useRef(null),P=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",_=f.filter(X=>X.type==="adhdev-daemon"),G=a.useMemo(()=>$s(f),[f]),T=Object.values(g),E=T.filter(X=>X==="connected").length,H=T.filter(X=>X==="connecting"||X==="new"||X==="checking").length,Y=r!=="connected"||_.length===0?null:H>0&&E===0?"P2P connecting...":E>0&&s===0?"Waiting for IDE...":null,oe=a.useMemo(()=>o.filter(X=>!Lc(X,o,G)),[o,G]),je=a.useMemo(()=>oe.filter(X=>Ls(X,G).requiresAction).sort(pr),[oe,G]),V=a.useMemo(()=>oe.filter(X=>{const J=(t==null?void 0:t.tabKey)===X.tabKey;return Ls(X,G,{hideOpenTaskCompleteUnread:!0,isOpenConversation:J}).unread}).sort(pr),[t,oe,G]),ae=a.useMemo(()=>[...je,...V].slice(0,9),[je,V]),W=je.length+V.length;a.useEffect(()=>{if(!b)return;const X=J=>{var ie;(ie=R.current)!=null&&ie.contains(J.target)||v(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[b,v]),a.useEffect(()=>{if(!d)return;const X=J=>{var ie;(ie=z.current)!=null&&ie.contains(J.target)||N(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[d,N]),a.useEffect(()=>{if(!d&&!b)return;const X=J=>{if(!J.altKey)return;const ie=J.code.match(/^Digit([1-9])$/);if(!ie)return;const ne=Number(ie[1])-1,he=d?y[ne]:void 0,ue=b?ae[ne]:void 0,fe=he||ue;if(fe){if(J.preventDefault(),J.stopPropagation(),he){S==null||S(he),N(!1);return}m==null||m(fe),v(!1)}};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[y,d,b,ae,N,v,m,S]);const be=X=>{if(!X)return;const J=o.find(ie=>ie.tabKey===X);J&&(h==null||h(J))};return e.jsxs("div",{className:"dashboard-header",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("div",{className:"header-title-block",children:e.jsxs("div",{className:"header-title-row",children:[e.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[e.jsx(Kt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Qe(t):"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:P,boxShadow:C}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.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:P,boxShadow:C}}),Y&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Y]}),M&&e.jsx("button",{type:"button",onClick:M,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(sc,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(w||j||!Ve(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:rs(t)||Qe(t),children:Qe(t)}),(w||j)&&l&&e.jsxs(e.Fragment,{children:[w&&x&&$&&e.jsx(jn,{mode:$,onChange:x,compact:!0}),e.jsx("button",{onClick:()=>l(t),className:"btn btn-secondary btn-sm",title:j?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:e.jsx(vt,{size:14})})]}),!Ve(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(fn,{size:14})}),!w&&!Ve(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(Nt,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[e.jsxs("div",{className:`dashboard-header-hidden${D?" is-drop-target":""}`,ref:z,onDragEnter:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),K(!0))},onDragOver:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),X.dataTransfer.dropEffect="move",K(!0))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||K(!1)},onDrop:X=>{const J=X.dataTransfer.getData("text/tab-key");X.preventDefault(),K(!1),be(J)},children:[e.jsxs("button",{type:"button",onClick:()=>N(!d),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[e.jsx(Qa,{size:16}),y.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:y.length})]}),d&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),e.jsx(da,{value:k==null?void 0:k.toggleHiddenTabs})]}),e.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),y.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),N(!1)},children:"Restore all"})]})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx(da,{value:k==null?void 0:k.hideCurrentTab})]}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Qe(t)})]}),y.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:y.map(X=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(X),N(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Qe(X)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[y.indexOf(X)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",y.indexOf(X)+1]}):null,rs(X)]})]},X.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>v(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(yr,{size:16}),W>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:W})]}),b&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),je.map(X=>e.jsx(ua,{conversation:X,isAttention:!0,shortcutIndex:ae.indexOf(X)>=0?ae.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.tabKey))]}),V.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),V.map(X=>e.jsx(ua,{conversation:X,shortcutIndex:ae.indexOf(X)>=0?ae.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.tabKey))]}),W===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Ml(t){if(!t)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(t))}catch{return new Date(t).toLocaleString()}}function kn({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:l,onNewChat:p,onSwitchSession:x,onRefreshHistory:m,onResumeSavedSession:h}){var v;const y=s.find(d=>d.id===t.routeId),S=(y==null?void 0:y.chats)||[],I=(v=y==null?void 0:y.activeChat)==null?void 0:v.id,u=Xe(t)&&!Ve(t),b=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:l,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.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:[e.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:yl(t)})]}),e.jsx("button",{onClick:l,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&e.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?e.jsx(e.Fragment,{children:o.map(d=>{const N=t.providerSessionId===d.providerSessionId,M=N||!d.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{M||!h||h(d)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${N?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:`font-bold text-sm mb-1 truncate ${N?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:d.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:d.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ml(d.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:d.preview||"No saved preview yet"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[e.jsxs("div",{className:"truncate",children:[d.workspace||"Workspace unknown",d.currentModel?` · ${d.currentModel}`:"",d.messageCount>0?` · ${d.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:N?"ACTIVE":d.canResume?c===d.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},d.id)})}):S.map(d=>e.jsxs("div",{onClick:()=>{x(t.routeId,d.id),l()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${I===d.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[e.jsx("div",{className:`font-bold text-sm mb-1 ${I===d.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:d.title||"Untitled Session"}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[d.id.substring(0,12),"..."]}),I===d.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},d.id)),(u&&!i&&o.length===0||!u&&S.length===0)&&e.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[e.jsx("div",{className:"text-3xl mb-3 opacity-60",children:e.jsx(ac,{size:32})}),e.jsx("div",{className:"text-[13px]",children:u?"No saved sessions found yet.":"No recent chat sessions found."})]}),u&&i&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xs,{size:13})," ",u?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Ts.createPortal(b,document.body)}const pa={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function ko({toasts:t,onDismiss:s,onClickToast:r}){return e.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:t.map(n=>{const o=pa[n.type]||pa.info;return e.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:[e.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))`}}),e.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:e.jsx(vt,{size:14})}),e.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[e.jsx("div",{className:"flex items-center gap-2 pr-8",children:e.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})}),e.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&e.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>e.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 Al=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function Tl(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function _l(t){return t.sessionId||t.instanceId||t.agentType}function Dr(t,s){return t||s}function ma(t,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of t[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 No(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=kt(r,{fallbackId:r.id}));return s}function So(t,s={}){var n,o;const r=t.daemonId||((n=t.id)==null?void 0:n.split(":")[0])||t.id;return{machineName:t.daemonId&&((o=s.machineNames)==null?void 0:o[t.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Nn(t,s,r={}){return Pl(t,s,So(t,r))}function Pl(t,s,r={}){var y,S,I,u,b,v;const n=[],o=r.machineName,i=r.connectionState,c=Tl(t),l=Ze(t.type),p=Array.isArray(t.childSessions)?t.childSessions.map(d=>{var N,M;return{sessionId:d.id,instanceId:d.id,providerSessionId:d.providerSessionId,transport:d.transport,agentType:d.providerType,agentName:d.providerName||Ze(d.providerType),status:d.status,title:d.title,lastMessagePreview:d.lastMessagePreview,lastMessageRole:d.lastMessageRole,lastMessageAt:d.lastMessageAt,lastMessageHash:d.lastMessageHash,messages:((N=d.activeChat)==null?void 0:N.messages)||[],activeModal:((M=d.activeChat)==null?void 0:M.activeModal)||void 0,unread:d.unread,lastSeenAt:d.lastSeenAt,lastUpdated:d.lastUpdated,inboxBucket:d.inboxBucket,surfaceHidden:d.surfaceHidden}}):[],x=Al(t),m=t.activeChat||{title:""},h=m.title&&String(m.title).trim()?String(m.title).trim():"";if(x){const d=t.sessionId||t.instanceId,N=Qn(t.type),M=(y=t.activeChat)==null?void 0:y.activeModal,k=M&&Array.isArray(M.buttons)&&M.buttons.length>0,f=xt((S=t.activeChat)==null?void 0:S.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||xt((b=(u=t.agents)==null?void 0:u[0])==null?void 0:b.status)||"idle",g=t.activeChat||{title:"",messages:[]};let w=g.title&&String(g.title).trim()?String(g.title).trim():"";const j=(v=t.activeChat)==null?void 0:v.id,$=t.chats;if(j&&Array.isArray($)&&$.length>0){const C=$.find(_=>_.id===j||_.id&&String(_.id)===String(j));C!=null&&C.title&&String(C.title).trim()&&(w=String(C.title).trim())}const D=(Xe(t)||Ve(t),t.type),K=(Xe(t)||Ve(t))&&ea(w,N,D)?"":w,R=g.messages||[],z=ma(s,[t.id,d]),P=ia(R,z);n.push({routeId:t.id,sessionId:d,providerSessionId:t.providerSessionId,nativeSessionId:d,transport:t.transport,daemonId:t.daemonId||void 0,mode:Xe(t)?t.mode||"terminal":"chat",agentName:N,agentType:D,status:f,title:K,messages:[...R,...P],resume:t.resume,hostIdeType:!Xe(t)&&!Ve(t)?t.type:void 0,workspaceName:c,displayPrimary:c||K||(Xe(t)?t.mode==="chat"?N:"Terminal":N),displaySecondary:l,cdpConnected:t.cdpConnected,lastMessagePreview:t.lastMessagePreview,lastMessageRole:t.lastMessageRole,lastMessageAt:t.lastMessageAt,lastMessageHash:t.lastMessageHash,lastUpdated:t.lastUpdated,modalButtons:k?M.buttons:void 0,modalMessage:k?M.message:void 0,streamSource:"native",tabKey:Dr(d,t.id),machineName:o,connectionState:i})}if(x&&(Xe(t)||Ve(t)))return n;for(const d of p){const N=d.activeModal&&Array.isArray(d.activeModal.buttons)&&d.activeModal.buttons.length>0,M=zc(d),k=_l(d),f=`${t.id}:${k}`,g=d.title&&String(d.title).trim()||"",w=ea(g,d.agentName,d.agentType)?"":g,j=d.messages||[],$=ma(s,[f,d.sessionId,d.instanceId]),D=ia(j,$);(d.transport==="cdp-webview"||d.sessionId||d.providerSessionId||j.length>0||D.length>0||N||w||!["idle","panel_hidden","disconnected","not_monitored"].includes(M))&&n.push({routeId:t.id,sessionId:d.sessionId||d.instanceId,providerSessionId:d.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:d.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:d.agentName,agentType:d.agentType,status:M,title:w,messages:[...j,...D],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||w||l,displaySecondary:`${l} · ${d.agentName}`,cdpConnected:t.cdpConnected,lastMessagePreview:d.lastMessagePreview,lastMessageRole:d.lastMessageRole,lastMessageAt:d.lastMessageAt,lastMessageHash:d.lastMessageHash,lastUpdated:d.lastUpdated||t.lastUpdated,modalButtons:N?d.activeModal.buttons:void 0,modalMessage:N?d.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Dr(d.sessionId||d.instanceId,f),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:t.id,sessionId:t.sessionId||t.instanceId,providerSessionId:t.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:t.transport,daemonId:t.daemonId||void 0,mode:"chat",agentName:Qn(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:t.type,workspaceName:c,displayPrimary:c||l,displaySecondary:l,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,streamSource:"native",tabKey:Dr(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function Ll(t){const s=t.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:t}}function Rl(t,s){const r=Ll(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Co=[{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:"🏄"}],Io=[{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:"🧩"}],Mo=[{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:"🟠"}],Dl=Co,El=Io,$l=Mo,Ao="adhdev_notification_prefs",fa={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Bl(){try{const t=localStorage.getItem(Ao);if(t){const s=JSON.parse(t);return{...fa,...s}}}catch{}return{...fa}}function Kl(t){try{localStorage.setItem(Ao,JSON.stringify(t))}catch{}}let $t=Bl(),rr=[];function Wl(){rr.forEach(t=>t())}function Ol(t){$t={...$t,...t},Kl($t),Wl()}function Hl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return rr.push(r),()=>{rr=rr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Ol(r)},[]);return[{...$t},s]}function Cs(t){if(!$t.globalEnabled)return!1;switch(t){case"disconnect":return $t.disconnectAlert;case"completion":return $t.completionAlert;case"approval":return $t.approvalAlert;case"browser":return $t.browserNotifications;default:return!0}}const Ul={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function zl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function To(){return"Notification"in window&&Notification.permission==="granted"}let Vt=null;async function Fl(){if(Vt!==null)return Vt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Vt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Vt=!!await t.pushManager.getSubscription(),Vt):(Vt=!1,!1)}catch{return Vt=!1,!1}}function nn(t,s,r){if(To())try{const n=new Notification(t,{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 Vl(t,s={}){const r={...Ul,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Fl().then(l=>{i.current=l})},[]);const c=a.useCallback((l,p,x)=>{const m=Date.now();m-o.current<r.throttleMs||(o.current=m,nn(l,p,x))},[r.throttleMs]);a.useEffect(()=>{var l;if(!(!r.enabled||!To())&&Cs("browser")&&i.current!==!0){if(document.hasFocus()){for(const p of t)n.current.set(p.id,xt(p.status,{activeModal:p.activeModal}));return}for(const p of t){const x=n.current.get(p.id),m=xt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(r.onApproval&&Cs("approval")&&m==="waiting_approval"&&x!=="waiting_approval"){const y=((l=p.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,y.slice(0,120),`approval-${p.id}`)}r.onComplete&&Cs("completion")&&io(x)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&m==="error"&&x!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,m)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Gl=/^(run|approve|accept|yes|allow|always)/,ql=/^(run|approve|accept|yes|allow|always|proceed|save)/,Yl=/^(reject|deny|delete|remove|abort|cancel|no)/;function Sn(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Xl(t){const s=Sn(t).toLowerCase();return Gl.test(s)?"primary":Yl.test(s)?"danger":"default"}function Jl(t){return ql.test(Sn(t).toLowerCase())?"approve":"reject"}function Zl(t){return t.map((s,r)=>({label:Sn(s),variant:Xl(s),action:Jl(s),button:s,buttonIndex:r}))}function Ql(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
31
- ${n}`}function ed(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function td(t,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(t,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(t,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class sd{constructor(){nt(this,"dedupMap",new Map);nt(this,"DEDUP_WINDOW_MS",5e3);nt(this,"DEDUP_MAX_SIZE",50);nt(this,"DEDUP_CLEANUP_AGE_MS",1e4);nt(this,"toastCallbacks",[]);nt(this,"systemMessageCallbacks",[]);nt(this,"clearSystemMessageCallbacks",[]);nt(this,"resolveActionFn",null);nt(this,"viewRequestRespondFn",null);nt(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 I,u;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const p=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,x=(p==null?void 0:p.type)||"";let m=Ze(x);const h=this.resolveOwningDaemon(s);if(h){const b=kt(h,{fallbackId:h.id});b&&(m=!x||x==="adhdev-daemon"?b:`${b}/${m}`)}let y="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";y=`✅ ${m} agent task completed${b}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(y=`⚡ ${m} approval needed`,S="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:Ql(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const v=this.resolveActionFn,d=Zl(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{v(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=ed(m,s.modalMessage,y),M=Date.now();this.emitToast({id:M,message:N,type:S,timestamp:M,targetKey:n||b,actions:d,duration:15e3}),y=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";y=`⚠️ ${m} agent is taking a long time${b}`,S="warning",Cs("browser")&&!document.hasFocus()&&nn(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",v=s.requestId,d=s.orgId;if(y=`👁️ ${b} wants to view your session`,S="warning",v&&d&&this.viewRequestRespondFn){const N=Date.now(),M=td(d,v,this.viewRequestRespondFn,(k,f)=>console.error(`[EventManager] ${k} view request failed:`,f));this.emitToast({id:N,message:y,type:S,timestamp:N,actions:M,duration:3e4}),y=""}Cs("browser")&&!document.hasFocus()&&nn("👁️ View Request",`${b} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(y="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(y=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(y){const b=Date.now();this.emitToast({id:b,message:y,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ht=new sd;function ns(...t){return Pi(Li(t))}function rd({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:ns("dashboard-header",i),children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"header-title flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center text-lg",children:t})," ",s,n&&e.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&&e.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&e.jsx("div",{className:"flex gap-2",children:o})]})}function _o({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(rd,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:ns("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Pt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:ns("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:[(t||r)&&e.jsxs("div",{className:"mb-4",children:[t&&e.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&e.jsx("span",{className:"mr-1.5",children:s}),t]}),r&&e.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Po({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:ns("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e.jsx("div",{className:"text-5xl mb-4 opacity-50",children:t}),e.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),e.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const nd={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"},ad={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function od({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:ns("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",nd[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:ad[t]}),e.jsx("span",{children:s})]}),r&&e.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const id={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"},cd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ld({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:ns("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",id[t],r),children:[e.jsx("span",{className:ns("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",cd[t])}),n]})}function dd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function an(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function nr(t){return t==="system"?dd():t}function ud(){typeof document>"u"||document.documentElement.setAttribute("data-theme",nr(an()))}function Cn(){const[t,s]=a.useState(an),[r,n]=a.useState(()=>nr(an()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=p=>{t==="system"&&n(p.matches?"light":"dark")};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[t]);const o=a.useCallback(c=>{s(c),n(nr(c));try{localStorage.setItem("theme",c)}catch{}},[]),i=a.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark";n(nr(l));try{localStorage.setItem("theme",l)}catch{}return l})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const xa={dark:"Dark",light:"Light",system:"System"};function pd({collapsed:t}){const{preference:s,cycleTheme:r}=Cn(),n=s==="dark"?e.jsx(ic,{size:16}):s==="light"?e.jsx(oc,{size:16}):e.jsx(cc,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${xa[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:xa[s]})]})}function qt({label:t,description:s,checked:r,disabled:n,onChange:o,extra:i}){return e.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[e.jsxs("div",{className:"pr-4",children:[e.jsx("div",{className:"font-medium text-sm",children:t}),e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,e.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:[e.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))"}}),e.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 md({onPrefChange:t}){const[s,r]=Hl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&e.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_s,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&e.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function mr(t){const s=t.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function fd(t,s){const r=mr(t),n=mr(s);if(!r||!n)return t.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 Lo(t,s){const r=t.version||null;return t.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Is(t,s){if(t.versionUpdateRequired===!0)return!0;const r=t.version||null;if(!r||!s||r===s||fd(r,s)>=0)return!1;const n=mr(r),o=mr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function xd(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Er(t,s){return t instanceof Error?t.message:s}function hd({ides:t,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=t.filter(c=>c.type==="adhdev-daemon");return i.length===0?e.jsx(Po,{icon:e.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||"Run 'adhdev-standalone' to connect a local daemon instance."}):e.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>e.jsx(gd,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function ha({title:t,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 Ts.createPortal(e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:e.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:[e.jsx("div",{className:"font-semibold text-sm mb-3",children:t}),e.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.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"}),e.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 bd(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Dl,...El,...$l].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:t}}function gd({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var z,P;const[i,c]=a.useState("idle"),[l,p]=a.useState(""),[x,m]=a.useState(null),[h,y]=a.useState("idle"),[S,I]=a.useState(""),u=t.version||null,b=((z=t.machine)==null?void 0:z.platform)||((P=t.system)==null?void 0:P.platform)||"",v=kt(t,{fallbackId:t.id}),d=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===t.id&&C.transport==="cdp-page"),M=s.filter(C=>C.daemonId===t.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===t.id&&C.transport==="acp"),f=t.p2p,g=async()=>{if(r){c("upgrading"),p("Starting upgrade...");try{const C=xd(await r(t.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),p(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),p(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(C.error||"Upgrade failed"))}catch(C){c("error"),p(Er(C,"Connection lost during upgrade"))}}},w=async()=>{if(m(null),!!n){y("loading");try{await n(t.id),y("done"),I("Machine disconnected.")}catch(C){y("error"),I(Er(C,"Failed to disconnect"))}}},j=async()=>{if(m(null),!!o){y("loading");try{await o(t.id),y("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(C){y("error"),I(Er(C,"Failed to revoke token"))}}},$="0.8.48",D=Lo(t,$),K=Is(t,$),R=N.length+M.length+k.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:d}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),u&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!D&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&D&&e.jsx("button",{onClick:g,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${K?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&e.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&e.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(ld,{status:t.status==="online"?"online":"error"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[f&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${f.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${f.state==="connecting"||f.state==="new"?"animate-pulse":""}`,style:f.state==="connecting"||f.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",f.state==="connected"?"connected":f.state==="connecting"||f.state==="new"?"connecting...":f.state||"off"]}),f.peers!==void 0&&f.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",f.peers," peer",f.peers!==1?"s":"",")"]})]}),f&&R>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const _=bd(C.type),G=C.cdpConnected;return e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:_.icon}),e.jsx("span",{children:_.name}),G!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},C.id)}),M.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"⌨️"}),e.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"🔗"}),e.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||S)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||l})]}),x==="disconnect"&&e.jsx(ha,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
32
-
33
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
-
35
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>m(null)}),x==="revoke"&&e.jsx(ha,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
36
-
37
- This will:
38
- • Immediately disconnect the machine
39
- • Delete the machine registration
40
- • Require restarting "adhdev-standalone" on that machine
41
-
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>m(null)})]})}const yd=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function vd(){const{preference:t,setPreference:s}=Cn();return e.jsx("div",{className:"flex gap-2",children:yd.map(r=>e.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 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function wd(t){const s=t.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 jd(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function $r(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ba(t){const{r:s,g:r,b:n}=jd(t);return .2126*$r(s)+.7152*$r(r)+.0722*$r(n)}function ga(t,s){const r=ba(t),n=ba(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function Ro(t){const s=wd(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return ga(s,r)>=ga(s,n)?r:n}const on={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},cn={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},kd=[{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"}}}],Do="adhdev-chat-theme",Eo="adhdev-chat-theme-custom";function ar(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Do)||"ember"}catch{return"ember"}}function Lt(t){try{const s=localStorage.getItem(Eo);if(s){const r=JSON.parse(s);return{...t==="dark"?on:cn,...r[t]}}}catch{}return t==="dark"?on:cn}function Vs(t,s){try{localStorage.setItem(Eo,JSON.stringify({dark:t,light:s}))}catch{}}function Mt(t,s){const r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function fr(t,s){const r=Math.min(255,parseInt(t.slice(1,3),16)+s),n=Math.min(255,parseInt(t.slice(3,5),16)+s),o=Math.min(255,parseInt(t.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 Nd={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ms(t,s){var o;const r=(o=Nd[t])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",fr(r,24)),n.style.setProperty("--accent-on-primary",Ro(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${fr(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function Xt(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",Mt(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",Mt(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(t.borderSubtle,.25)),s.style.setProperty("--text-primary",t.textPrimary),s.style.setProperty("--text-secondary",t.textSecondary),s.style.setProperty("--text-muted",t.textMuted),s.style.setProperty("--border-subtle",Mt(t.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",fr(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Ro(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${fr(t.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${Mt(t.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",t.userBubble),s.style.setProperty("--chat-user-color",t.userText),s.style.setProperty("--chat-user-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px 4px ${t.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",t.assistantBubble),s.style.setProperty("--chat-assistant-color",t.assistantText),s.style.setProperty("--chat-assistant-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px ${t.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Mt(t.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",t.containerBg),s.style.setProperty("--dashboard-pane-bg",t.containerBg),s.style.setProperty("--chat-thought-accent",t.accentColor),s.style.setProperty("--chat-tool-accent",t.accentColor),s.style.setProperty("--chat-action-color",t.accentColor),s.style.setProperty("--chat-send-bg",t.sendButton),s.style.setProperty("--chat-input-border",t.inputBorder)}function In(){const t=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=>t.style.removeProperty(r))}function Sd(t){try{localStorage.setItem(Do,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else In(),Ms(t,Jt()?"dark":"light")}function Cd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=ar();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else In(),Ms(t,Jt()?"dark":"light")}function Jt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ft({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.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}}),e.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 ys({title:t,children:s}){return e.jsxs("div",{style:{marginBottom:14},children:[e.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:t}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Id({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>Lt(r));a.useEffect(()=>{o(Lt(r))},[r]);const i=a.useCallback((c,l)=>{o(p=>{const x={...p,[c]:l},h=Lt(r==="dark"?"light":"dark");return r==="dark"?Vs(x,h):Vs(h,x),Xt(x),s(x),x})},[r,s]);return e.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[e.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",e.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[t?"🌙 Dark":"☀️ Light"," mode"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ys,{title:"App Background",children:[e.jsx(ft,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(ft,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(ft,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(ys,{title:"App Text",children:[e.jsx(ft,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(ft,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(ft,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(ys,{title:"Borders & Accent",children:[e.jsx(ft,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(ft,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(ft,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(ys,{title:"Chat Bubbles",children:[e.jsx(ft,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(ft,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(ft,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(ft,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(ys,{title:"Chat Layout",children:[e.jsx(ft,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(ft,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(ft,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[e.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)"}}),e.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),e.jsx("button",{onClick:()=>{const c=t?on:cn,p=Lt(t?"light":"dark");t?Vs(c,p):Vs(p,c),o(c),Xt(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 Md(){const[t,s]=a.useState(ar),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Lt("dark"));a.useEffect(()=>{n(Jt());const p=new MutationObserver(()=>{const h=Jt();n(h);const y=ar();y==="custom"?Xt(Lt(h?"dark":"light")):Ms(y,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const x=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=Jt();n(h);const y=ar();y==="custom"?Xt(Lt(h?"dark":"light")):Ms(y,h?"dark":"light")};return x.addEventListener("change",m),()=>{p.disconnect(),x.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xt(Lt(r?"dark":"light")):(In(),Ms(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(Lt(r?"dark":"light"))},[r]);const c=p=>{s(p),Sd(p)},l=[...kd,{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 e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(p=>{const x=t===p.id,m=r?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:x?"var(--bg-glass-hover)":"var(--bg-glass)",border:x?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:x?1:.75},children:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[x&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?"🎨 Custom":p.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&e.jsx(Id,{dark:r,onColorsChange:p=>i(p)})]})}const $o="adhdev_mobileDashboardMode_v1";function Bo(){try{return localStorage.getItem($o)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Ad(t){try{localStorage.setItem($o,t)}catch{}}function Td(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(Bo()==="chat")},[]),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:t?"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:t,onChange:r=>{s(r),Ad(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function _d(t,s,r){return{...t||{},id:s,type:(t==null?void 0:t.type)||"adhdev-daemon",status:(t==null?void 0:t.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(t==null?void 0:t.machine)||{},...r.machine}}}function Pd(t,s){const{sendData:r}=St(),{injectEntries:n,getIdes:o}=lr(),i=Array.from(new Set(t.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(p=>Ot.subscribe({sendData:r},p,{type:"subscribe",topic:"machine.runtime",key:`machine:${p}`,params:{intervalMs:s==null?void 0:s.intervalMs}},x=>{const m=o().find(y=>y.id===p),h=_d(m,p,x);n([h])}));return()=>{l.forEach(p=>p())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Ko(t,s){const{sendData:r}=St(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!t){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);const l=Ot.subscribe({sendData:r},t,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${t}`,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=>{o(p.diagnostics),c(!1)});return()=>{l()}},[t,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 Ld(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function Wo(t){const{sendData:s}=St(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Ld(t);if(!o||!t.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${t.sessionId}`,params:{targetSessionId:t.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const Oo="adhdev_hiddenTabs";function Rd(){try{const t=localStorage.getItem(Oo);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function is(t){try{localStorage.setItem(Oo,JSON.stringify([...t]))}catch{}}function Dd(){const[t,s]=a.useState(Rd),r=a.useCallback(x=>{s(m=>{const h=new Set(m);return h.has(x)?h.delete(x):h.add(x),is(h),h})},[]),n=a.useCallback(x=>{s(m=>{if(m.has(x))return m;const h=new Set(m);return h.add(x),is(h),h})},[]),o=a.useCallback(x=>{s(m=>{if(!m.has(x))return m;const h=new Set(m);return h.delete(x),is(h),h})},[]),i=a.useCallback(()=>{s(x=>{if(x.size===0)return x;const m=new Set;return is(m),m})},[]),c=a.useCallback((x,m)=>{s(h=>{const y=new Set(h);for(const S of m)y.add(S);return is(y),y})},[]),l=a.useCallback((x,m)=>{s(h=>{const y=new Set(h);for(const S of m)y.delete(S);return is(y),y})},[]),p=a.useCallback(x=>t.has(x),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:p}}function Ed({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{zl()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:vo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return Vl(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const p=Date.now(),x={};for(const[m,h]of Object.entries(l))p-h<5e3&&(x[m]=h);return Object.keys(x).length===Object.keys(l).length?l:x})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const p=l.filter(x=>x.timestamp>c).slice(-100);return p.length===l.length?l:p})},6e4);return()=>clearInterval(i)},[n]),null}function $d(t){const s=t.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 Gs(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function Bd(t,s){const r=Date.now();return t.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Kd(t,s){const r=[],n=t.sessionId||t.instanceId;r.push({key:t.id,ref:s[t.id]}),n&&r.push({key:n,ref:s[n]});for(const o of t.childSessions||[]){const i=o.id||o.providerType,c=`${t.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Wd(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r].key!==s[r].key||t[r].ref!==s[r].ref)return!1;return!0}function Od(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Hd(t){const s=Od(t);if(!s)return`empty:${t.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=ts(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Ud({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),l=a.useRef([]),p=a.useRef([]),x=a.useMemo(()=>{const f=$d(t);return Gs(i.current,f)?i.current:(i.current=f,f)},[t]),m=a.useMemo(()=>No(t),[t]),h=a.useRef(new Map),y=a.useRef(new Map),S=a.useMemo(()=>{const f=new Map,g=[];for(const D of x){const{connectionState:K="new",machineName:R}=So(D,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),z=Kd(D,r),P=h.current.get(D.id);if(P&&P.ide===D&&P.connectionState===K&&P.machineName===R&&Wd(P.localRefs,z)){f.set(D.id,P),g.push(...P.conversations);continue}const C=Nn(D,r,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),_={ide:D,connectionState:K,machineName:R,localRefs:z,conversations:C};f.set(D.id,_),g.push(...C)}h.current=f;const w=new Map,j=D=>{const K=Hd(D),R=y.current.get(D.tabKey);if(R&&R.signature===K)return w.set(D.tabKey,R),R.timestamp;const z={signature:K,timestamp:jo(D)||(R==null?void 0:R.timestamp)||0};return w.set(D.tabKey,z),z.timestamp},$=[...g].sort((D,K)=>pr(D,K,j));return y.current=w,$},[x,r,s,m]),I=a.useMemo(()=>{const f=Bd(S,n);return Gs(c.current,f)?c.current:(c.current=f,f)},[S,n]),u=a.useMemo(()=>{const f=new Map,g=Array.from(new Set(I.map(w=>w.routeId)));for(const w of g){const j=Dt(I,w);j&&f.set(w,j)}return f},[I]),b=a.useMemo(()=>{const f=new Map;for(const g of I)if(g.sessionId&&f.set(g.sessionId,g),g.streamSource==="native"&&g.sessionId){const w=u.get(g.routeId);w&&f.set(g.sessionId,w)}return f},[I,u]),v=a.useMemo(()=>{const f=new Map;for(const g of I)g.sessionId&&f.set(g.sessionId,g),f.set(g.routeId,u.get(g.routeId)||g),f.set(g.tabKey,g);return f},[I,u]),d=a.useCallback(f=>{if(f)return b.get(f)},[b]),N=a.useCallback(f=>{if(f)return v.get(f)},[v]),M=a.useMemo(()=>{const f=I.filter(g=>!o.has(g.tabKey));return Gs(l.current,f)?l.current:(l.current=f,f)},[I,o]),k=a.useMemo(()=>{const f=M.map(g=>g.tabKey);return Gs(p.current,f)?p.current:(p.current=f,f)},[M]);return{chatIdes:x,conversations:I,visibleConversations:M,visibleTabKeys:k,resolveConversationBySessionId:d,resolveConversationByTarget:N}}function zd({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var l;return t||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var l;return!t||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(l=>{const p=new URLSearchParams(l);return p.delete("activeTab"),p},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Fd({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{ht.setIdes(t)},[t]),a.useEffect(()=>{ht.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),a.useEffect(()=>{const i=ht.onToast(p=>{r(m=>m.some(y=>y.message===p.message&&p.timestamp-y.timestamp<3e3)?m:[...m.slice(-4),{id:p.id,message:p.message,type:p.type,timestamp:p.timestamp,targetKey:p.targetKey,actions:p.actions}]);const x=p.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==p.id)),x)}),c=ht.onSystemMessage((p,x)=>{var S,I;const m=o(p),h=(S=x._localId)==null?void 0:S.startsWith("sys_approval_"),y=!!(m&&(m.status==="waiting_approval"||(I=m.modalButtons)!=null&&I.length||m.modalMessage));h&&y||n(u=>({...u,[p]:[...u[p]||[],x]}))}),l=ht.onClearSystemMessage((p,x)=>{n(m=>{var h;return(h=m[p])!=null&&h.length?{...m,[p]:m[p].filter(y=>{var S;return!(y.role==="system"&&((S=y._localId)!=null&&S.startsWith(x)))})}:m})});return()=>{i(),c(),l()}},[r,n]),a.useEffect(()=>{const i=bo.on("status_event",c=>{ht.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=l=>{var b;const p=l.data;if((p==null?void 0:p.type)!=="notification_action"||typeof p.action!="string"||!p.action.startsWith("approval_")||!(p.daemonId||p.targetSessionId||p.targetKey))return;const x=p.targetSessionId||p.targetKey||p.daemonId,m=o(x),h=(m==null?void 0:m.routeId)||p.daemonId;if(!h)return;const y=Number(p.buttonIndex),S=p.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[y])||"Approve",I=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(y)&&{buttonIndex:y},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...p.targetSessionId&&{targetSessionId:p.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 Vd="adhdev_dashboardLayout_v1",Gd="adhdev_dashboardDockview_v1",qd="adhdev_dashboardDockviewHiddenRestore_v1",vs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Mn(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function Ho(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Uo(t){return`${Vd}:${t}`}function Yd(t){const s=Uo(t);return Mn(s,null)}function Xd(t,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=Uo(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function zo(t){return`${Gd}:${t}`}function Jd(t){const s=zo(t);return Mn(s,null)}function Zd(t,s){try{const r=zo(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Fo(t){return`${qd}:${t}`}function Qd(t){const s=Fo(t);return Mn(s,{})}function eu(t,s){try{const r=Fo(t);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function tu(){return{groupAssignments:[...vs.groupAssignments],focusedGroup:vs.focusedGroup,groupActiveTabIds:{...vs.groupActiveTabIds},groupTabOrders:{...vs.groupTabOrders},groupSizes:[...vs.groupSizes]}}function su(){const[t]=a.useState(()=>Ho(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[l,p]=a.useState({}),[x,m]=a.useState([]),[h,y]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,I]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const b=Yd(t)??tu();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),p(b.groupTabOrders),m(b.groupSizes),I(!0)},[S,t]);return a.useEffect(()=>{S&&Xd(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:x})},[S,t,s,n,i,l,x]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=d=>y(d.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:p,groupSizes:x,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function ru(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 nu({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:p,historyModalOpen:x,activeConv:m,isRefreshingHistory:h,ides:y,handleRefreshHistory:S}){const I=a.useRef(!1),u=a.useRef(!1),b=a.useRef(null),v=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const d=r(t);if(!d)return;const N=n.get(d.tabKey)??0;c(M=>({...M,[N]:d.tabKey})),l(N),I.current=!0,u.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),p(M=>{const k=new URLSearchParams(M);return k.delete("activeTab"),k},{replace:!0})},[t,s,r,n,o,i,c,l,p]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!t){i(),u.current=!0;return}if(I.current){u.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!x){v.current=!1;return}if(!m||v.current||h)return;const d=y.find(N=>N.id===m.routeId);d&&(!d.chats||d.chats.length===0||ru(d.chats,m))&&(v.current=!0,S())},[x,m,h,y,S]),a.useEffect(()=>{if(!m)return;let d=null,N=0,M=-1,k=0;const f=()=>{d=null;const g=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(g.length===0){N<18&&(N+=1,d=requestAnimationFrame(f));return}let w=0;for(const j of g)j.scrollTop=j.scrollHeight,w+=j.scrollHeight;w===M?k+=1:(k=0,M=w),N+=1,!(k>=2||N>=18)&&(d=requestAnimationFrame(f))};return d=requestAnimationFrame(f),()=>{d!=null&&cancelAnimationFrame(d)}},[m==null?void 0:m.tabKey])}function au({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:l}){const[p,x]=a.useState(null),[m,h]=a.useState(null),y=a.useMemo(()=>{if(t||!n)return null;const v=l(n);return v&&!Xe(v)&&!Ve(v)?v:null},[t,n,l]),S=a.useMemo(()=>{const v=p==null?void 0:p.routeId;if(!v)return null;const d=p!=null&&p.tabKey?i.find(N=>N.tabKey===p.tabKey):o?i.find(N=>N.tabKey===o):null;return(d==null?void 0:d.routeId)===v?d:Dt(i,v)},[i,p,o]),I=a.useMemo(()=>{if(S)return c.find(v=>v.id===S.routeId)},[c,S]);a.useEffect(()=>{y&&(x({routeId:y.routeId,tabKey:ta(y)}),h(y),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,y]);const u=a.useCallback(v=>{v&&(x({routeId:v.routeId,tabKey:ta(v)}),h(v))},[]),b=a.useCallback(()=>{x(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:I,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:u,closeRemoteDialog:b}}function us(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:Xe(t)||Ve(t)?{agentType:jt(t)}:t.streamSource==="agent-stream"?{agentType:jt(t)}:s}function Ds(t){return t?dr(t):""}function ws(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Br(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[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 ya({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[l,p]=a.useState(!1),[x,m]=a.useState(!1),h=a.useCallback(async u=>{try{await t("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),y=a.useCallback(async(u,b)=>{try{const v=u||(s==null?void 0:s.daemonId)||"",d=await t(v,"switch_chat",{id:b,sessionId:b,...us(s)}),N=d==null?void 0:d.result;if((d==null?void 0:d.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?ws(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?ws(o,`⚠️ Switch error: ${N}`):ws(o,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),ws(o,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,t,o]),S=a.useCallback(async()=>{if(!(!s||l)){p(!0);try{const u=Ds(s);await t(u,"new_chat",{...us(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{p(!1)}}},[s,l,t,c,i]),I=a.useCallback(async()=>{var u,b;if(!(!s||x)){m(!0);try{const v=Ds(s),d=async()=>t(v,"list_chats",{forceExpand:!0,...us(s)});let N=await d(),M=(N==null?void 0:N.chats)||((u=N==null?void 0:N.result)==null?void 0:u.chats);Br(M,s)&&(await new Promise(k=>setTimeout(k,450)),N=await d(),M=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(M)&&(n(s.routeId,M),Br(M,s)&&!Br(r,s)&&ws(o,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,x,t,n,o]);return{isCreatingChat:l,isRefreshingHistory:x,handleLaunchIde:h,handleSwitchSession:y,handleNewChat:S,handleRefreshHistory:I}}function ou(t,s){if(t.size!==s.size)return!1;for(const[r,n]of t)if(s.get(r)!==n)return!1;return!0}function iu(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function va(t,s){const r=Object.keys(t),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===t[Number(o)])}function qs(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of t)!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 t){if(!r.has(c)||l<=0)continue;const p=o[l];typeof p=="number"&&p>0&&i.set(c,p)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function wa(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function cu(t,s,r){if(s.length===0)return 0;if(typeof r[t]=="number")return r[t];const n=[...s].reverse().find(o=>o<t)??s[0];return r[n]??0}function lu(t,s,r){if(s.length<=1)return[];const n=s.map(c=>t[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 ja(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function ka(t){return Array(t).fill(100/t)}function du({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:p,visibleTabKeys:x}){const m=a.useRef(null),h=a.useMemo(()=>qs(t,x),[t,x]),y=h.assignments,S=a.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),I=S>1,u=a.useCallback((k,f)=>{s(g=>{const w=new Map(qs(g,x).assignments);return f===0?w.delete(k):w.set(k,f),w}),n(g=>({...g,[f]:k})),r(f)},[s,x,n,r]),b=a.useCallback(k=>{s(f=>{const g=qs(f,x).assignments,w=new Map;for(const[j,$]of g)$!==k&&($>k?w.set(j,$-1):w.set(j,$));return w}),c(f=>{if(f.length<=1)return[];const g=[...f];g.splice(k,1);const w=g.reduce((j,$)=>j+$,0);return w>0?g.map(j=>j/w*100):[]}),r(0)},[s,x,c,r]),v=a.useCallback((k,f)=>{f.preventDefault();const g=m.current;if(!g)return;const w=f.clientX,j=g.offsetWidth,$=i.length===S?[...i]:ka(S),D=R=>{const P=(R.clientX-w)/j*100,C=[...$];C[k]=Math.max(15,$[k]+P),C[k+1]=Math.max(15,$[k+1]-P),c(C)},K=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",D),document.addEventListener("mouseup",K)},[i,S,c]),d=a.useCallback((k,f,g)=>{if(S>=4)return;const w=g==="left"?f:f+1;s(j=>{const $=qs(j,x).assignments,D=new Map;for(const K of p){const R=$.get(K.tabKey)??0,z=R>=w?R+1:R;z>0&&D.set(K.tabKey,z)}return w>0&&D.set(k,w),D}),c(j=>{const $=j.length===S?[...j]:ka(S),D=$[f]??100/S,K=Math.max(15,D/2),R=Math.max(15,D/2),z=[...$];z[f]=K,z.splice(w,0,R);const P=z.reduce((C,_)=>C+_,0);return z.map(C=>C/P*100)}),n(j=>{const $=ja(j,w);return $[w]=k,$}),o(j=>{const $=ja(j,w);return $[w]=[k],$}),r(w)},[S,s,x,p,c,n,o,r]);a.useEffect(()=>{ou(t,y)||s(y)},[t,y,s]),a.useEffect(()=>{const{mapping:k,usedGroups:f}=h;n(g=>{const w=wa(g,k);return va(g,w)?g:w}),o(g=>{const w=wa(g,k);return va(g,w)?g:w}),r(g=>{const w=l?0:cu(g,f,k);return g===w?g:w}),c(g=>{const w=l?[]:lu(g,f,h.groupCount);return iu(g,w)?g:w})},[h,l,n,o,r,c]);const N=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const f of p){const g=y.get(f.tabKey)??0,w=Math.min(g,S-1);k[w].push(f)}return k},[p,y,S]),M=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:y,numGroups:S,isSplitMode:I,groupedConvs:N,moveTabToGroup:u,closeGroup:b,handleResizeStart:v,splitTabRelative:d,clearAllSplits:M}}function uu({ides:t,sendDaemonCommand:s}){const r="0.8.48",n=a.useMemo(()=>t.filter(m=>m.type!=="adhdev-daemon"?!1:Lo(m,r)).sort((m,h)=>Number(Is(h,r))-Number(Is(m,r))),[r,t]),o=a.useMemo(()=>n.some(m=>Is(m,r)),[r,n]),[i,c]=a.useState(!1),[l,p]=a.useState({}),x=a.useCallback(async m=>{var h,y;p(S=>({...S,[m]:"upgrading"}));try{const S=await s(m,"daemon_upgrade",{});(h=S==null?void 0:S.result)!=null&&h.upgraded||(y=S==null?void 0:S.result)!=null&&y.success?p(I=>({...I,[m]:"done"})):p(I=>({...I,[m]:"error"}))}catch{p(S=>({...S,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:x}}function Na(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function An(t){return t instanceof Error?t.message:String(t||"")}function Sa(t){const s=An(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ca(t,s){const r=An(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function jr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[l,p]=a.useState(!1),x=a.useRef(!1),m=a.useRef(null),h=a.useCallback(async u=>{if(!s)return;const b=u.trim();if(!b||x.current)return;const v=s.tabKey,d=Date.now(),N=m.current;if(N&&N.tabKey===v&&N.message===b&&d-N.timestamp<2e3)return;x.current=!0,p(!0),m.current={tabKey:v,message:b,timestamp:d};const M=`${d}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:b,timestamp:d,_localId:M},f=!(Xe(s)||Ve(s));f&&r(g=>({...g,[v]:[...g[v]||[],k]}));try{const g=Ds(s);if(!g)return;const w=await t(g,"send_chat",{message:b,...us(s)}),j=Na(w);if(f&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r($=>({...$,[v]:($[v]||[]).filter(D=>D._localId!==M)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const $=Date.now()-6e4;r(D=>{const K=D[v];if(!K)return D;const R=K.filter(z=>z.timestamp>$);return R.length===K.length?D:{...D,[v]:R}})},6e4)}catch(g){const w=An(g);w.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",w):console.error("Send failed",g),f&&r(j=>({...j,[v]:(j[v]||[]).filter($=>$._localId!==M)}))}finally{x.current=!1,p(!1)}},[s,t,r]),y=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),S=a.useCallback(async u=>{if(s)try{const v=(s.modalButtons||[]).indexOf(u),d=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(d),M=Ds(s);if(!M)return;const k=await t(M,"resolve_action",{button:u,action:N?"approve":"reject",...v>=0&&{buttonIndex:v},...us(s)}),f=Na(k);f.success||n(g=>[...g,{routeId:s.tabKey,text:Ca(u,f==null?void 0:f.error),timestamp:Date.now()}])}catch(b){Sa(b)||console.error("[ModalButton] Error:",b),n(v=>[...v,{routeId:s.tabKey,text:Sa(b)?Ca(u,b):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),I=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await t(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:h,handleRelaunch:y,handleModalButton:S,handleFocusAgent:I}}const Tn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:p,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:y,userName:S,scrollToBottomRequestNonce:I,isInputActive:u=!0}){const b=Wo(s),v=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return e.jsxs(e.Fragment,{children:[e.jsx(oo,{activeConv:v,onModalButton:c}),v.transport!=="pty"&&v.transport!=="acp"&&v.cdpConnected===!1?e.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:e.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:[e.jsx("span",{className:"text-sm",children:e.jsx(es,{size:14})}),e.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),e.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,v.transport==="pty"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(wl,{activeConv:v,clearToken:r,terminalRef:i,handleSendChat:p,isSendingChat:x,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(tn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:y,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})})]}):e.jsx(tn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:y,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function pu({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:p,onOpenNativeConversation:x,onOpenMachine:m,onOpenHistory:h,onOpenRemote:y,onHideConversation:S,onStopCli:I,cliViewMode:u,onSetCliViewMode:b,handleSendChat:v,handleFocusAgent:d,handleModalButton:N,handleRelaunch:M}){const k=a.useRef(null),f=Xe(t)&&!s,g=f&&u==="terminal",w=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center justify-between gap-3 ${w} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.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:p,type:"button","aria-label":"Back",children:e.jsx(pn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Qe(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(po,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>x(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[f&&u&&e.jsx(jn,{mode:u,onChange:b,compact:!0}),f&&I&&e.jsx("button",{onClick:()=>{I(t)},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:e.jsx(vt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(fn,{size:14})}),!s&&!f&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(t),type:"button",children:e.jsx(Nt,{size:14})}),S&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(t),type:"button",title:"Close chat",children:e.jsx(vt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Tn,{activeConv:t,clearToken:0,isCliTerminal:g,ideEntry:n,terminalRef:k,handleModalButton:N,handleRelaunch:M,handleSendChat:v,isSendingChat:c,handleFocusAgent:d,isFocusingAgent:l,actionLogs:o,userName:i})})]})}const Kr={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 mu(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Vo(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(mu())},[]);const l=a.useCallback(()=>{navigator.clipboard.writeText(Kr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return e.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:[e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"}),e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="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"})]}),t==="windows"&&e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.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"}),e.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"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:Kr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Kr[c].cmd}),e.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),e.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",e.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Go({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Kt}];return e.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:e.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=t===n;return e.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:[e.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:e.jsx(i,{size:15})}),e.jsx("span",{children:o})]},n)})})})}function Ys({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function cs({children:t,className:s=""}){return e.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:t})}function js({icon:t,title:s,subtitle:r,children:n}){return e.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:[e.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:t}),e.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Xs({item:t,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:p,isConnecting:x}=hs(t.conversation),m=Qe(t.conversation),h=rs(t.conversation),y=yo(t.conversation,{requiresAction:s==="needs_attention"}),S=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",I=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",u=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",d=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return e.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(t.conversation),type:"button",children:[o||i?e.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,e.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${I}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:m}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${d}`,children:ao(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):x?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):y==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:N,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:t.preview})]}),o&&!l&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&e.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&&e.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"})]},t.conversation.tabKey)}function Ia({size:t=32,label:s}){return e.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[e.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:t,height:t}}),s&&e.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function fu({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:p,onShowConversation:x,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:y,onOpenSettings:S,onSectionChange:I,wsStatus:u="connected",isStandalone:b=!1}){const v=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",d=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,M=t==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",f=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return e.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[e.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:M}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[t==="chats"&&(s.length>0||r.length>0)&&e.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:[e.jsx(yr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:e.jsx(br,{size:18})})]})]})}),e.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] ${f}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?e.jsx(js,{icon:e.jsx(Ia,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(js,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your first machine",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!b&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(Vo,{})})}):e.jsx(cs,{children:c.map((g,w)=>e.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(g.id),type:"button",children:[e.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(g.label)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:g.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:g.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[g.unread," new"]}):g.total>0?`${g.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:g.subtitle}),g.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[g.total," chat",g.total!==1?"s":"",g.unread>0?` · ${g.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},g.id))})}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Ys,{title:"Needs attention",className:"mb-0"}),e.jsx(cs,{children:s.map((g,w)=>e.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:e.jsx(Xs,{item:g,type:"needs_attention",getAvatarText:l,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Ys,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(cs,{children:r.map((g,w)=>e.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:e.jsx(Xs,{item:g,type:"task_complete",getAvatarText:l,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Ys,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(cs,{children:n.map((g,w)=>e.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:e.jsx(Xs,{item:g,type:"working",getAvatarText:l,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&e.jsx(Ys,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(cs,{children:o.map((g,w)=>e.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:e.jsx(Xs,{item:g,type:"earlier",getAvatarText:l,onOpenConversation:p})},g.conversation.tabKey))}):N?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?e.jsx(js,{icon:e.jsx(Ia,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):d?e.jsx(js,{icon:e.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:e.jsx(Kt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):e.jsx(js,{icon:e.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."})]}),t==="chats"&&i.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.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:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(cs,{className:"bg-bg-secondary/25",children:i.map((g,w)=>e.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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(g),type:"button",children:[e.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(Qe(g))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Qe(g)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:rs(g)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},g.tabKey))})]})]}),t==="chats"&&h&&e.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:h,"aria-label":"Start new session",children:e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),e.jsx(Go,{section:t,onSectionChange:I})]})}function xu(t){const s=t.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 kr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=xu(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 hu(t){const s=t.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function Nr(t,s,r){const n=await t(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const o=typeof(n==null?void 0:n.path)=="string"?n.path:r,i=o.includes("\\")?"\\":"/",c=(p,x)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${x}`:p==="/"||p==="\\"?`${i}${x}`:`${p.replace(/[\\/]+$/,"")}${i}${x}`,l=Array.isArray(n==null?void 0:n.files)?n.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:c(o,p.name)})).sort((p,x)=>p.name.localeCompare(x.name)):[];return{path:o,directories:l}}function Sr({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:p,onConfirm:x}){const[m,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const y=hu(r),S=m.trim();return e.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:e.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:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[e.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:()=>{!y||o||p(y)},disabled:!y||o,children:[e.jsx(pn,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!S||o||(I.preventDefault(),p(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||o||p(S)},disabled:!S||o,children:"Go"})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?e.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):e.jsx("div",{className:"p-3",children:n.map(I=>e.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:()=>p(I.path),children:[e.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:e.jsx(ps,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:I.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:I.path})]})]},I.path))})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>x(S||r),disabled:!S&&!r||o,children:c})]})]})})}function _n({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:l=!1,showArgsInput:p,argsValue:x,onArgsChange:m,showModelInput:h,modelValue:y,onModelChange:S,historyProviderNode:I,onConfirm:u,onCancel:b}){const v=n==null?void 0:n.find(d=>d.key===o);return e.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:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.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:b,"aria-label":"Close launch confirmation",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),e.jsx("select",{value:o||"",onChange:d=>i(d.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:l,children:n.map(d=>e.jsx("option",{value:d.key,children:d.label},d.key))}),(v==null?void 0:v.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),I,r.map(d=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:d.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:d.value})]},`${d.label}:${d.value}`)),h&&S&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),e.jsx("input",{type:"text",value:y||"",onChange:d=>S(d.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:l})]}),p&&m&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),e.jsx("input",{type:"text",value:x||"",onChange:d=>m(d.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:l})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:l,children:"Cancel"}),e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:u,disabled:l,children:[e.jsx(xn,{size:14}),l?"Launching…":c]})]})]})})}function Ma(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Zt(t){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=t,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const p of s.workspaces||[])i.push({key:`saved:${p.id}`,label:`${p.id===s.defaultWorkspaceId?"⭐ ":""}${Ma(p.path,p.label)}`,description:p.path,workspaceId:p.id,workspacePath:p.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(p=>p.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:Ma(c),description:c,workspaceId:null,workspacePath:c}),n){const p=`saved:${n}`;if(i.some(x=>x.key===p))return{options:i,selectedKey:p}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Wr(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function bu({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ge,F,me,Ce;const c=Ks(),[l,p]=a.useState(!1),x=(((ge=t.detectedIdes)==null?void 0:ge.length)||0)>0,m=a.useMemo(()=>(t.workspaces||[]).map(xe=>({id:xe.id,path:xe.path,label:xe.label})),[t]),h=t.defaultWorkspaceId||null,[y,S]=a.useState(h||((F=m[0])==null?void 0:F.id)||""),[I,u]=a.useState(""),[b,v]=a.useState(""),[d,N]=a.useState([]),[M,k]=a.useState(!1),[f,g]=a.useState(""),[w,j]=a.useState(!1),[$,D]=a.useState(Wr(x,s.length,r.length)),K=a.useRef(null),[R,z]=a.useState(null),P=a.useRef("__home__"),[C,_]=a.useState("__home__"),[G,T]=a.useState(""),[E,H]=a.useState(""),[se,Y]=a.useState(""),[oe,je]=a.useState([]),[V,ae]=a.useState(!1),[W,be]=a.useState(!1),X=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const J=y==="__custom__"?I.trim():((me=m.find(xe=>xe.id===y))==null?void 0:me.path)||"",ie=y==="__custom__"&&!!J&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ne=y!=="__custom__"&&((Ce=m.find(xe=>xe.id===y))==null?void 0:Ce.path)||"",he=a.useCallback(async xe=>{k(!0),g("");try{const Le=await o(xe);v(Le.path),u(Le.path),N(Le.directories)}catch(Le){g(Le instanceof Error?Le.message:"Could not load folder")}finally{k(!1)}},[o]),ue=a.useCallback(()=>{var Le,Be;S("__custom__"),j(!0);const xe=kr(t.platform,[I.trim(),ne,(Le=m.find(Fe=>Fe.id===h))==null?void 0:Le.path,(Be=m[0])==null?void 0:Be.path]);he(xe)},[I,h,he,ne,t.platform,m]),fe=a.useCallback(xe=>{if(xe!=null&&xe.workspaceId){S(xe.workspaceId),u("");return}if(xe!=null&&xe.workspacePath){S("__custom__"),u(xe.workspacePath);return}S(""),u("")},[]),te=a.useCallback(xe=>{if(S(xe),xe==="__custom__"){ue();return}u("")},[ue]),pe=a.useCallback(xe=>{S("__custom__"),u(xe)},[]),de=a.useCallback((xe,Le)=>{K.current=Le,P.current=xe.selectedWorkspaceKey||"__home__",_(xe.selectedWorkspaceKey||"__home__"),T(xe.initialArgs||""),H(xe.initialModel||""),Y(""),je([]),z(xe),xe.providerType&&i&&(ae(!0),i(xe.providerType).then(Be=>je(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>ae(!1)))},[i]),ye=a.useCallback(()=>{K.current&&(be(!0),K.current().finally(()=>{K.current=null,be(!1),z(null)}))},[]),we=a.useCallback(()=>{K.current=null,z(null)},[]),L=a.useCallback(xe=>{P.current=xe,_(xe)},[]);return a.useEffect(()=>{var xe;X.current!==t.id&&(X.current=t.id,S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"),u(""),v(""),N([]),g(""),j(!1),D(Wr(x,s.length,r.length)))},[r.length,s.length,h,x,t.id,m]),a.useEffect(()=>{var xe;y!=="__custom__"&&(y&&m.some(Le=>Le.id===y)||S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"))},[h,y,m]),a.useEffect(()=>{$==="ide"&&x||$==="cli"&&s.length>0||$==="acp"&&r.length>0||D(Wr(x,s.length,r.length))},[$,r.length,s.length,x]),{showAllRecent:l,setShowAllRecent:p,hasIdeOptions:x,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:y,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:d,browseBusy:M,browseError:f,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:R,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:C,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:se,launchConfirmSavedSessions:oe,launchConfirmSessionsLoading:V,launchConfirmBusy:W,resolvedWorkspacePath:J,canCreateMissingWorkspace:ie,openBrowseDialog:ue,loadBrowsePath:he,handleWorkspaceChoiceChange:te,chooseCustomWorkspacePath:pe,setCustomWorkspacePath:u,setBrowseDialogOpen:j,setActiveLauncherKind:D,openLaunchConfirm:de,handleConfirmLaunch:ye,closeLaunchConfirm:we,setWorkspaceSelectionFromOption:fe,setLaunchConfirmWorkspaceKeyAndSync:L,setLaunchConfirmArgs:T,setLaunchConfirmModel:H,setLaunchConfirmResumeId:Y}}function gu({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:p,section:x,showBottomNav:m,onBack:h,onSectionChange:y,onOpenConversation:S,onOpenRecent:I,onOpenMachineDetails:u,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:d,onBrowseDirectory:N,onLaunchWorkspaceProvider:M,onListSavedSessions:k}){const f=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",g=r.slice(0,4),w=s.slice(0,3),j=bu({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:l,onBrowseDirectory:N,onListSavedSessions:k}),$=a.useMemo(()=>g.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${f(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:_,selectedKey:G}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:C.workspace});j.openLaunchConfirm({title:`Launch ${C.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:_,selectedWorkspaceKey:G,details:[{label:"Mode",value:f(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const T=_.find(E=>E.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(T),await I({...C,workspace:(T==null?void 0:T.workspacePath)??null})})}})),[j,I,g]),D=a.useMemo(()=>w.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:Qe(C.conversation),secondary:bl(C.conversation,{timestampLabel:C.timestamp?ao(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,w]),K=j.showAllRecent?$:$.slice(0,4),R=$.length>0,z=D.length>0,P=p?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.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:h,type:"button","aria-label":"Back",children:e.jsx(pn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(t,{fallbackId:t.id})}),e.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[t.platform||"machine",t.version?` · v${t.version}`:""]})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[z&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(C=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),R&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:K.map(C=>e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),$.length>4&&e.jsx("div",{className:"flex justify-center px-4 pt-2",children:e.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:()=>j.setShowAllRecent(C=>!C),children:j.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||o.length>0)&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:e.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:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),e.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),e.jsx("select",{value:j.workspaceChoice,onChange:C=>j.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:j.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[j.workspaceRows.map(C=>e.jsxs("option",{value:C.id,children:[C.id===j.defaultWorkspaceId?"⭐ ":"",vr(C.path,C.label)||C.path]},C.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.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:e.jsx(ps,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.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:j.openBrowseDialog,children:"Select workspace…"}),e.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:()=>{j.resolvedWorkspacePath&&d(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&e.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[e.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(C=>e.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:_,selectedKey:G}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:_,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const T=_.find(E=>E.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(T),v(C.type,{workspacePath:(T==null?void 0:T.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(j.activeLauncherKind==="cli"?n:o).map(C=>e.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 _=j.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:T}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${_.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:T,details:[{label:"Mode",value:_.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:_==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const E=G.find(H=>H.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(E),M(_,C.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&e.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,j.canCreateMissingWorkspace&&e.jsx("div",{className:"mt-2",children:e.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:()=>d(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&e.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:b,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&e.jsx(Sr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:C=>{j.loadBrowsePath(C)},onConfirm:C=>{j.chooseCustomWorkspacePath(C),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(_n,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.confirmLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),j.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:j.launchConfirmResumeId,onChange:C=>j.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),j.launchConfirmSavedSessions.map(C=>e.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),m&&e.jsx(Go,{section:x,onSectionChange:y})]})}function qo(t){var r;const s=((r=t.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function yu(t,s){if(!t)return[];const r=t.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:n.currentModel||n.workspace||void 0,workspace:n.workspace,currentModel:n.currentModel})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===t.id).map(n=>{var i,c,l,p,x;const o=Rs(n)?"cli":ds(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Rs(n)?n.cliName||n.type:ds(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ds(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((x=(p=(l=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:l.at)==null?void 0:p.call(l,-1))==null?void 0:x.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function vu(t,s){const r=new Map;for(const n of s){const o=zt(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return t.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((h,y)=>y.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=en(n),p=o.filter(h=>h.unread||h.requiresAction).length,x=qo(n),m=[n.platform||"machine",x].filter(Boolean);return{id:n.id,label:kt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:p,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?gl(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 Js(t,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] ${t}`,s)}catch{}}function wu({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:p,onRequestedActiveTabConsumed:x,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:y,onRequestedMobileSectionConsumed:S,setSelectedTabKey:I,setScreen:u,setSelectedMachineId:b,setSection:v,setMachineBackTarget:d,resetMachineAction:N}){const M=a.useRef(null),k=a.useCallback(f=>{if(!(f!=null&&f.sessionId))return;const g=Ps(f,c),w=Math.max(Date.now(),Ht(f),g.lastUpdated||0);Js("mark_read:start",{tabKey:f.tabKey,sessionId:f.sessionId,displayPrimary:Qe(f),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:Ht(f),readAt:w}),l(zt(f)||f.routeId,"mark_session_seen",{sessionId:f.sessionId,seenAt:w}).then(j=>{Js("mark_read:result",{tabKey:f.tabKey,sessionId:f.sessionId,result:j})}).catch(j=>{Js("mark_read:error",{tabKey:f.tabKey,sessionId:f.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,l]);return a.useEffect(()=>{var g;if(!n){u("inbox"),I(((g=t[0])==null?void 0:g.tabKey)||null),M.current=null;return}if(i!=="chat"){M.current=null;return}const f=`${n.tabKey}:${n.sessionId||""}`;M.current!==f&&(M.current=f,k(n))},[t,k,i,n,u,I]),a.useEffect(()=>{if(!p)return;const f=t.find(g=>g.tabKey===p);f&&(I(f.tabKey),u("chat"),x==null||x())},[t,x,p,u,I]),a.useEffect(()=>{if(!m)return;const f=s.find(g=>g.id===m);f&&(b(f.id),N(),v("machines"),d("inbox"),u("machine"),h==null||h())},[s,h,m,N,d,u,v,b]),a.useEffect(()=>{y&&(v(y),u("inbox"),S==null||S())},[S,y,u,v]),a.useEffect(()=>{const f=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);f.length!==0&&Js("inbox_state",{screen:i,selectedTabKey:o,items:f.map(g=>{const w=Ps(g.conversation,c);return{liveState:w,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:Qe(g.conversation),serverBucket:w.inboxBucket,computedBucket:g.inboxBucket,serverUnread:w.unread,computedUnread:g.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:Ht(g.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function ju(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Aa(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ku(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Nu({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,l]=a.useState(""),[p,x]=a.useState(null),m=a.useCallback(()=>{i("idle"),l(""),x(null)},[]),h=a.useCallback(async(d,N,M)=>{var k;try{i("loading"),l(`Launching ${N}…`);const f={ideType:N,enableCdp:!0};(k=M==null?void 0:M.workspacePath)!=null&&k.trim()&&(f.workspace=M.workspacePath.trim()),await t(d,"launch_ide",f),i("done"),l(`${N} launch requested`)}catch(f){i("error"),l(f instanceof Error?f.message:"Launch IDE failed"),console.error("Launch IDE failed",f)}},[t]),y=a.useCallback(async(d,N,M)=>{if(N.trim())try{i("loading"),l(M!=null&&M.createIfMissing?"Creating folder…":"Saving workspace…");const k=await t(d,"workspace_add",{path:N.trim(),createIfMissing:(M==null?void 0:M.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(M!=null&&M.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[t]),S=a.useCallback(async d=>{var N,M,k,f,g,w;try{i("loading"),l("Starting daemon upgrade…");const j=await t(d,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((M=j==null?void 0:j.result)==null?void 0:M.version)||"latest"}.`);return}if((k=j==null?void 0:j.result)!=null&&k.upgraded||(f=j==null?void 0:j.result)!=null&&f.success){i("done"),l(`Upgrade to v${((g=j==null?void 0:j.result)==null?void 0:g.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=j==null?void 0:j.result)==null?void 0:w.error)||"Upgrade failed")}catch(j){i("error"),l(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(d,N,M,k)=>{var w,j,$;const f=Date.now(),g={machineId:d,kind:N,providerType:M,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:f};try{i("loading"),l(`Launching ${M}…`),x(g);const D={cliType:M};(w=k==null?void 0:k.workspacePath)!=null&&w.trim()?D.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(D.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(D.resumeSessionId=k.resumeSessionId),(j=k==null?void 0:k.args)!=null&&j.trim()&&(D.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),($=k==null?void 0:k.model)!=null&&$.trim()&&(D.initialModel=k.model.trim());const K=await t(d,"launch_cli",D),R=(K==null?void 0:K.result)||K,z=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(K!=null&&K.success&&z){x(null),i("done"),l(`${M} launched`),s(`/dashboard?activeTab=${encodeURIComponent(z)}`);return}if(K!=null&&K.success){i("loading"),l(`${M} launch requested — waiting for session…`);return}x(null),i("error"),l((K==null?void 0:K.error)||(R==null?void 0:R.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(D){if(ku(D)){i("loading"),l(`${M} launch requested — waiting for session…`);return}x(null),i("error"),l(D instanceof Error?D.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,t]),u=a.useCallback(async(d,N)=>{try{const M=await t(d,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(M==null?void 0:M.result)??M;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(M){return console.error("Failed to list saved sessions on mobile:",M),[]}},[t]),b=a.useCallback(async(d,N)=>Nr(t,d,N),[t]);a.useEffect(()=>{var k;if(!p)return;const d=Aa(p.workspacePath),N=r.find(f=>{var K,R,z,P;if(!f||f.type==="adhdev-daemon"||ju(f.daemonId||f.id)!==p.machineId||(f.transport==="acp"?"acp":f.transport==="pty"?"cli":null)!==p.kind||String(f.agentType||f.type||"")!==p.providerType)return!1;const $=String(f.providerSessionId||"");if(p.resumeSessionId&&$)return $===p.resumeSessionId;if(d){const C=Aa(f.workspace||f.runtimeWorkspaceLabel);return C?C===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((P=(z=(R=(K=f.activeChat)==null?void 0:K.messages)==null?void 0:R.at)==null?void 0:z.call(R,-1))==null?void 0:P.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const M=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(k=n.find(f=>f.routeId===N.id))==null?void 0:k.sessionId;M&&(x(null),i("done"),l(`${p.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(M)}`))},[n,r,s,p]),a.useEffect(()=>{if(!p)return;const d=window.setTimeout(()=>{x(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(d)},[p]);const v=a.useCallback(async(d,N)=>{if(N.kind==="ide"&&N.providerType){await h(d,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await I(d,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:y,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:I,handleListSavedSessions:u,handleBrowseDirectory:b,handleOpenRecent:v}}function Su({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:p,setMachineBackTarget:x}){const m=a.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=a.useCallback(v=>{const d=t.find(N=>N.routeId===v.routeId&&N.streamSource==="native");d&&(i(d.tabKey),c("chat"),n(d))},[t,n,c,i]),y=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((v,d="inbox")=>{l(v),o(),p("machines"),x(d),c("machine")},[o,x,c,p,l]),I=a.useCallback(v=>{const d=zt(v);d&&S(d,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(v=>{p(v),c("inbox")},[c,p]);return{openConversation:m,openNativeConversation:h,backFromConversation:y,openMachine:S,openConversationMachine:I,backFromMachine:u,changeMachineSection:b}}function Cu(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function Iu(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Zs(t){return[...t].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Mu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:p,requestedActiveTabKey:x,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:u,onOpenRemote:b,onStopCli:v,wsStatus:d,isConnected:N,onShowHiddenConversation:M,onShowAllHiddenConversations:k,onHideConversation:f,onOpenNewSession:g}){const[w,j]=a.useState(()=>{var F;return((F=t[0])==null?void 0:F.tabKey)||null}),[$,D]=a.useState(()=>t[0]?"chat":"inbox"),[K,R]=a.useState("chats"),[z,P]=a.useState(null),[C,_]=a.useState("inbox"),G=fs(),T="0.8.48",E=a.useMemo(()=>t.find(F=>F.tabKey===w)||t[0]||null,[t,w]),H=a.useMemo(()=>E?r.find(F=>F.id===E.routeId):void 0,[r,E]),se=a.useMemo(()=>!E||Ve(E)||!Xe(E)?null:ms(E),[E]),Y=a.useMemo(()=>r.filter(F=>F.type==="adhdev-daemon").sort(gn),[r]),oe=a.useMemo(()=>Y.find(F=>F.id===z)||null,[Y,z]),je=a.useMemo(()=>$s(r),[r]),V=jr({sendDaemonCommand:o,activeConv:E||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ae=Nu({sendDaemonCommand:o,navigate:G,ides:r,conversations:t}),W=a.useMemo(()=>t.map(F=>{const me=$==="chat"&&(E==null?void 0:E.tabKey)===F.tabKey,Ce=Ls(F,je,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),xe=Ht(F),Le=go(F);return{conversation:F,timestamp:xe,preview:Le,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[t,je,$,E]),{markConversationRead:be}=wu({conversations:t,machineEntries:Y,items:W,selectedConversation:E,selectedTabKey:w,screen:$,liveSessionInboxState:je,sendDaemonCommand:o,requestedActiveTabKey:x,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:y,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:D,setSelectedMachineId:P,setSection:R,setMachineBackTarget:_,resetMachineAction:ae.resetMachineAction}),X=Su({conversations:t,selectedConversation:E,machineBackTarget:C,markConversationRead:be,resetMachineAction:ae.resetMachineAction,setSelectedTabKey:j,setScreen:D,setSelectedMachineId:P,setSection:R,setMachineBackTarget:_}),J=a.useMemo(()=>Zs(W.filter(F=>F.requiresAction)),[W]),ie=a.useMemo(()=>Zs(W.filter(F=>F.unread&&!F.requiresAction)),[W]),ne=a.useMemo(()=>Zs(W.filter(F=>!F.unread&&!F.requiresAction&&F.isWorking)),[W]),he=a.useMemo(()=>Zs(W.filter(F=>!F.unread&&!F.requiresAction&&!F.isWorking)),[W]),ue=a.useMemo(()=>oe?W.filter(F=>zt(F.conversation)===oe.id):[],[W,oe]),fe=a.useMemo(()=>yu(oe,r),[r,oe]),te=(oe==null?void 0:oe.version)||null,pe=!!oe&&!!te&&!0&&te!==T,de=a.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),ye=a.useMemo(()=>de.filter(F=>F.category==="cli"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[de]),we=a.useMemo(()=>de.filter(F=>F.category==="acp"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[de]),L=a.useMemo(()=>vu(Y,W),[W,Y]),ge=a.useCallback(async F=>{oe&&await ae.handleOpenRecent(oe.id,F)},[ae,oe]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&E?e.jsx(pu,{selectedConversation:E,isAcp:Ve(E),isStandalone:l,selectedIdeEntry:H,actionLogs:n,userName:p,isSendingChat:V.isSendingChat,isFocusingAgent:V.isFocusingAgent,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,onBack:X.backFromConversation,onOpenNativeConversation:X.openNativeConversation,onOpenMachine:X.openConversationMachine,onHideConversation:f,onOpenHistory:u,onOpenRemote:b,onStopCli:v,cliViewMode:se,onSetCliViewMode:async F=>{if(E&&se!==F)try{await o(zt(E)||E.routeId,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:jt(E),mode:F})}catch(me){Iu(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},handleSendChat:V.handleSendChat,handleFocusAgent:V.handleFocusAgent}):$==="machine"&&oe?e.jsx(gu,{selectedMachineEntry:oe,selectedMachineConversations:ue,selectedMachineRecentLaunches:fe,cliProviders:ye,acpProviders:we,selectedMachineNeedsUpgrade:pe,appVersion:T,machineAction:ae.machineAction,isStandalone:l,section:K,showBottomNav:C==="inbox",onBack:X.backFromMachine,onSectionChange:X.changeMachineSection,onOpenConversation:X.openConversation,onOpenRecent:ge,onOpenMachineDetails:()=>G(`/machines/${oe.id}`),onMachineUpgrade:()=>ae.handleMachineUpgrade(oe.id),onLaunchDetectedIde:(F,me)=>ae.handleLaunchDetectedIde(oe.id,F,me),onAddWorkspace:(F,me)=>ae.handleAddWorkspace(oe.id,F,me),onBrowseDirectory:F=>ae.handleBrowseDirectory(oe.id,F),onLaunchWorkspaceProvider:(F,me,Ce)=>ae.handleLaunchWorkspaceProvider(oe.id,F,me,Ce),onListSavedSessions:F=>ae.handleListSavedSessions(oe.id,F)}):e.jsx(fu,{section:K,attentionItems:J,unreadItems:ie,workingItems:ne,completedItems:he,hiddenConversations:s,machineCards:L,getAvatarText:Cu,onOpenConversation:X.openConversation,onShowConversation:M,onShowAllHidden:k,onOpenNewSession:g,onOpenMachine:X.openMachine,onOpenSettings:()=>G("/settings"),onSectionChange:R,wsStatus:d,isConnected:N,isStandalone:l})})}function Or(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Au({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[l,p]=a.useState(!1),[x,m]=a.useState(null),h=a.useCallback(()=>{c.current=0,p(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const y=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,p(!0))},[]),S=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Or(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),d=b.clientX-v.left,N=v.width/3;d<N?m("split-left"):d>N*2?m("split-right"):m("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,p(!1),m(null))},[]),u=a.useCallback(b=>{c.current=0,p(!1);const v=b.dataTransfer.getData("text/tab-key"),d=v?t.some(M=>M.tabKey===v):!1,N=x;if(m(null),i(),!!v){if(b.preventDefault(),N==="split-left"&&Or(s,r)){r==null||r(v,"split-left");return}if(N==="split-right"&&Or(s,r)){r==null||r(v,"split-right");return}if(d){o(v);return}n==null||n(v)}},[t,x,s,r,n,o,i]);return{dragOver:l,dropAction:x,resetDragState:h,handleDragEnter:y,handleDragOver:S,handleDragLeave:I,handleDrop:u}}function Tu(t,s){const r=new Set(s.map(i=>i.tabKey)),n=t.filter(i=>r.has(i)),o=s.filter(i=>!t.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function _u({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[l,p]=a.useState(r??[]),[x,m]=a.useState(null),h=a.useRef(null),y=a.useRef(null),S=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{p(g=>{const w=Tu(g,t);return w.length===g.length&&w.every((j,$)=>j===g[$])?g:w})},[t]);const u=a.useMemo(()=>{const g=x??l;if(g.length===0)return t;const w=new Map(g.map((j,$)=>[j,$]));return[...t].sort((j,$)=>{const D=w.get(j.tabKey)??999,K=w.get($.tabKey)??999;return D-K})},[t,x,l]);a.useEffect(()=>{var w,j;if(u.length===0){i!==null&&(c(null),(w=S.current)==null||w.call(S,null));return}if(i&&u.some($=>$.tabKey===i))return;const g=u[0].tabKey;g!==i&&(c(g),(j=S.current)==null||j.call(S,g))},[u,i]);const b=a.useMemo(()=>u.find(g=>g.tabKey===i),[u,i]),v=a.useCallback(g=>{var w;c(g),(w=S.current)==null||w.call(S,g)},[]),d=a.useCallback((g,w,j)=>{p($=>{var z;const D=$.filter(P=>P!==g),K=D.indexOf(w);if(K<0)return $;const R=j==="left"?K:K+1;return D.splice(R,0,g),(z=I.current)==null||z.call(I,D),D}),m(null)},[]),N=a.useCallback((g,w,j)=>{const D=(l.length>0?l:t.map(z=>z.tabKey)).filter(z=>z!==g),K=D.indexOf(w);if(K<0)return;const R=j==="left"?K:K+1;D.splice(R,0,g),h.current=D,m(D)},[l,t]),M=a.useCallback(()=>{var w;const g=h.current;g&&(p(g),(w=I.current)==null||w.call(I,g))},[]),k=a.useCallback(()=>{h.current=null,m(null)},[]),f=a.useCallback(g=>{p(w=>{var $;const j=w.filter(D=>D!==g);return j.push(g),($=I.current)==null||$.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:u,previewOrderRef:h,draggingTabRef:y,selectTab:v,handleTabReorder:d,updatePreviewOrder:N,commitPreviewOrder:M,clearPreviewOrder:k,moveTabToEnd:f,setDraggingTabKey:g=>{y.current=g}}}function Pu({dropAction:t,canSplit:s}){return e.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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"})}),e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:e.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"})}),e.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="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:e.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 Pn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,l=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",p=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 the ADHDev daemon and link your dashboard to start.";return t===0&&!s&&o&&i?e.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[e.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),e.jsxs("div",{className:"text-center max-w-lg",children:[e.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:l}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&e.jsx(Vo,{}),r&&o.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Detected IDEs"}),e.jsx("div",{className:"flex flex-wrap gap-2.5 justify-center mt-1",children:o.map(x=>e.jsxs("button",{className:"btn btn-sm bg-accent/10 border border-accent/25 text-accent text-xs font-medium px-4 py-2.5 rounded-lg cursor-pointer flex items-center gap-2 transition-all hover:bg-accent/20 hover:scale-105 active:scale-95",onClick:()=>i(x.type),children:[e.jsx(to,{size:14,className:"opacity-70"})," Open ",x.name]},x.type))})]}),c&&e.jsx("div",{className:"mt-8",children:e.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 →"})})]})]}):e.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const Yo="adhdev-tab-shortcuts";function Xo(){try{return JSON.parse(localStorage.getItem(Yo)||"{}")}catch{return{}}}function Jo({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>Xo()),[l,p]=a.useState(null),x=a.useCallback(h=>{const y=[];return h.metaKey&&y.push(o?"⌘":"Meta"),h.ctrlKey&&y.push("Ctrl"),h.altKey&&y.push(o?"⌥":"Alt"),h.shiftKey&&y.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(y.push(h.key.length===1?h.key.toUpperCase():h.key),y.join("+"))},[o]),m=a.useCallback(h=>{c(h);try{localStorage.setItem(Yo,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!l)return;const h=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){p(null);return}const S=x(y);if(!S)return;const I={...i};for(const[u,b]of Object.entries(I))b===S&&delete I[u];I[l]=S,m(I),p(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,l,i,m,x]),a.useEffect(()=>{if(!t)return;const h=y=>{if(!(!y.ctrlKey&&!y.metaKey&&!y.altKey)){for(const[S,I]of Object.entries(i))if(s.includes(S)&&x(y)===I){y.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,x]),{isMac:o,tabShortcuts:i,shortcutListening:l,setShortcutListening:p,saveShortcuts:m}}const Lu=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:p,onSelectTab:x,onConversationActivated:m,onPreviewReorder:h,onReorderTab:y,onCommitPreviewOrder:S,onClearPreviewOrder:I,onDragStateReset:u,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:d,longPressTimer:N,isGroupActive:M}){const k=hs(s),f=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",g=k.isReconnecting,w=a.useCallback(_=>{l.current=s.tabKey,b(s.tabKey),_.dataTransfer.setData("text/tab-key",s.tabKey),_.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),j=a.useCallback(()=>{l.current=null,b(null),S(),I(),u()},[l,b,S,I,u]),$=a.useCallback(_=>{const G=l.current;if(!(!G||G===s.tabKey)&&_.dataTransfer.types.includes("text/tab-key")){_.preventDefault(),_.stopPropagation();const T=_.currentTarget.getBoundingClientRect(),E=_.clientX<T.left+T.width/2?"left":"right";h(G,s.tabKey,E)}},[s.tabKey,l,h]),D=a.useCallback(_=>{_.preventDefault(),_.stopPropagation();const G=_.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const T=_.currentTarget.getBoundingClientRect(),E=_.clientX<T.left+T.width/2?"left":"right";c.includes(G)?y(G,s.tabKey,E):v&&v(G)}I()},[s.tabKey,c,y,v,I]),K=a.useCallback(_=>{_.stopPropagation(),p(),x(s.tabKey),m(s)},[s,m,p,x]),R=a.useCallback(_=>{_.preventDefault(),d(_.clientX,_.clientY,s.tabKey)},[s.tabKey,d]),z=a.useCallback(_=>{const G=_.touches[0];N.current=setTimeout(()=>{d(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,N,d]),P=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",f,r&&"is-active",M&&"is-group-active",g&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:w,onDragEnd:j,onDragOver:$,onDrop:D,onClick:K,onContextMenu:R,onTouchStart:z,onTouchEnd:P,onTouchMove:P,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?e.jsx("div",{className:"tab-spinner"}):k.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Qe(s),children:Qe(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(s)}):k.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Yt(s),e.jsx("span",{className:"connecting-dots"})]}):Yt(s)})]}),i&&e.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})]})},(t,s)=>t.conv===s.conv&&t.isActive===s.isActive&&t.isDraggedTab===s.isDraggedTab&&t.isTaskCompleteUnread===s.isTaskCompleteUnread&&t.shortcut===s.shortcut&&t.conversationKeys===s.conversationKeys&&t.isGroupActive===s.isGroupActive);function Ru({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:p,onReorderTab:x,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:S,onReceiveTab:I,onHideTab:u,isGroupActive:b,allowTabShortcuts:v=!0}){const[d,N]=a.useState(null),M=a.useRef(null),k=a.useRef(null),f=a.useMemo(()=>t.map(R=>R.tabKey),[t]);Es("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(d==null?void 0:d.tabKey)||null});const{isMac:g,tabShortcuts:w,shortcutListening:j,setShortcutListening:$,saveShortcuts:D}=Jo({enabled:v,sortedTabKeys:t.map(R=>R.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!d)return;const R=z=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(z.target)||N(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[d]),a.useEffect(()=>{const R=k.current;if(!R)return;const z=P=>{Math.abs(P.deltaY)>Math.abs(P.deltaX)&&(P.preventDefault(),R.scrollLeft+=P.deltaY)};return R.addEventListener("wheel",z,{passive:!1}),()=>R.removeEventListener("wheel",z)},[]);const K=a.useCallback((R,z,P)=>{N({x:R,y:z,tabKey:P})},[]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:e.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(R=>e.jsx(Lu,{conv:R,isActive:s===R.tabKey,isDraggedTab:o.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:v?w[R.tabKey]:void 0,conversationKeys:f,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:p,onReorderTab:x,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:y,onDragTabKeyChange:S,onReceiveTab:I,onOpenContextMenu:K,longPressTimer:M,isGroupActive:b},R.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),d&&e.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:d.x,top:d.y},children:[v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:R=>{R.stopPropagation(),$(d.tabKey),N(null)},children:["⌨ ",w[d.tabKey]?`Change shortcut (${w[d.tabKey]})`:"Set shortcut"]}),w[d.tabKey]&&e.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 R={...w};delete R[d.tabKey],D(R),N(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(d.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&j&&e.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:()=>$(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",g?"⌘+1":"Ctrl+1",", ",g?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Du({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:p,userName:x,groupIndex:m,onFocus:h,isSplitMode:y,numGroups:S,onMoveTab:I,onReceiveTab:u,style:b,detectedIdes:v,handleLaunchIde:d,onActiveTabChange:N,initialActiveTabId:M,initialTabOrder:k,onTabOrderChange:f,onHideTab:g,isFocused:w,allowTabShortcuts:j=!0}){const{sendCommand:$}=St(),D=a.useRef(null),{activeTabId:K,activeConv:R,sortedConversations:z,draggingTabRef:P,selectTab:C,handleTabReorder:_,updatePreviewOrder:G,commitPreviewOrder:T,clearPreviewOrder:E,moveTabToEnd:H,setDraggingTabKey:se}=_u({conversations:t,initialActiveTabId:M,initialTabOrder:k,onActiveTabChange:N,onTabOrderChange:f}),Y=jr({sendDaemonCommand:o,activeConv:R,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:oe,dropAction:je,resetDragState:V,handleDragEnter:ae,handleDragOver:W,handleDragLeave:be,handleDrop:X}=Au({conversations:t,numGroups:S,onMoveTab:I,onReceiveTab:u,onOwnTabDrop:H,onClearPreviewOrder:E}),J=R&&!Ve(R)&&ms(R)==="terminal",ie=a.useMemo(()=>R?s.find(te=>te.id===R.routeId):void 0,[s,R]),ne=a.useMemo(()=>R?n.filter(te=>te.routeId===R.tabKey):[],[n,R]),he=a.useMemo(()=>$s(s),[s]),ue=a.useMemo(()=>new Set(z.filter(te=>Pc(te,he,{isOpenConversation:te.tabKey===K})).map(te=>te.tabKey)),[K,he,z]);Es("PaneGroup",{groupIndex:m,conversationCount:t.length,activeTabId:K,dragOver:oe});const fe=a.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&$(te.routeId,"focus_session",{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[$]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:oe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(Ru,{conversations:z,activeTabId:K,groupIndex:m,numGroups:S,unreadTabKeys:ue,draggingTabRef:P,onFocus:h,onSelectTab:C,onConversationActivated:fe,onPreviewReorder:G,onReorderTab:_,onCommitPreviewOrder:T,onClearPreviewOrder:E,onDragStateReset:V,onDragTabKeyChange:se,onMoveTab:I,onReceiveTab:u,onHideTab:g,isGroupActive:w??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ae,onDragOver:W,onDragLeave:be,onDrop:X,children:[oe&&e.jsx(Pu,{dropAction:je,canSplit:!!(S<4&&I)}),R?e.jsx(Tn,{activeConv:R,clearToken:r[R.tabKey]||0,isCliTerminal:!!J,ideEntry:ie,terminalRef:D,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ne,userName:x,isInputActive:!y||!!w}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Pn,{conversationsCount:t.length,isSplitMode:y,isStandalone:l,hasRegisteredMachines:p,detectedIdes:v,handleLaunchIde:d})})]})]})}function Eu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:p,setLocalUserMessages:x,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:S,focusedGroup:I,setFocusedGroup:u,moveTabToGroup:b,splitTabRelative:v,closeGroup:d,handleResizeStart:N,detectedIdes:M,handleLaunchIde:k,groupActiveTabIds:f,setGroupActiveTabIds:g,groupTabOrders:w,setGroupTabOrders:j,toggleHiddenTab:$,allowTabShortcuts:D=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((K,R)=>{const z=s&&n.length===r?`${n[R]}%`:void 0;return e.jsxs(et.Fragment,{children:[s&&R>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:P=>N(R-1,P),onDoubleClick:()=>d(R),title:"Drag to resize · Double-click to merge",children:e.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),e.jsx(Du,{style:s?{flexBasis:z??`${100/r}%`,flexGrow:z?0:1,flexShrink:z?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:p,setLocalUserMessages:x,setActionLogs:m,isStandalone:h,hasRegisteredMachines:y,userName:S,groupIndex:R,isFocused:s&&I===R,onFocus:()=>u(R),isSplitMode:s,numGroups:r,onMoveTab:(P,C)=>{C==="left"&&R>0?b(P,R-1):C==="right"&&R<r-1?b(P,R+1):C==="split-left"&&r<4?v(P,R,"left"):C==="split-right"&&r<4&&v(P,R,"right")},onReceiveTab:P=>b(P,R),detectedIdes:R===0?M:void 0,handleLaunchIde:R===0?k:void 0,onActiveTabChange:P=>g(C=>(C[R]??null)===(P??null)?C:{...C,[R]:P}),initialActiveTabId:f[R],initialTabOrder:w[R],onTabOrderChange:P=>j(C=>{const _=C[R]||[];return _.length===P.length&&_.every((G,T)=>G===P[T])?C:{...C,[R]:P}}),onHideTab:$,allowTabShortcuts:D})]},R)})})}function Zo({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,l]=a.useState(null);a.useEffect(()=>t?tt.onScreenshot("ide-page",(m,h)=>{if(m!==t)return;const y=new FileReader;y.onload=()=>i(y.result),y.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var m;return t?((m=tt.onStatus)==null?void 0:m.call(tt,(h,y)=>{h===t&&y!=null&&y.screenshotUsage&&l(y.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const x=t?tt.get(t):null;if(!(!x||r!=="connected"))return n!=="chat"&&s?x.startScreenshots(s):x.stopScreenshots(s),()=>{x.stopScreenshots(s)}},[n,r,s,t]);const p=a.useCallback(async(x,m)=>{const h=t?tt.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(x,m,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:p}}const Qo="adhdev-dashboard-action-shortcuts",$u=1200,Bu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Ku(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(t,s){switch(t){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 ei(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",t)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",t)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",t)},{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",t)},{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",t)},{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",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",t)}]}function ln(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function xr(t){const s=Object.fromEntries(ei(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Qo)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Bu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function ti(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Wu({enabled:t=!0,onTrigger:s}){const r=Ku(),[n,o]=a.useState(()=>xr(r)),[i,c]=a.useState(null),[l,p]=a.useState([]),x=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const b=[];return u.metaKey&&b.push(r?"⌘":"Meta"),u.ctrlKey&&b.push("Ctrl"),u.altKey&&b.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(b.push(ti(u.key)),b.join("+"))},[r]),h=a.useCallback(u=>{o(u);try{localStorage.setItem(Qo,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=xr(r),b=Object.entries(n),v=Object.entries(u);b.length===v.length&&b.every(([d,N])=>u[d]===N)||h(u)},[n,r,h]);const y=a.useCallback(()=>{typeof window<"u"&&x.current.timer!=null&&window.clearTimeout(x.current.timer),x.current={parts:[],timer:null}},[]),S=a.useCallback(()=>{typeof window>"u"||(x.current.timer!=null&&window.clearTimeout(x.current.timer),x.current.timer=window.setTimeout(()=>{x.current={parts:[],timer:null}},$u))},[]);a.useEffect(()=>{if(!i)return;const u=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),p([]);return}const v=m(b);if(!v)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&N){p([v]);return}const k=[...l,v].slice(0,2).join(" "),f={...n};for(const[g,w]of Object.entries(f))w===k&&delete f[g];f[i]=k,h(f),c(null),p([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,h,i,l]),a.useEffect(()=>{if(!t||i)return;const u=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const d=b.metaKey||b.ctrlKey||b.altKey;if(ln(b.target)&&!d)return;const N=x.current.parts,M=d?[v]:[...N.slice(-1),v].slice(-2),k=M.join(" "),f=M[M.length-1],g=Object.entries(n).filter(([,K])=>!!K),w=g.find(([,K])=>K===k);if(w){b.preventDefault(),y(),s(w[0]);return}if(g.some(([,K])=>K.startsWith(`${k} `))){b.preventDefault(),x.current.parts=M,S();return}const $=g.find(([,K])=>K===f);if($){b.preventDefault(),y(),s($[0]);return}if(g.some(([,K])=>K.startsWith(`${f} `))){b.preventDefault(),x.current.parts=[f],S();return}y()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,t,m,s,y,i]),a.useEffect(()=>()=>y(),[y]);const I=a.useMemo(()=>ei(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:p,saveShortcuts:h}}const si=a.createContext(null);function Cr(){const t=a.useContext(si);if(!t)throw new Error("DashboardDockviewContext missing");return t}function or(t){return Qe(t)||t.tabKey}function Ou(t){return`remote:${t}`}function Wt(t){return t.startsWith("remote:")}function Ta(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Hr(t){var r,n,o,i,c;const s=t==null?void 0:t.defaultView;if(s)try{s.focus(),(n=(r=t==null?void 0:t.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=t==null?void 0:t.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,p;try{s.focus(),(p=(l=t==null?void 0:t.body)==null?void 0:l.focus)==null||p.call(l)}catch{}})}catch{}}function Qs(t,s){t.classList.remove(Jr.className,Zr.className),t.classList.add(s==="light"?Jr.className:Zr.className)}function _a(t){return t?Array.from(new Set(t.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 Hu(t){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[t.api.onDidActiveGroupChange(r),t.api.onDidTitleChange(r),t.api.onDidGroupChange(r),t.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[t.api,t.containerApi])}function Uu(t,s,r){var l;const n=[s];let o;for(const p of n){let x;for(const m of p){const h=t.addPanel({id:m.tabKey,component:"conversation",title:or(m),params:{kind:"conversation",tabKey:m.tabKey},...x?{position:{referencePanel:x,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});x||(x=h.id)}o=x??o}const i=r??((l=s[0])==null?void 0:l.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function Pa(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Wt(n.id)||r.has(n.id)||t.removePanel(n);for(const n of s){const o=t.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==or(n)&&o.api.setTitle(or(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:or(n),params:{kind:"conversation",tabKey:n.tabKey},...t.activePanel?{position:{referencePanel:t.activePanel.id,direction:"within"},inactive:!0}:t.panels[0]?{position:{referencePanel:t.panels[0].id,direction:"within"},inactive:!0}:{}})}}function La(t,s,r){var p,x;const n=r?Ou(r):null;for(const m of[...t.panels])Wt(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const o=Dt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=wo(o);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(o==null?void 0:o.tabKey)??((p=t.activePanel)==null?void 0:p.id)??((x=t.panels.find(m=>!Wt(m.id)))==null?void 0:x.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function zu({params:t,api:s}){var h;const r=Cr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),l=jr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const y=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of y)S.dispose()}},[s]);const p=a.useMemo(()=>c?r.ides.find(y=>y.id===c.routeId):void 0,[r.ides,c]),x=a.useMemo(()=>c?r.actionLogs.filter(y=>y.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:e.jsx(Pn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!Ve(c)&&ms(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Tn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:p,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:x,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function Fu({params:t}){var p;const s=Cr(),r=a.useMemo(()=>Dt([...s.conversationsByTabKey.values()],t.routeId),[s.conversationsByTabKey,t.routeId]),n=a.useMemo(()=>s.ides.find(x=>x.id===t.routeId),[s.ides,t.routeId]),o=(r==null?void 0:r.daemonId)||((p=r==null?void 0:r.routeId)==null?void 0:p.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Zo({doId:o,targetSessionId:r?wn(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?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(no,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):e.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 Vu(){const t=Cr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Pn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function Gu(t){var S,I;Hu(t);const s=Cr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=Dt([...s.conversationsByTabKey.values()],t.params.routeId),b=((S=t.api.group.activePanel)==null?void 0:S.id)===t.api.id,v=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const o=((I=t.api.group.activePanel)==null?void 0:I.id)===t.api.id,i=t.api.isGroupActive,c=Ls(n,s.liveSessionInboxState,{isOpenConversation:o}),l=c.isReconnecting,p=c.isConnecting,x=c.isGenerating,m=c.isWaiting,h=c.unread,y=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:Qe(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var b;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((b=u.target)==null?void 0:b.ownerDocument)??document})},children:[h&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:x?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):p?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:Qe(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(n)}):p?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Yt(n)}):e.jsx("span",{children:Yt(n)})})]}),y&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function qu({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:p,initialDataLoaded:x,userName:m,detectedIdes:h,handleLaunchIde:y,toggleHiddenTab:S,actionShortcuts:I,registerActionHandlers:u,onActiveTabChange:b,requestedActiveTabKey:v,requestedRemoteIdeId:d,onRequestedActiveTabConsumed:N,scrollToBottomRequest:M}){var wt,bt,Tt;const{theme:k}=Cn(),{sendCommand:f}=St(),g=a.useRef(null),w=a.useRef(null),j=a.useRef(!1),$=a.useRef(!1),D=a.useRef(!1),K=a.useRef(null),R=a.useRef([]),[z,P]=a.useState(null),[C,_]=a.useState(!1),[G,T]=a.useState(!1),[E,H]=a.useState(0),se=a.useRef(null),Y=a.useMemo(()=>Ho(typeof window<"u"?window.innerWidth:1280),[]),oe=a.useRef(typeof window>"u"?{}:Qd(Y)),je=a.useMemo(()=>new Map(t.map(B=>[B.tabKey,B])),[t]),V=a.useMemo(()=>$s(r),[r]),ae=a.useCallback(()=>{var B;(B=g.current)==null||B.focus()},[]),W=a.useCallback(B=>{const U=document,q=B.document;for(const Z of U.querySelectorAll('link[rel="stylesheet"]')){const Ie=q.createElement("link");Ie.rel="stylesheet",Ie.href=Z.href,Z.crossOrigin&&(Ie.crossOrigin=Z.crossOrigin),q.head.appendChild(Ie)}for(const Z of U.querySelectorAll("style")){const Ie=q.createElement("style");Ie.textContent=Z.textContent,q.head.appendChild(Ie)}const O=[];for(const Z of U.styleSheets)try{for(const Ie of Z.cssRules)Ie instanceof CSSStyleRule&&(Ie.selectorText===":root"||Ie.selectorText==="html")&&O.push(Ie.cssText)}catch{}if(O.length>0){const Z=q.createElement("style");Z.textContent=O.join(`
43
- `),q.head.appendChild(Z)}const le=U.documentElement.getAttribute("data-theme");le&&q.documentElement.setAttribute("data-theme",le),q.documentElement.style.colorScheme=le==="light"?"light":"dark",q.body.className=U.body.className;const Se=U.documentElement.getAttribute("style");Se&&q.documentElement.setAttribute("style",Se);const Me=q.getElementById("dv-popout-window");Me instanceof HTMLElement&&(Me.classList.add("adhdev-dockview"),Qs(Me,k))},[k]),be=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const le=O.getElementById("dv-popout-window");le instanceof HTMLElement&&(le.classList.add("adhdev-dockview"),Qs(le,k));const Se=document.documentElement.getAttribute("data-theme");Se&&O.documentElement.setAttribute("data-theme",Se),O.documentElement.style.colorScheme=Se==="light"?"light":"dark",O.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me?O.documentElement.setAttribute("style",Me):O.documentElement.removeAttribute("style")}catch{}},[k]),X=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const le=O.getElementById("dv-popout-window");if(!(le instanceof HTMLElement))continue;le.classList.add("adhdev-dockview"),Qs(le,k),le.classList.toggle("is-showing-dockview-overlay",G),le.classList.toggle("is-dragging-dockview",C)}catch{}},[C,G,k]),J=a.useCallback(B=>{const U=g.current;if(!U)return;const q=U.getPanel(B);q&&U.addPopoutGroup(q,{popoutUrl:"/popout.html",onDidOpen:({window:O})=>{W(O),ye();const le=je.get(B);O.document.title=le?`${Qe(le)} — ADHDev`:"ADHDev — Popout"}})},[je,W]),ie=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(le=>{var Se;try{return((Se=le.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),ne=a.useCallback(B=>{var O;const U=g.current;if(!U)return!1;const q=U.getPanel(B);if(!q)return!1;try{return((O=q.group.element)==null?void 0:O.ownerDocument)!==document}catch{return!1}},[]),he=a.useCallback(B=>{ne(B)&&ie(B),S(B)},[ne,ie,S]),ue=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);!U||!q||U.addFloatingGroup(q,{width:600,height:500})},[]),fe=a.useCallback(B=>{var q;const U=(q=g.current)==null?void 0:q.getPanel(B);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),te=a.useCallback(()=>{var U,q;const B=(q=(U=g.current)==null?void 0:U.activePanel)==null?void 0:q.id;return!B||Wt(B)?null:je.has(B)?B:null},[je]),pe=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(le=>{try{return le.model.location.type==="grid"}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),de=a.useCallback(()=>{var Se;const B=g.current;if(!B)return;const q=B.groups.filter(Me=>{var Z;try{return((Z=Me.element)==null?void 0:Z.ownerDocument)===document&&Me.model.location.type==="grid"}catch{return!1}})[0]||null,O=[...B.panels];for(const Me of O){const Z=(Se=Me.group.element)==null?void 0:Se.ownerDocument,Ie=Me.group.model.location.type;Z===document&&Ie==="grid"||(q&&q.id!==Me.group.id?Me.api.moveTo({group:q,position:"center"}):Me.api.moveTo({position:"center"}))}const le=B.activePanel;le&&(le.group.model.openPanel(le),le.api.setActive()),Hr(document)},[]),ye=a.useCallback(()=>{var U,q;const B=g.current;if(B)for(const O of B.groups){const le=(U=O.element)==null?void 0:U.ownerDocument;if(!le||le===document)continue;const Se=le.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Me=null,Z=le.title||"ADHDev",Ie="Popout workspace";const De=O.activePanel;if(De)if(Me=De.id,Wt(De.id)){const re=((q=De.params)==null?void 0:q.routeId)||De.id.slice(7),ce=Dt([...je.values()],re);Z=wo(ce),Ie=ce!=null&&ce.machineName?`Remote view · ${ce.machineName}`:"Remote view"}else{const re=je.get(De.id);Z=re?Qe(re):De.title||De.id,Ie=re?Yt(re):"Dockview panel"}le.title=`${Z} — ADHDev`;let Ue=le.getElementById("adhdev-popout-header");Ue instanceof HTMLElement||(Ue=le.createElement("div"),Ue.id="adhdev-popout-header",le.body.appendChild(Ue)),Ue.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(";")),Ue.innerHTML=`
44
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
46
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ta(Z)}</div>
47
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ta(Ie)}</div>
48
- </div>
49
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
50
- <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
51
- <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
52
- </div>
53
- `,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const A=Ue.querySelector("[data-adhdev-popout-focus]");A&&(A.onclick=()=>{window.focus()});const ee=Ue.querySelector("[data-adhdev-popout-dock]");ee&&(ee.disabled=!Me,ee.style.opacity=Me?"1":"0.5",ee.style.cursor=Me?"pointer":"default",ee.onclick=()=>{var re;Me&&ie(Me),(re=le.defaultView)==null||re.focus()})}},[je,ie]),we=a.useCallback(B=>{var O;const U=g.current,q=U==null?void 0:U.getPanel(B);if(!(!U||!q)){q.group.model.openPanel(q),q.api.setActive();try{const le=q.group.model.location;le.type==="popout"?le.getWindow().focus():Hr((O=q.group.element)==null?void 0:O.ownerDocument)}catch{}}},[]),L=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.activePanel,O=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!O)return;const le=O.panels||[];if(le.length<=1)return;const Se=le.findIndex(Ie=>Ie.id===q.id);if(Se<0)return;const Me=(Se+B+le.length)%le.length,Z=le[Me];Z&&(Z.group.model.openPanel(Z),Z.api.setActive())},[]),ge=a.useCallback(B=>{var ee;const U=g.current,q=(U==null?void 0:U.activeGroup)||((ee=U==null?void 0:U.activePanel)==null?void 0:ee.group);if(!U||!q)return;const O=U.groups||[],le=O.find(re=>re.id===q.id);if(!le)return;const Se=le.element.getBoundingClientRect(),Me=Se.left+Se.width/2,Z=Se.top+Se.height/2,Ie=(re,ce,Pe,Ae)=>Math.max(0,Math.min(ce,Ae)-Math.max(re,Pe)),De=re=>{const ce=re.element.getBoundingClientRect(),Pe=ce.left+ce.width/2,Ae=ce.top+ce.height/2;let Oe=0,rt=0,Ye=0,qe=!1;if(B==="left"?(qe=Pe<Me,Oe=Math.max(0,Se.left-ce.right),rt=Math.abs(Ae-Z),Ye=Ie(Se.top,Se.bottom,ce.top,ce.bottom)):B==="right"?(qe=Pe>Me,Oe=Math.max(0,ce.left-Se.right),rt=Math.abs(Ae-Z),Ye=Ie(Se.top,Se.bottom,ce.top,ce.bottom)):B==="above"?(qe=Ae<Z,Oe=Math.max(0,Se.top-ce.bottom),rt=Math.abs(Pe-Me),Ye=Ie(Se.left,Se.right,ce.left,ce.right)):(qe=Ae>Z,Oe=Math.max(0,ce.top-Se.bottom),rt=Math.abs(Pe-Me),Ye=Ie(Se.left,Se.right,ce.left,ce.right)),!qe)return Number.POSITIVE_INFINITY;const He=Ye>0?0:120;return Oe*3+rt+He};let Ue=null,A=Number.POSITIVE_INFINITY;for(const re of O){if(re.id===le.id)continue;const ce=De(re);Number.isFinite(ce)&&(ce>=A||(A=ce,Ue=re))}return Ue||void 0},[]),F=a.useCallback(B=>{var O;const U=ge(B);if(!U)return;const q=U.activePanel||U.panels[0];q&&(U.model.openPanel(q),q.api.setActive(),Hr((O=U.element)==null?void 0:O.ownerDocument))},[ge]),me=a.useCallback((B,U)=>{const q=g.current,O=q==null?void 0:q.activePanel,le=(q==null?void 0:q.activeGroup)||(O==null?void 0:O.group);if(!q||!O||!le)return;let Se=ge(B);!Se&&(U!=null&&U.createGroupIfMissing)&&(Se=q.addGroup({referenceGroup:le,direction:B})),Se&&(O.api.moveTo({group:Se,position:"center"}),O.group.model.openPanel(O),O.api.setActive())},[ge]),{isMac:Ce,tabShortcuts:xe,shortcutListening:Le,setShortcutListening:Be,saveShortcuts:Fe}=Jo({sortedTabKeys:t.map(B=>B.tabKey),onFocus:ae,onSelectTab:we}),st=a.useCallback(()=>{var q;const B=g.current;if(!B)return;const U=B.activePanel;if(U){if(Wt(U.id)){const O=((q=U.params)==null?void 0:q.routeId)||U.id.slice(7),le=Dt(t,O);le!=null&&le.tabKey&&Be(le.tabKey);return}je.has(U.id)&&Be(U.id)}},[je,we,Be,t]),ze=a.useCallback(B=>{const U=[];return B.metaKey&&U.push(Ce?"⌘":"Meta"),B.ctrlKey&&U.push("Ctrl"),B.altKey&&U.push(Ce?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&U.push(Ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(U.push(ti(B.key)),U.join("+"))},[Ce]),dt=a.useCallback(B=>{var U,q;switch(B){case"splitActiveTabRight":me("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":me("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const O=te();O&&ue(O);return}case"popoutActiveTab":{const O=te();O&&J(O);return}case"dockActiveTab":{const O=te();if(!O)return;ne(O)?ie(O):fe(O)&&pe(O);return}case"focusLeftPane":F("left");return;case"focusRightPane":F("right");return;case"focusUpPane":F("above");return;case"focusDownPane":F("below");return;case"moveActiveTabToLeftPane":me("left");return;case"moveActiveTabToRightPane":me("right");return;case"moveActiveTabToUpPane":me("above");return;case"moveActiveTabToDownPane":me("below");return;case"selectPreviousGroupTab":L(-1);return;case"selectNextGroupTab":L(1);return;case"setActiveTabShortcut":st();return;case"hideCurrentTab":{const O=(q=(U=g.current)==null?void 0:U.activePanel)==null?void 0:q.id;O&&!Wt(O)&&he(O);return}default:return}},[L,pe,F,ue,te,he,fe,ne,ie,me,J,st]);a.useEffect(()=>{if(!z)return;const B=z.sourceDocument,U=B.defaultView??window,q=O=>{const le=B.querySelector("[data-dockview-tab-context-menu]");le&&le.contains(O.target)||P(null)};return U.addEventListener("mousedown",q,!0),U!==window&&window.addEventListener("mousedown",()=>P(null),!0),()=>{U.removeEventListener("mousedown",q,!0),U!==window&&window.removeEventListener("mousedown",()=>P(null),!0)}},[z]);const gt=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:je,detectedIdes:h,handleLaunchIde:y,ides:r,isStandalone:l,hasRegisteredMachines:p,liveSessionInboxState:V,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:he,userName:m,scrollToBottomRequest:M,tabShortcuts:xe,openTabContextMenu:({x:B,y:U,tabKey:q,sourceDocument:O})=>P({x:B,y:U,tabKey:q,sourceDocument:O??document}),popoutTab:J,moveTabBackToMain:ie,isTabInPopout:ne,floatTab:ue,isTabFloating:fe}),[n,s,je,h,y,r,l,p,V,o,c,i,he,m,M,xe,J,ie,ne,ue,fe]),Ge=a.useCallback(B=>{if(!B)return!1;const U=g.current;if(!U)return!1;const q=U.getPanel(B);return q?(q.group.model.openPanel(q),q.api.setActive(),N==null||N(),!0):!1},[N]),at=a.useCallback(()=>{if(D.current)return!1;const B=Ge(K.current);return B&&(D.current=!0),B},[Ge]),ot=a.useCallback(()=>{var U;const B=g.current;B&&Zd(Y,{activeTabId:((U=B.activePanel)==null?void 0:U.id)??null,layout:B.toJSON()})},[Y]),Ke=a.useCallback(()=>{eu(Y,oe.current)},[Y]),ct=a.useCallback(B=>{var O,le,Se,Me;const U=g.current;if(!U)return{kind:"grid"};const q=U.toJSON();for(const Z of q.floatingGroups||[])if((le=(O=Z.data)==null?void 0:O.views)!=null&&le.includes(B)&&Z.position)return{kind:"floating",position:Z.position};for(const Z of q.popoutGroups||[])if((Me=(Se=Z.data)==null?void 0:Se.views)!=null&&Me.includes(B))return{kind:"popout",position:Z.position,popoutUrl:Z.url};return{kind:"grid"}},[]),ut=a.useCallback(B=>{const U=g.current;if(!U)return;const q=U.getPanel(B),O=oe.current[B];if(!q||!O||O.kind==="grid")return;if(q.group.model.location.type===O.kind){delete oe.current[B],Ke();return}if(O.kind==="floating"){U.addFloatingGroup(q,{x:O.position.left??24,y:O.position.top??24,width:O.position.width,height:O.position.height}),delete oe.current[B],Ke();return}delete oe.current[B],Ke()},[Ke]);a.useEffect(()=>(u==null||u({setShortcutForActiveTab:st,restoreHiddenTabToSavedLocation:ut,resetAllPanelsToMain:de,activatePreviousTabInGroup:()=>L(-1),activateNextTabInGroup:()=>L(1),floatActiveTab:()=>{const B=te();B&&ue(B)},popoutActiveTab:()=>{const B=te();B&&J(B)},dockActiveTab:()=>{const B=te();B&&(ne(B)?ie(B):fe(B)&&pe(B))},splitActiveTabRight:()=>me("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>me("below",{createGroupIfMissing:!0}),focusLeftPane:()=>F("left"),focusRightPane:()=>F("right"),focusUpPane:()=>F("above"),focusDownPane:()=>F("below"),moveActiveTabToLeftPane:()=>me("left"),moveActiveTabToRightPane:()=>me("right"),moveActiveTabToUpPane:()=>me("above"),moveActiveTabToDownPane:()=>me("below")}),()=>u==null?void 0:u(null)),[L,pe,ue,F,te,fe,ne,me,ie,J,u,de,ut,st]);const it=a.useCallback(()=>{const B=w.current;if(!B)return;const U=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const q of U)q.setAttribute("data-adhdev-force-hidden","true")},[]),Q=a.useCallback(()=>{const B=w.current;if(!B)return;const U=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const q of U)q.removeAttribute("data-adhdev-force-hidden")},[]),_e=a.useCallback(()=>{const B=w.current;if(!B)return;const U=B.querySelectorAll(".dv-drop-target-container");for(const le of U)le.remove();const q=B.querySelectorAll(".dv-drop-target-dropzone");for(const le of q)le.remove();const O=B.querySelectorAll(".dv-drop-target");for(const le of O)le.classList.remove("dv-drop-target")},[]),Re=a.useCallback(()=>{_(!1),T(!1),Q(),it(),_e(),!(typeof window>"u")&&(se.current!=null&&window.clearTimeout(se.current),window.requestAnimationFrame(()=>{it(),_e()}),se.current=window.setTimeout(()=>{it(),_e(),se.current=null},80))},[Q,it,_e]),We=a.useCallback(B=>{var q;g.current=B.api;const U=Jd(Y);K.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&B.api.fromJSON(U.layout,{reuseExistingPanels:!1}),$.current=!!(U!=null&&U.layout)&&!x&&t.length===0,$.current||(Pa(B.api,t),La(B.api,t,d)),B.api.totalPanels===0&&t.length>0?Uu(B.api,t,v):!$.current&&!Ge(v)&&at(),j.current=!0,B.api.onDidActivePanelChange(O=>{var Se;if(K.current=(O==null?void 0:O.id)??null,D.current=!0,ye(),O&&Wt(O.id)){const Me=((Se=O.params)==null?void 0:Se.routeId)||O.id.slice(7),Z=Dt(t,Me);b((Z==null?void 0:Z.tabKey)??null),ot();return}if(b((O==null?void 0:O.id)??null),ot(),!O)return;const le=je.get(O.id);(le==null?void 0:le.streamSource)==="agent-stream"&&le.agentType&&f(le.routeId,"focus_session",{agentType:le.agentType,...le.sessionId&&{targetSessionId:le.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{ot(),ye(),H(O=>O+1)}),B.api.onWillDragPanel(()=>{_(!0),T(!1),it()}),B.api.onWillDragGroup(()=>{_(!0),T(!1),it()}),B.api.onWillShowOverlay(()=>{Q(),T(!0)}),B.api.onDidMovePanel(Re),B.api.onDidDrop(Re),B.api.onDidAddGroup(O=>{requestAnimationFrame(()=>{var le,Se;try{const Me=(le=O.element)==null?void 0:le.ownerDocument;if(!Me||Me===document)return;(Se=Me.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Z=document.documentElement.getAttribute("data-theme");Z&&Me.documentElement.setAttribute("data-theme",Z),Me.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&Me.documentElement.setAttribute("style",Ie)}catch{}ye(),H(Me=>Me+1)})}),b(((q=B.api.activePanel)==null?void 0:q.id)??null)},[Ge,Re,Q,je,x,Y,it,_e,b,ot,v,d,f,ye,t]);a.useLayoutEffect(()=>{const B=g.current;if(!B||!j.current||$.current&&!x)return;$.current&&($.current=!1);const U=R.current,q=new Set(U),O=t.map(De=>De.tabKey),le=new Set(O);let Se=!1;for(const De of U)le.has(De)||(oe.current[De]=ct(De),Se=!0);Se&&Ke(),Pa(B,t),La(B,t,d);const Me=O.filter(De=>!q.has(De));let Z=!1;for(const De of Me){const Ue=B.getPanel(De),A=oe.current[De];if(!Ue||!A||A.kind==="grid")continue;if(Ue.group.model.location.type===A.kind){delete oe.current[De],Z=!0;continue}if(A.kind==="floating"){B.addFloatingGroup(Ue,{x:A.position.left??24,y:A.position.top??24,width:A.position.width,height:A.position.height}),delete oe.current[De],Z=!0;continue}}if(Z&&Ke(),R.current=O,v&&Ge(v))return;!B.activePanel&&B.panels[0]&&(B.panels[0].group.model.openPanel(B.panels[0]),B.panels[0].api.setActive()),!!(B.activePanel&&B.getPanel(B.activePanel.id))||at()},[Ge,at,x,Ke,ct,v,d,t]),a.useEffect(()=>{j.current&&Ge(v)},[Ge,v]),a.useEffect(()=>{if(!C||typeof window>"u")return;const B=()=>Re();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[Re,C]),a.useEffect(()=>()=>{typeof window>"u"||se.current!=null&&window.clearTimeout(se.current)},[]),a.useEffect(()=>{const B=q=>{const O=q.target;if(!O)return;const le=O.querySelector("[data-tab-key]")||O.closest("[data-tab-key]");if(le){const Se=le.getAttribute("data-tab-key");if(Se&&q.dataTransfer){const Me=O.closest(".dv-tab")||le.closest(".dv-tab")||le;q.dataTransfer.effectAllowed="move",q.dataTransfer.setData("text/tab-key",Se),Me instanceof HTMLElement&&q.dataTransfer.setDragImage(Me,Math.max(12,Math.round(Me.clientWidth/2)),Math.max(10,Math.round(Me.clientHeight/2)))}}};window.addEventListener("dragstart",B);const U=_a(g.current);for(const q of U)q.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const q of U)q.removeEventListener("dragstart",B)}},[E]),a.useEffect(()=>{var U;const B=(U=w.current)==null?void 0:U.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Qs(B,k),be(),ye(),X()},[ye,X,be,k]),a.useEffect(()=>{ye(),X()},[ye,X]),a.useEffect(()=>{const B=U=>{if(U.defaultPrevented||Le)return;const q=ze(U);if(!q)return;const O=U.metaKey||U.ctrlKey||U.altKey;ln(U.target)&&!O||xr(Ce).setActiveTabShortcut!==q||(U.preventDefault(),U.stopPropagation(),st())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[ze,Ce,Le,st]),a.useEffect(()=>{const B=_a(g.current);if(B.length===0)return;const U=B.map(q=>{let O=[],le=null;const Se=()=>{le!=null&&q.clearTimeout(le),le=null,O=[]},Me=()=>{le!=null&&q.clearTimeout(le),le=q.setTimeout(()=>{le=null,O=[]},1200)},Z=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const Ue=ze(De);if(!Ue)return;const A=Xo();for(const[ee,re]of Object.entries(A))if(t.some(ce=>ce.tabKey===ee)&&re===Ue){De.preventDefault(),we(ee);return}},Ie=De=>{if(De.defaultPrevented||Le)return;const Ue=ze(De);if(!Ue)return;const A=De.metaKey||De.ctrlKey||De.altKey;if(ln(De.target)&&!A)return;const ee=xr(Ce),re=Object.entries(ee).filter(([He,as])=>!!as&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),ce=A?[Ue]:[...O.slice(-1),Ue].slice(-2),Pe=ce.join(" "),Ae=ce[ce.length-1],Oe=re.find(([,He])=>He===Pe);if(Oe){De.preventDefault(),Se(),dt(Oe[0]);return}if(re.some(([,He])=>He.startsWith(`${Pe} `))){De.preventDefault(),O=ce,Me();return}const Ye=re.find(([,He])=>He===Ae);if(Ye){De.preventDefault(),Se(),dt(Ye[0]);return}if(re.some(([,He])=>He.startsWith(`${Ae} `))){De.preventDefault(),O=[Ae],Me();return}Se()};return q.addEventListener("keydown",Z),q.addEventListener("keydown",Ie),()=>{Se(),q.removeEventListener("keydown",Z),q.removeEventListener("keydown",Ie)}});return()=>{for(const q of U)q()}},[ze,Ce,E,we,Le,dt,t]);const Ct=k==="light"?Jr:Zr,pt=((Tt=(bt=(wt=g.current)==null?void 0:wt.activePanel)==null?void 0:bt.group.element)==null?void 0:Tt.ownerDocument)??document;return e.jsxs(si.Provider,{value:gt,children:[e.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Ri,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${G?" is-showing-dockview-overlay":""}`,components:{conversation:zu,remote:Fu},defaultTabComponent:Gu,watermarkComponent:Vu,onReady:We,singleTabMode:"default",tabAnimation:"smooth",theme:Ct,popoutUrl:"/popout.html"})}),z&&Ts.createPortal(e.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:z.x,top:z.y},children:[ne(z.tabKey)?e.jsxs(e.Fragment,{children:[fe(z.tabKey)&&e.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:()=>{pe(z.tabKey),P(null)},children:[e.jsx(zn,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Dock in window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]}),e.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:()=>{ie(z.tabKey),P(null)},children:[e.jsx(fc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Move back to main window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]})]}):fe(z.tabKey)?e.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:()=>{pe(z.tabKey),P(null)},children:[e.jsx(zn,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Dock back to grid"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]}):e.jsxs(e.Fragment,{children:[e.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:()=>{ue(z.tabKey),P(null)},children:[e.jsx(hc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Float as panel"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.floatActiveTab||""})]}),e.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:()=>{J(z.tabKey),P(null)},children:[e.jsx(mc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Open in new window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.popoutActiveTab||""})]})]}),e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.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:B=>{B.stopPropagation(),Be(z.tabKey),P(null)},children:[e.jsx(xc,{size:13,className:"shrink-0 opacity-70"})," ",xe[z.tabKey]?`Change shortcut (${xe[z.tabKey]})`:"Set shortcut"]}),xe[z.tabKey]&&e.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 B={...xe};delete B[z.tabKey],Fe(B),P(null)},children:[e.jsx(vt,{size:13,className:"shrink-0 opacity-70"})," Remove shortcut"]}),e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.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:()=>{he(z.tabKey),P(null)},children:[e.jsx(Qa,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),z.sourceDocument.body),Le&&Ts.createPortal(e.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:()=>Be(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",Ce?"⌘+1":"Ctrl+1",", ",Ce?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),pt.body)]})}const ri="adhdev-recent-launch-args-v1",Yu=8;function Xu(t){return String(t||"").trim().replace(/\s+/g," ")}function ni(t,s){return`${t.trim()}::${s.trim()}`}function ai(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(ri)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Ju(t){if(!(typeof window>"u"))try{window.localStorage.setItem(ri,JSON.stringify(t))}catch{}}function oi(t,s){var i;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=ai().byKey[ni(r,n)])==null?void 0:i.items)||[]}function ii(t,s,r){var m;const n=String(t||"").trim(),o=String(s||"").trim(),i=Xu(r);if(!n||!o||!i)return;const c=ai(),l=ni(n,o),p=((m=c.byKey[l])==null?void 0:m.items)||[],x=[i,...p.filter(h=>h!==i)].slice(0,Yu);c.byKey[l]={items:x},Ju(c)}function Ur(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Zu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Ra(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Da(t){if(!t)return"unknown";const s=Date.now()-t,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 Qu(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function ep(t){const s=typeof(t==null?void 0:t.runtimeRecoveryState)=="string"?String(t.runtimeRecoveryState):"";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 tp(t){switch(t){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 sp(t){var r;const s=new Map;for(const n of t){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 rp({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var z;const[l,p]=a.useState(n||((z=t[0])==null?void 0:z.id)||null),[x,m]=a.useState(""),[h,y]=a.useState(null),[S,I]=a.useState(!1);a.useEffect(()=>{var P;p(n||((P=t[0])==null?void 0:P.id)||null)},[n,t]);const u=a.useMemo(()=>t.find(P=>P.id===l)||t[0]||null,[l,t]),b=a.useMemo(()=>r.filter(P=>{if(P.type==="adhdev-daemon"||P.transport!=="pty")return!1;const C=Zu(P.daemonId||P.id);return!!(u!=null&&u.id)&&C===u.id}),[u==null?void 0:u.id,r]),v=Ko(u==null?void 0:u.id,{enabled:!!(u!=null&&u.id),includeSessions:!0,limit:6,intervalMs:1e4}),d=v.diagnostics,N=v.loading,M=v.applyDiagnostics,k=a.useMemo(()=>{const P=new Map;for(const C of b){const _=s.find(G=>G.sessionId===C.sessionId||G.routeId===C.id);C.sessionId&&_&&P.set(C.sessionId,_)}return P},[b,s]),f=a.useCallback(async()=>{if(u!=null&&u.id){I(!0);try{const P=await o(u.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),C=Ur(P);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Could not load session host diagnostics");M(C.diagnostics||C.result||null),m("")}catch(P){const C=P instanceof Error?P.message:"Could not load session host diagnostics";m(C)}finally{I(!1)}}},[u==null?void 0:u.id,M,o]),g=a.useCallback(async(P,C)=>{if(!(u!=null&&u.id)||P==="session_host_stop_session"&&!window.confirm(`Stop ${C.displayName}?
54
- This will terminate the hosted runtime.`))return;const _=`${P}:${C.sessionId}`;y(_);try{const G=await o(u.id,P,{sessionId:C.sessionId}),T=Ur(G);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Session host action failed");const E=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${E}: ${C.displayName}`,"success"),await f()}catch(G){const T=G instanceof Error?G.message:"Session host action failed";m(T),ht.showToast(T,"warning")}finally{y(G=>G===_?null:G)}},[u==null?void 0:u.id,f,o]),w=a.useCallback(async()=>{if(!(!(u!=null&&u.id)||!window.confirm(`Prune duplicate hosted runtimes?
55
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){y("session_host_prune_duplicate_sessions");try{const C=await o(u.id,"session_host_prune_duplicate_sessions",{}),_=Ur(C);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Duplicate prune failed");const G=_.result||{},T=Array.isArray(G.prunedSessionIds)?G.prunedSessionIds.length:0,E=typeof G.duplicateGroupCount=="number"?G.duplicateGroupCount:0;ht.showToast(`Pruned ${T} duplicate runtime(s) across ${E} group(s)`,"success"),await f()}catch(C){const _=C instanceof Error?C.message:"Duplicate prune failed";m(_),ht.showToast(_,"warning")}finally{y(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[u==null?void 0:u.id,f,o]),j=a.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((P,C)=>(C.lastActivityAt||0)-(P.lastActivityAt||0)),[d==null?void 0:d.sessions]),$=a.useMemo(()=>sp(j),[j]),D=a.useMemo(()=>j.reduce((P,C)=>{var _;return P+(((_=C.attachedClients)==null?void 0:_.length)||0)},0),[j]),K=a.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[d==null?void 0:d.recentLogs]),R=a.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-3).reverse(),[d==null?void 0:d.recentTransitions]);return e.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:e.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:P=>P.stopPropagation(),children:[e.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(u==null?void 0:u.label)||"No machine selected"}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Hosted CLI runtime recovery and control."})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.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:()=>{f()},disabled:N||S,"aria-label":"Refresh session host",children:e.jsx(xs,{size:16})}),e.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 session host",children:e.jsx(vt,{size:16})})]})]}),t.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:t.map(P=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${P.id===(u==null?void 0:u.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>p(P.id),children:P.label},P.id))}),e.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:[x&&!d&&e.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:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(es,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Session host unavailable"}),e.jsx("div",{className:"mt-1 text-amber-200/90",children:x})]})]})}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:d.runtimeCount})]}),e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Clients"}),e.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:D})]}),e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),e.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:Da(d.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Ra(d.hostStartedAt)})]})]}),K&&e.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[e.jsx(es,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:K.message})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[e.jsx(gr,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[$>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:h==="session_host_prune_duplicate_sessions",onClick:()=>{w()},children:h==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${$}`}),e.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),j.length===0?e.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No hosted CLI runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:j.map(P=>{var Y,oe;const C=k.get(P.sessionId),_=b.find(je=>je.sessionId===P.sessionId),G=h===`session_host_resume_session:${P.sessionId}`,T=h===`session_host_restart_session:${P.sessionId}`,E=h===`session_host_stop_session:${P.sessionId}`,H=ep(P.meta),se=typeof((Y=P.meta)==null?void 0:Y.runtimeRecoveryError)=="string"?String(P.meta.runtimeRecoveryError):"";return e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:P.displayName||(_==null?void 0:_.runtimeDisplayName)||(_==null?void 0:_.cliName)||P.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${tp(P.lifecycle)}`,children:P.lifecycle}),H&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:H})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:P.workspaceLabel||(_==null?void 0:_.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[e.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((oe=P.writeOwner)==null?void 0:oe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Qu(P.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(mn,{size:11})," ",P.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Da(P.lastActivityAt),P.osPid?` · pid ${P.osPid}`:""]}),se&&e.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:se})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[C&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(C),c()},children:"Open chat"}),(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{g("session_host_resume_session",P)},children:G?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{g("session_host_restart_session",P)},children:T?"Restarting…":"Restart"}),(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&e.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:!!h,onClick:()=>{g("session_host_stop_session",P)},children:E?"Stopping…":"Stop"})]})]},P.sessionId)})}),R.length>0&&e.jsxs("div",{className:"pb-1",children:[e.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"}),e.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:R.map(P=>{const C=j.find(_=>_.sessionId===P.sessionId);return e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(C==null?void 0:C.displayName)||P.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:Ra(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]})]})]})]})})}function zr(t){var n;if(!t)return null;const s=t.availableProviders||[];return s.some(o=>o.category==="cli"&&o.installed!==!1)?"cli":(((n=t.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(o=>o.category==="acp"&&o.installed!==!1)?"acp":null}function er(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function np({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:p,sendDaemonCommand:x,onOpenConversation:m}){var ut,it;const h=Ks(),y=a.useMemo(()=>[...t].sort(gn),[t]),[S,I]=a.useState(((ut=y[0])==null?void 0:ut.id)||""),u=a.useMemo(()=>y.find(Q=>Q.id===S)||y[0],[S,y]),b=a.useMemo(()=>((u==null?void 0:u.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[u]),v=(u==null?void 0:u.defaultWorkspaceId)||null,[d,N]=a.useState(""),[M,k]=a.useState(""),[f,g]=a.useState(zr(y[0])),[w,j]=a.useState(""),[$,D]=a.useState(""),[K,R]=a.useState([]),[z,P]=a.useState(""),[C,_]=a.useState([]),[G,T]=a.useState(!1),[E,H]=a.useState(""),[se,Y]=a.useState(!1),[oe,je]=a.useState(!1),[V,ae]=a.useState(null),[W,be]=a.useState(!1),[X,J]=a.useState(""),[ie,ne]=a.useState(!1),[he,ue]=a.useState(""),[fe,te]=a.useState([]),[pe,de]=a.useState(!1),[ye,we]=a.useState(""),[L,ge]=a.useState(!1),F=a.useRef(null),me=a.useRef(0);a.useEffect(()=>{var Q;!S&&((Q=y[0])!=null&&Q.id)&&I(y[0].id)},[S,y]),a.useEffect(()=>{!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||h(u.id,{minFreshMs:3e4}).catch(()=>{})},[h,u]);const Ce=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(Q=>Q.category==="cli"&&Q.installed!==!1),[u]),xe=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(Q=>Q.category==="acp"&&Q.installed!==!1),[u]),Le=a.useMemo(()=>((u==null?void 0:u.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[u]),Be=a.useMemo(()=>f==="cli"?Ce.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):f==="acp"?xe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):Le,[xe,f,Ce,Le]);a.useEffect(()=>{var _e;if(!u)return;if(F.current!==u.id){F.current=u.id,N(v||((_e=b[0])==null?void 0:_e.id)||"__home__"),k(""),g(zr(u)),j(""),D(""),P(""),_([]),H(""),J("");return}N(Re=>{var We;return Re==="__custom__"||Re==="__home__"||b.some(Ct=>Ct.id===Re)?Re:v||((We=b[0])==null?void 0:We.id)||"__home__"}),g(Re=>Re==="ide"&&Le.length>0||Re==="cli"&&Ce.length>0||Re==="acp"&&xe.length>0?Re:zr(u))},[xe.length,Ce.length,v,Le.length,u,b]),a.useEffect(()=>{var Q;f&&(Be.some(_e=>_e.id===w)||j(((Q=Be[0])==null?void 0:Q.id)||""))},[f,Be,w]);const Fe=a.useCallback(async(Q,_e)=>{const Re=me.current+1;return me.current=Re,T(!0),H(""),p(Q,_e).then(We=>{me.current===Re&&_(We)}).catch(We=>{me.current===Re&&(_([]),H(We instanceof Error?We.message:"Could not load saved sessions"))}).finally(()=>{me.current===Re&&T(!1)})},[p]),st=a.useCallback((Q,_e)=>{R(oi(Q,_e))},[]);a.useEffect(()=>{if(P(""),!u||!w||f==="ide"?R([]):st(u.id,w),f!=="cli"){_([]),H(""),T(!1);return}if(!u||!w){_([]),H(""),T(!1);return}Fe(u.id,w)},[f,st,Fe,u,w]),a.useEffect(()=>{if(!z)return;const Q=C.find(_e=>_e.providerSessionId===z);Q!=null&&Q.canResume||P("")},[C,z]);const ze=d==="__custom__"?M.trim():d==="__home__"?"":((it=b.find(Q=>Q.id===d))==null?void 0:it.path)||"",dt=a.useCallback(Q=>{const _e=String(Q.workspace||"").trim();if(!_e)return;const Re=b.find(We=>er(We.path)===er(_e));if(Re){N(Re.id),k("");return}N("__custom__"),k(_e)},[b]),gt=a.useCallback(Q=>{const _e=String(Q.workspace||"").trim();if(!_e)return{workspaceId:null,workspacePath:null};const Re=b.find(We=>er(We.path)===er(_e));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:_e}},[b]),Ge=a.useMemo(()=>{var _e;if(f!=="cli"||!u||!w)return null;const Q=((_e=Ce.find(Re=>Re.type===w))==null?void 0:_e.displayName)||w;return{routeId:u.id,daemonId:u.id,providerSessionId:z||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:w,status:"idle",title:Q,messages:[],ideType:w,workspaceName:ze,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${u.id}:${w}`,machineName:kt(u,{fallbackId:u.id})}},[f,Ce,ze,u,z,w]),at=a.useCallback(()=>{var _e,Re;if(!u)return;N("__custom__"),ne(!0),we("");const Q=kr(u.platform,[M.trim(),ze,(_e=b.find(We=>We.id===v))==null?void 0:_e.path,(Re=b[0])==null?void 0:Re.path]);de(!0),o(u.id,Q).then(We=>{ue(We.path),k(We.path),te(We.directories)}).catch(We=>{we(We instanceof Error?We.message:"Could not load folder")}).finally(()=>de(!1))},[M,v,o,ze,u,b]),ot=a.useCallback(Q=>{u&&(de(!0),we(""),o(u.id,Q).then(_e=>{ue(_e.path),k(_e.path),te(_e.directories)}).catch(_e=>{we(_e instanceof Error?_e.message:"Could not load folder")}).finally(()=>de(!1)))},[o,u]),Ke=a.useCallback(async()=>{if(!u||!ze)return;ge(!0),J("");const Q=await i(u.id,ze);if(ge(!1),!Q.ok){J(Q.error||"Could not save workspace");return}J("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,ze,u]),ct=a.useCallback(async()=>{if(!u||!f||!w)return;be(!0),J("");const Q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],_e=f==="ide"?await c(u.id,w,{workspacePath:ze||null}):await l(u.id,f,w,{workspaceId:d!=="__home__"&&d!=="__custom__"?d:null,workspacePath:d==="__custom__"&&ze||null,resumeSessionId:f==="cli"&&z?z:null,cliArgs:Q});if(be(!1),!_e.ok){J(_e.error||"Could not start session");return}f!=="ide"&&$.trim()&&(ii(u.id,w,$),st(u.id,w)),n()},[f,$,st,n,c,l,ze,u,z,w,d]);return u?e.jsxs(e.Fragment,{children:[e.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:e.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:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"New session"}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine, choose a workspace, then start IDE, CLI, or ACP without leaving the dashboard."})]}),e.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:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Machine"}),e.jsx("select",{value:u.id,onChange:Q=>I(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:W,children:y.map(Q=>e.jsx("option",{value:Q.id,children:kt(Q,{fallbackId:Q.id})},Q.id))})]}),f==="cli"&&e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Session Host"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Inspect hosted runtimes first, then resume or restart without leaving this flow."})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u,onClick:()=>je(!0),children:[e.jsx(Ut,{size:14}),"Open"]})]})}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Workspace"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Saved workspace is preferred. Home and custom folders are still available."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:W,children:"Browse…"})]}),e.jsxs("select",{value:d,onChange:Q=>{const _e=Q.target.value;N(_e),_e==="__custom__"?at():J("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W,children:[e.jsx("option",{value:"__home__",children:"Home directory"}),b.map(Q=>e.jsxs("option",{value:Q.id,children:[Q.id===v?"⭐ ":"",vr(Q.path,Q.label)||Q.path]},Q.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:d==="__home__"?"Launch without a workspace.":ze||"Select a workspace folder."}),d==="__custom__"&&ze&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:W,children:[e.jsx(ps,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ke,disabled:W||L,children:L?"Saving…":"Save workspace"})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ce.length>0},{id:"ide",label:"IDE",enabled:Le.length>0},{id:"acp",label:"ACP",enabled:xe.length>0}].map(Q=>e.jsx("button",{type:"button",className:`btn btn-sm ${f===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>g(Q.id),disabled:!Q.enabled||W,children:Q.label},Q.id))})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:f==="ide"?"Choose IDE":f==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Be.map(Q=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>j(Q.id),disabled:W,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),Be.length===0&&e.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."})]})]}),f!=="ide"&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Startup arguments"}),e.jsx("input",{type:"text",value:$,onChange:Q=>D(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:W}),K.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:K.map(Q=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>D(Q),disabled:W,title:Q,children:Q},Q))})]}),f==="cli"&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Pick a saved CLI session, then launch with optional args."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u||!w||G,onClick:()=>{!u||!w||Fe(u.id,w)},children:G?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u||!w,onClick:()=>{!u||!w||(Y(!0),Fe(u.id,w))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:z,onChange:Q=>{const _e=Q.target.value;if(P(_e),!_e)return;const Re=C.find(We=>We.providerSessionId===_e);!Re||!Re.canResume||dt(Re)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W||G,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),C.map(Q=>e.jsxs("option",{value:Q.providerSessionId,disabled:!Q.canResume,children:[Q.title||Q.providerSessionId,Q.canResume?"":" (workspace missing)"]},Q.providerSessionId))]})}),z&&(()=>{const Q=C.find(_e=>_e.providerSessionId===z);return Q?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:Q.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[Q.workspace||"Workspace unknown",Q.currentModel?` · ${Q.currentModel}`:""]})]}):null})(),E&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:E}),!G&&!E&&C.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),X&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:X})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:W,children:"Cancel"}),e.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:W||!f||!w||d==="__custom__"&&!ze,children:[e.jsx(xn,{size:14}),W?"Starting…":"Start session"]})]})]})}),ie&&e.jsx(Sr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:he,directories:fe,busy:pe,error:ye,onClose:()=>ne(!1),onNavigate:ot,onConfirm:Q=>{k(Q),ue(Q),N("__custom__"),ne(!1)}}),se&&Ge&&e.jsx(kn,{activeConv:Ge,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:C,isSavedSessionsLoading:G,isResumingSavedSessionId:V,onClose:()=>Y(!1),onNewChat:()=>{P(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!u||!w||Fe(u.id,w)},onResumeSavedSession:Q=>{if(!u||!w||V||!Q.canResume)return;const _e=gt(Q);P(Q.providerSessionId),dt(Q),ae(Q.providerSessionId),Y(!1),be(!0),J(""),l(u.id,"cli",w,{workspaceId:_e.workspaceId,workspacePath:_e.workspacePath,resumeSessionId:Q.providerSessionId}).then(Re=>{if(!Re.ok){J(Re.error||"Could not resume session");return}n()}).finally(()=>{be(!1),ae(Re=>Re===Q.providerSessionId?null:Re)})}}),oe&&u&&e.jsx(rp,{machineCards:[{id:u.id,label:kt(u,{fallbackId:u.id}),subtitle:[u.platform||"machine",qo(u)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:u.id,sendDaemonCommand:x,onOpenConversation:Q=>{je(!1),n(),m(Q)},onClose:()=>je(!1)})]}):null}function ap(t){switch(t.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 op(t){return t instanceof Error?t.message:String(t||"")}function ip(t){const s=op(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function cp({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:p,activeCliViewMode:x,onSetActiveCliViewMode:m,mobileChatConversations:h,hiddenConversations:y,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:d,initialDataLoaded:N,userName:M,requestedMobileTabKey:k,onRequestedMobileTabConsumed:f,requestedMachineId:g,onRequestedMachineConsumed:w,requestedMobileSection:j,onRequestedMobileSectionConsumed:$,containerRef:D,isSplitMode:K,numGroups:R,groupSizes:z,groupedConvs:P,clearedTabs:C,focusedGroup:_,setFocusedGroup:G,moveTabToGroup:T,splitTabRelative:E,closeGroup:H,handleResizeStart:se,detectedIdes:Y,handleLaunchIde:oe,groupActiveTabIds:je,setGroupActiveTabIds:V,groupTabOrders:ae,setGroupTabOrders:W,toggleHiddenTab:be,visibleConversations:X,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:ie,onDesktopActiveTabChange:ne,onHideConversation:he,onShowHiddenConversation:ue,onShowAllHiddenConversations:fe,scrollToBottomRequest:te,machineEntries:pe,onBrowseMachineDirectory:de,onSaveMachineWorkspace:ye,onLaunchMachineIde:we,onLaunchMachineProvider:L,onListMachineSavedSessions:ge}){const F=et.useRef(null),[me,Ce]=et.useState(!1),[xe,Le]=et.useState(!1),[Be,Fe]=et.useState(!1),[st,ze]=et.useState(!1),dt=et.useCallback(Z=>{var Ie;Ts.flushSync(()=>{ue(Z)}),(Ie=F.current)==null||Ie.restoreHiddenTabToSavedLocation(Z.tabKey)},[ue]),[gt,Ge]=et.useState(!1),[at,ot]=et.useState("quickstart"),[Ke,ct]=et.useState("workspace"),ut=!t&&!s,it=et.useCallback(Z=>{Ce(Z),Z&&Le(!1)},[]),Q=et.useCallback(Z=>{Le(Z),Z&&Ce(!1)},[]),_e=et.useCallback(()=>{var Ie;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ie=F.current)==null||Ie.resetAllPanelsToMain(),Le(!1))},[]),Re=et.useCallback(()=>{ot(X.length===0?"quickstart":"shortcuts"),ct("workspace"),Fe(!0),Ce(!1),Le(!1)},[X.length]),We=et.useCallback(async Z=>{var ee;if(!r)return;const Ie=(ee=r.modalButtons)==null?void 0:ee[Z];if(!Ie)return;const De=Ds(r);if(!De)return;const Ue=Ie.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ue);try{await u(De,"resolve_action",{button:Ie,action:A?"approve":"reject",buttonIndex:Z,...us(r)})}catch(re){ip(re)||console.error("[Shortcut approval] Failed:",re)}},[r,u]),{isMac:Ct,actionDefinitions:pt,actionShortcuts:wt,shortcutListening:bt,shortcutListeningDraft:Tt,setShortcutListening:B,setShortcutListeningDraft:U,saveShortcuts:q}=Wu({enabled:ut&&!Be,onTrigger:Z=>{var Ie,De,Ue,A,ee,re,ce,Pe,Ae,Oe,rt,Ye,qe,He,as,Ws;if(Z==="openShortcutHelp"){Re();return}if(Z==="hideCurrentTab"){r&&he(r);return}if(Z==="toggleHiddenTabs"){Q(!xe);return}if(Z==="openHistoryForActiveTab"){r&&!Ve(r)&&c(r);return}if(Z==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ve(r)&&l(r);return}if(Z==="splitActiveTabRight"){(Ie=F.current)==null||Ie.splitActiveTabRight();return}if(Z==="splitActiveTabDown"){(De=F.current)==null||De.splitActiveTabDown();return}if(Z==="floatActiveTab"){(Ue=F.current)==null||Ue.floatActiveTab();return}if(Z==="popoutActiveTab"){(A=F.current)==null||A.popoutActiveTab();return}if(Z==="dockActiveTab"){(ee=F.current)==null||ee.dockActiveTab();return}if(Z==="focusLeftPane"){(re=F.current)==null||re.focusLeftPane();return}if(Z==="focusRightPane"){(ce=F.current)==null||ce.focusRightPane();return}if(Z==="focusUpPane"){(Pe=F.current)==null||Pe.focusUpPane();return}if(Z==="focusDownPane"){(Ae=F.current)==null||Ae.focusDownPane();return}if(Z==="moveActiveTabToLeftPane"){(Oe=F.current)==null||Oe.moveActiveTabToLeftPane();return}if(Z==="moveActiveTabToRightPane"){(rt=F.current)==null||rt.moveActiveTabToRightPane();return}if(Z==="moveActiveTabToUpPane"){(Ye=F.current)==null||Ye.moveActiveTabToUpPane();return}if(Z==="moveActiveTabToDownPane"){(qe=F.current)==null||qe.moveActiveTabToDownPane();return}if(Z==="triggerPrimaryApprovalAction"){We(0);return}if(Z==="triggerSecondaryApprovalAction"){We(1);return}if(Z==="triggerTertiaryApprovalAction"){We(2);return}if(Z==="setActiveTabShortcut"){(He=F.current)==null||He.setShortcutForActiveTab();return}if(Z==="selectPreviousGroupTab"){(as=F.current)==null||as.activatePreviousTabInGroup();return}if(Z==="selectNextGroupTab"){(Ws=F.current)==null||Ws.activateNextTabInGroup();return}!r||!Xe(r)||Ve(r)||Z==="toggleCliView"&&m(x==="chat"?"terminal":"chat")}}),O=et.useCallback(()=>{Fe(!1),B(null),U([])},[B,U]),le=et.useMemo(()=>Ke==="all"?pt:pt.filter(Z=>ap(Z)===Ke),[pt,Ke]),Se=et.useCallback(()=>{const Z=Object.fromEntries(pt.map(Ie=>[Ie.id,""]));q(Z)},[pt,q]),Me=et.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Z=Object.fromEntries(pt.map(Ie=>[Ie.id,Ie.defaultShortcut]));q(Z)},[pt,q]);return et.useEffect(()=>{const Z=Ie=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ie.metaKey&&Ie.key.toLowerCase()==="w":Ie.ctrlKey&&Ie.key.toLowerCase()==="w")&&(Ie.preventDefault(),r&&he&&he(r))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[r,he]),et.useEffect(()=>{if(!Be||bt)return;const Z=Ie=>{Ie.key==="Escape"&&(Ie.preventDefault(),O())};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[O,Be,bt]),et.useEffect(()=>{if(!ut){Ge(!1);return}Ge(!0);const Z=window.setTimeout(()=>{Ge(!1)},1e4);return()=>window.clearTimeout(Z)},[ut]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(Il,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:X,hiddenConversations:y,onOpenHistory:c,onOpenConversation:dt,onHideConversation:he,onShowConversation:dt,onShowAllHidden:fe,onResetPanelsToMain:_e,inboxOpen:me,onInboxOpenChange:it,hiddenOpen:xe,onHiddenOpenChange:Q,onOpenNewSession:s?void 0:()=>ze(!0),actionShortcuts:wt,onOpenRemote:()=>{!r||Xe(r)||Ve(r)||l(r)},onStopCli:p,activeCliViewMode:x,onSetCliViewMode:m}),t?e.jsx(Mu,{conversations:h,hiddenConversations:y,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:d,userName:M,requestedActiveTabKey:k,onRequestedActiveTabConsumed:f,requestedMachineId:g,onRequestedMachineConsumed:w,requestedMobileSection:j,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:l,onStopCli:p,wsStatus:o,isConnected:i,onShowHiddenConversation:dt,onShowAllHiddenConversations:fe,onOpenNewSession:()=>ze(!0)}):s?e.jsx(Eu,{containerRef:D,isSplitMode:K,numGroups:R,groupSizes:z,groupedConvs:P,clearedTabs:C,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:d,hasRegisteredMachines:pe.length>0,userName:M,focusedGroup:_,setFocusedGroup:G,moveTabToGroup:T,splitTabRelative:E,closeGroup:H,handleResizeStart:se,detectedIdes:Y,handleLaunchIde:oe,groupActiveTabIds:je,setGroupActiveTabIds:V,groupTabOrders:ae,setGroupTabOrders:W,toggleHiddenTab:be,allowTabShortcuts:!1}):e.jsx(qu,{visibleConversations:X,clearedTabs:C,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:d,hasRegisteredMachines:pe.length>0,initialDataLoaded:N,userName:M,detectedIdes:Y,handleLaunchIde:oe,toggleHiddenTab:be,actionShortcuts:wt,registerActionHandlers:Z=>{F.current=Z},onActiveTabChange:ne,requestedActiveTabKey:J,onRequestedActiveTabConsumed:ie,scrollToBottomRequest:te}),st&&e.jsx(np,{machines:pe,conversations:h,ides:S,onClose:()=>ze(!1),onBrowseDirectory:de,onSaveWorkspace:ye,onLaunchIde:we,onLaunchProvider:L,onListSavedSessions:ge,sendDaemonCommand:u,onOpenConversation:Z=>{ze(!1),ue(Z),ne(Z.tabKey)}}),Be&&e.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:O,children:e.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:Z=>Z.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),e.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."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:O,"aria-label":"Close dashboard guide",children:e.jsx(vt,{size:14})})]}),e.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(Z=>e.jsx("button",{type:"button",className:`btn btn-sm ${at===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(Z.id),children:Z.label},Z.id))}),at==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]})]})]})]}),at==="quickstart"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),e.jsxs("div",{children:[e.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."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]}),e.jsxs("div",{children:[e.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."]})]})]})]}),at==="shortcuts"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[e.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(Z=>e.jsx("button",{type:"button",className:`btn btn-sm ${Ke===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>ct(Z.id),children:Z.label},Z.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Se,children:"Disable all"}),e.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:Me,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:le.map(Z=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${bt===Z.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:Z.defaultShortcut})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.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:bt===Z.id?Tt.length>0?`${Tt.join(" ")} ...`:"Listening...":wt[Z.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{B(Z.id),U([])},children:bt===Z.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ie={...wt};Ie[Z.id]="",q(Ie)},children:"Disable"})]})]})},Z.id))}),e.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."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:Re,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 ${gt?"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:[e.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:"?"}),gt&&e.jsx("span",{children:"Guide"})]})]})}const Fr=[{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 lp({onClose:t}){const[s,r]=a.useState(0),n=Fr[s],o=s===Fr.length-1;return e.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&&t()},children:[e.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:[e.jsx("button",{onClick:t,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:e.jsx(vt,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Fr.map((i,c)=>e.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))}),e.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),e.jsxs("div",{style:{textAlign:"center"},children:[e.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[e.jsx("span",{children:n.icon})," ",n.title]}),e.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&e.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:[e.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),o&&e.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 →"})]}),e.jsxs("div",{className:"flex justify-between items-center mt-6",children:[e.jsx("button",{onClick:t,className:"btn btn-secondary border-none",children:"Skip"}),e.jsx("button",{onClick:()=>o?t():r(i=>i+1),className:"btn btn-primary",children:o?"Get Started →":"Next →"})]})]}),e.jsx("style",{children:`
56
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
57
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
58
- `})]})}function dp({hasExtensions:t,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:o}){return t?e.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[e.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",p=i.status==="generating";return e.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:[e.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":p?"var(--accent-primary)":"var(--text-muted)",boxShadow:p?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&e.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 up({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,l]=a.useState(()=>i||"native"),p=a.useMemo(()=>No(s),[s]),x=a.useMemo(()=>t?Nn(t,n,{machineNames:p,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,p,r]),m=a.useMemo(()=>x.find(b=>b.streamSource==="native"),[x]),h=a.useMemo(()=>x.filter(b=>b.streamSource==="agent-stream"),[x]),y=a.useMemo(()=>t?Dt(x,t.id):null,[x,t]);a.useEffect(()=>{i&&l(i)},[i]),a.useEffect(()=>{if(i||!y)return;const b=y.streamSource==="native"?"native":y.tabKey;!b||c===b||c==="native"&&l(b)},[c,y,i]),a.useEffect(()=>{var b;c!=="native"&&(h.some(v=>v.tabKey===c)||l(((b=h[0])==null?void 0:b.tabKey)||"native"))},[c,h]),a.useEffect(()=>{c==="native"&&(m||h[0]&&l(h[0].tabKey))},[c,m,h]);const S=a.useMemo(()=>c==="native"&&m?m:h.find(b=>b.tabKey===c)||y||m||h[0],[c,m,y,h]),I=a.useMemo(()=>h.map(b=>({tabKey:b.tabKey,title:vo(b)||o,status:b.status})),[h,o]),u=a.useCallback(b=>{if(b)return x.find(v=>v.sessionId===b||v.routeId===b||v.tabKey===b)},[x]);return{activeChatTab:c,setActiveChatTab:l,activeConv:S,conversations:x,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:u}}function pp({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:p,isStandalone:x,userName:m,onOpenHistory:h,onConversationChange:y,onClose:S}){const[I,u]=a.useState("split"),[b,v]=a.useState(()=>Bt(t)?"native":t.tabKey),d=a.useRef(null),N=a.useMemo(()=>s||r.find(T=>T.id===t.routeId),[t.routeId,s,r]),M=a.useMemo(()=>Ze((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:k,extensionTabs:f,hasExtensions:g}=up({ideData:N,allIdes:r,connectionStates:n,localUserMessages:i,ideName:M||"IDE",preferredTabKey:Bt(t)?void 0:t.tabKey}),w=a.useMemo(()=>N?Dt(k,N.id):null,[N,k]);a.useEffect(()=>{const T=d.current,E={routeId:t.routeId,tabKey:t.tabKey,streamSource:t.streamSource};if(d.current=E,!(T&&T.routeId===E.routeId&&T.tabKey===E.tabKey&&T.streamSource===E.streamSource)){if(Bt(t)){v("native");return}v(t.tabKey)}},[t.routeId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(b==="native"){if(k.some(T=>T.streamSource==="native"))return;(w==null?void 0:w.streamSource)==="agent-stream"&&v(w.tabKey);return}if(!k.some(T=>T.tabKey===b)){if((w==null?void 0:w.streamSource)==="agent-stream"){v(w.tabKey);return}v("native")}},[k,b,w]);const j=a.useMemo(()=>b==="native"?k.find(T=>T.streamSource==="native")||t:k.find(T=>T.tabKey===b)||t,[t,k,b]),$=Wo(j),D=a.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...j,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:j,[j,$]),K=dr(D),R=jr({sendDaemonCommand:c,activeConv:D,setLocalUserMessages:l,setActionLogs:p,isStandalone:x}),{connScreenshot:z,screenshotUsage:P,handleRemoteAction:C}=Zo({doId:K,targetSessionId:wn(D),connState:D.connectionState||"new",viewMode:I}),_=a.useMemo(()=>o.filter(T=>T.routeId===D.tabKey),[o,D.tabKey]);a.useEffect(()=>{y==null||y(D)},[D,y]),a.useEffect(()=>{const T=E=>{E.key==="Escape"&&S()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[S]);const G=a.useCallback(T=>{T.stopPropagation()},[]);return e.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:S,children:e.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:G,children:[e.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:[e.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[e.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:e.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:[e.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:e.jsx(Nt,{size:16})}),e.jsx("span",{className:"truncate",children:wr(j)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:S,children:"Close"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[e.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(T=>{const E=I===T;return e.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${E?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>u(T),title:T==="split"?"Split view":"Remote only",children:T==="split"?e.jsx(tc,{size:15}):e.jsx(Nt,{size:15})},T)})}),e.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),e.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>h(j),title:"Chat History",children:[e.jsx(fn,{size:14,className:"md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:"History"})]}),e.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:S,children:"Close"})]})]}),e.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${I==="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:[I!=="remote"&&e.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${I==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[e.jsx(dp,{hasExtensions:g,ideName:M||"IDE",activeChatTab:b,extensionTabs:f,onSelectTab:v}),e.jsx(oo,{activeConv:D,onModalButton:R.handleModalButton}),e.jsx(tn,{activeConv:D,ideEntry:N,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:_,userName:m})]}),e.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${I==="split"?"order-1 md:order-2":""}`,children:e.jsx(no,{addLog:()=>{},connState:D.connectionState||"new",connScreenshot:z,screenshotUsage:P,transportType:D.transport,onAction:C})})]})]})})}function mp({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=vl(t);return e.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-center justify-center p-4",children:[e.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.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:[e.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[e.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),e.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."})]}),e.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&e.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),e.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"}),e.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function fp({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:p,onNewHistoryChat:x,onSwitchHistorySession:m,onRefreshHistory:h,onResumeSavedHistorySession:y,remoteDialogConv:S,remoteDialogIdeEntry:I,connectionStates:u,actionLogs:b,localUserMessages:v,sendDaemonCommand:d,setLocalUserMessages:N,setActionLogs:M,isStandalone:k,userName:f,onOpenRemoteHistory:g,onRemoteConversationChange:w,onCloseRemoteDialog:j,cliStopDialogOpen:$,cliStopTargetConv:D,onCancelCliStop:K,onStopCliNow:R,onSaveCliAndStop:z,toasts:P,onDismissToast:C,onClickToast:_,showOnboarding:G,onCloseOnboarding:T}){var E;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(kn,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,onClose:p,onNewChat:x,onSwitchSession:m,onRefreshHistory:h,onResumeSavedSession:y}),S&&e.jsx(pp,{activeConv:S,ideEntry:I,ides:r,connectionStates:u,actionLogs:b,localUserMessages:v,sendDaemonCommand:d,setLocalUserMessages:N,setActionLogs:M,isStandalone:k,userName:f,onOpenHistory:g,onConversationChange:w,onClose:j}),$&&D&&(Xe(D)||Ve(D))&&e.jsx(mp,{activeConv:D,canSaveAndStop:Xe(D)&&!Ve(D)&&!!((E=D.resume)!=null&&E.supported),onCancel:K,onStopNow:R,onSaveAndStop:z}),e.jsx(ko,{toasts:P,onDismiss:C,onClickToast:_}),G&&e.jsx(lp,{onClose:T})]})}function xp({daemons:t,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:o,onDismiss:i}){return t.length===0?null:e.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:[e.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:e.jsx(xs,{size:14})}),e.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[e.jsxs("span",{children:[r?"Daemon update required":"Update available",s?e.jsxs(e.Fragment,{children:[": ",e.jsxs("strong",{children:["v",s]})]}):null]}),t.map(c=>{const l=kt(c,{fallbackId:c.id}),p=n[c.id],x=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[e.jsx("span",{className:"font-medium text-text-primary",children:l}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",x]}),m&&e.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),p==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:m?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):p==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):p==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:m?"Update now":"Upgrade"})]},c.id)})]}),!r&&e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:e.jsx(vt,{size:16})})]})}function hp(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Ea(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bp(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function gp(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function yp(){var $n,Bn,Kn,Wn,On;const{sendCommand:t}=St(),s=Ks(),r=un(),n=fs(),[o,i]=Di(),c=o.get("activeTab"),l=(($n=r.state)==null?void 0:$n.openRemoteForTabKey)||null,p=((Bn=r.state)==null?void 0:Bn.openMachineId)||null,x=((Kn=r.state)==null?void 0:Kn.mobileSection)||null,m=ho(),h=m.ides||[],y=m.initialLoaded??!0,{updateRouteChats:S,setToasts:I}=m,[u,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),v=m.toasts||[],d=m.wsStatus||"connected",N=m.isConnected??!0,M=m.connectionStates||{},k=m.showReconnected||!1,{groupAssignments:f,setGroupAssignments:g,focusedGroup:w,setFocusedGroup:j,groupActiveTabIds:$,setGroupActiveTabIds:D,groupTabOrders:K,setGroupTabOrders:R,groupSizes:z,setGroupSizes:P,isMobile:C,hasHydratedStoredLayout:_,hydrateStoredLayout:G}=su(),[T,E]=a.useState(!1),[H,se]=a.useState(!1),[Y,oe]=a.useState(null),[je,V]=a.useState([]),[ae,W]=a.useState(!1),[be,X]=a.useState(null),[J]=a.useState(()=>Bo()),[ie,ne]=a.useState([]),[he,ue]=a.useState({}),[fe,te]=a.useState({}),[pe,de]=a.useState(null),[ye,we]=a.useState(null),[L,ge]=a.useState(null),F=a.useRef(null);Es("Dashboard",{ideCount:h.length,toastCount:v.length,focusedGroup:w,groupCount:Object.keys(f).length,localMessageTabs:Object.keys(he).length,actionLogCount:ie.length});const me=h.find(ve=>ve.type==="adhdev-daemon"),Ce=(me==null?void 0:me.detectedIdes)||[],xe=a.useMemo(()=>h.filter(ve=>ve.type==="adhdev-daemon").sort(gn),[h]),Le=!!me;a.useEffect(()=>{!me||!(!me.detectedIdes||!me.availableProviders||!me.recentLaunches||!me.workspaces)||s(me.id,{minFreshMs:3e4}).catch(()=>{})},[me,s]);const Be=(me==null?void 0:me.terminalBackend)||null,Fe=me?kt(me,{fallbackId:me.id}):null,st=(me==null?void 0:me.id)||null,{hiddenTabs:ze,hideTab:dt,toggleTab:gt,showTab:Ge,showAllTabs:at}=Dd(),{chatIdes:ot,conversations:Ke,visibleConversations:ct,visibleTabKeys:ut,resolveConversationBySessionId:it,resolveConversationByTarget:Q}=Ud({ides:h,connectionStates:M,localUserMessages:he,clearedTabs:fe,hiddenTabs:ze}),_e=a.useMemo(()=>$s(h),[h]),Re=a.useRef(null),{containerRef:We,normalizedGroupAssignments:Ct,numGroups:pt,isSplitMode:wt,groupedConvs:bt,moveTabToGroup:Tt,closeGroup:B,handleResizeStart:U,splitTabRelative:q}=du({groupAssignments:f,setGroupAssignments:g,setFocusedGroup:j,setGroupActiveTabIds:D,setGroupTabOrders:R,groupSizes:z,setGroupSizes:P,isMobile:C,visibleConversations:ct,visibleTabKeys:ut}),O=a.useMemo(()=>{var Te,Ne;if(!C){if(pe){const ke=Ke.find($e=>$e.tabKey===pe);if(ke)return ke}return ct[0]}const ve=$[w];if(ve){const ke=Ke.find($e=>$e.tabKey===ve);if(ke)return ke}return((Te=bt[w])==null?void 0:Te[0])||((Ne=bt[0])==null?void 0:Ne[0])},[pe,C,$,w,Ke,bt,ct]);a.useEffect(()=>{if(C){Re.current=null;return}if(!(O!=null&&O.sessionId)){Re.current=null;return}const ve=`${O.tabKey}:${O.sessionId}`;if(Re.current===ve)return;const Te=()=>{if(document.visibilityState!=="visible"||Re.current===ve)return;Re.current=ve;const Ne=Ps(O,_e),ke=Math.max(Date.now(),Ht(O),Ne.lastUpdated||0);t(O.daemonId||O.routeId,"mark_session_seen",{sessionId:O.sessionId,seenAt:ke}).catch(()=>{})};if(document.visibilityState==="visible"){const Ne=setTimeout(Te,1500),ke=()=>{document.visibilityState!=="visible"&&clearTimeout(Ne)};return document.addEventListener("visibilitychange",ke),()=>{clearTimeout(Ne),document.removeEventListener("visibilitychange",ke)}}else{const Ne=()=>{document.visibilityState==="visible"&&(setTimeout(Te,800),document.removeEventListener("visibilitychange",Ne))};return document.addEventListener("visibilitychange",Ne),()=>{document.removeEventListener("visibilitychange",Ne)}}},[O,C,_e,t]);const{requestedDesktopTabKey:le,requestedMobileTabKey:Se,consumeRequestedActiveTab:Me}=zd({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:it,setSearchParams:i}),{remoteDialogConv:Z,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:De,setRemoteDialogActiveConv:Ue,openRemoteDialog:A,closeRemoteDialog:ee}=au({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:le,conversations:Ke,ides:h,resolveConversationByTarget:Q}),re=De||Z||O,ce=!!re&&Xe(re)&&!Ve(re),Pe=a.useMemo(()=>{if(!re||!ce)return null;const ve=re.daemonId||re.routeId||"",Te=jt(re);return`${ve}:${Te}`},[re,ce]),Ae=a.useMemo(()=>ct,[ct]),Oe=C&&J==="chat",rt=a.useMemo(()=>Ke.filter(ve=>ze.has(ve.tabKey)),[Ke,ze]),Ye=a.useCallback(ve=>{const Te=new URLSearchParams(o);Te.set("activeTab",ve),i(Te,{replace:!0})},[o,i]),qe=a.useCallback(async(ve,Te)=>Nr(t,ve,Te),[t]),He=a.useCallback(async(ve,Te)=>{if(!Te.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ne=await t(ve,"workspace_add",{path:Te.trim()});return Ne!=null&&Ne.success?{ok:!0}:{ok:!1,error:(Ne==null?void 0:Ne.error)||"Could not save workspace"}}catch(Ne){return{ok:!1,error:Ne instanceof Error?Ne.message:"Could not save workspace"}}},[t]),as=a.useCallback(async(ve,Te,Ne)=>{var ke;try{const $e={ideType:Te,enableCdp:!0};(ke=Ne==null?void 0:Ne.workspacePath)!=null&&ke.trim()&&($e.workspace=Ne.workspacePath.trim());const lt=await t(ve,"launch_ide",$e);return!(lt!=null&&lt.success)&&(lt==null?void 0:lt.success)!==void 0?{ok:!1,error:(lt==null?void 0:lt.error)||"Could not launch IDE"}:(ge({machineId:ve,kind:"ide",providerType:Te,workspacePath:(Ne==null?void 0:Ne.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch($e){return{ok:!1,error:$e instanceof Error?$e.message:"Could not launch IDE"}}},[t]),Ws=a.useCallback(async(ve,Te,Ne,ke)=>{var lt,bs,os;const $e=Date.now();try{const _t={cliType:Ne};(lt=ke==null?void 0:ke.workspacePath)!=null&&lt.trim()?_t.dir=ke.workspacePath.trim():ke!=null&&ke.workspaceId&&(_t.workspaceId=ke.workspaceId),(bs=ke==null?void 0:ke.resumeSessionId)!=null&&bs.trim()&&(_t.resumeSessionId=ke.resumeSessionId.trim()),Array.isArray(ke==null?void 0:ke.cliArgs)&&ke.cliArgs.length>0&&(_t.cliArgs=ke.cliArgs),(os=ke==null?void 0:ke.initialModel)!=null&&os.trim()&&(_t.initialModel=ke.initialModel.trim());const mt=await t(ve,"launch_cli",_t),yt=(mt==null?void 0:mt.result)||mt,gs=(yt==null?void 0:yt.sessionId)||(yt==null?void 0:yt.id);return mt!=null&&mt.success&&gs?(Ye(gs),{ok:!0}):mt!=null&&mt.success?(ge({machineId:ve,kind:Te,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:(mt==null?void 0:mt.error)||(yt==null?void 0:yt.error)||`Could not launch ${Te.toUpperCase()} session`}}catch(_t){return bp(_t)?(ge({machineId:ve,kind:Te,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:_t instanceof Error?_t.message:`Could not launch ${Te.toUpperCase()} session`}}},[Ye,t]),ci=a.useCallback(async(ve,Te)=>{if(!ve||!Te)return[];try{const Ne=await t(ve,"list_saved_sessions",{providerType:Te,kind:"cli",limit:30}),ke=(Ne==null?void 0:Ne.result)??Ne;return Array.isArray(ke==null?void 0:ke.sessions)?ke.sessions:[]}catch(Ne){return console.error("List saved sessions failed",Ne),[]}},[t]);a.useEffect(()=>{var ke;if(!L)return;const ve=Ea(L.workspacePath),Te=h.find($e=>{var mt,yt,gs,Hn;if(!$e||$e.type==="adhdev-daemon"||hp($e.daemonId||$e.id)!==L.machineId||(Rs($e)?"cli":ds($e)?"acp":"ide")!==L.kind||String($e.agentType||$e.type||"")!==L.providerType)return!1;if(L.resumeSessionId)return String($e.providerSessionId||"")===L.resumeSessionId;if(ve){const Mr=Ea($e.workspace||$e.runtimeWorkspaceLabel);return Mr?Mr===ve:!1}return Number($e.lastUpdated||$e._lastUpdate||$e.timestamp||((Hn=(gs=(yt=(mt=$e.activeChat)==null?void 0:mt.messages)==null?void 0:yt.at)==null?void 0:gs.call(yt,-1))==null?void 0:Hn.timestamp)||0)>=L.startedAt-5e3});if(!Te)return;const Ne=typeof Te.sessionId=="string"&&Te.sessionId?Te.sessionId:typeof Te.instanceId=="string"&&Te.instanceId?Te.instanceId:(ke=Ke.find($e=>$e.routeId===Te.id))==null?void 0:ke.sessionId;Ne&&(ge(null),Ye(Ne))},[Ke,Ye,h,L]),a.useEffect(()=>{if(!L)return;const ve=window.setTimeout(()=>{ge(Te=>!Te||Te.startedAt!==L.startedAt?Te:null)},45e3);return()=>window.clearTimeout(ve)},[L]),Ed({visibleConversations:ct,clearedTabs:fe,setClearedTabs:te,setActionLogs:ne}),Fd({ides:h,sendDaemonCommand:t,setToasts:I,setLocalUserMessages:ue,resolveConversationByTarget:Q});const{isRefreshingHistory:li,handleLaunchIde:di,handleRefreshHistory:ui}=ya({sendDaemonCommand:t,activeConv:O,chats:(Wn=h.find(ve=>ve.id===(O==null?void 0:O.routeId)))==null?void 0:Wn.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:ue,setClearedTabs:te}),{isCreatingChat:pi,isRefreshingHistory:mi,handleSwitchSession:fi,handleNewChat:xi,handleRefreshHistory:hi}=ya({sendDaemonCommand:t,activeConv:re,chats:(On=h.find(ve=>ve.id===(re==null?void 0:re.routeId)))==null?void 0:On.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:ue,setClearedTabs:te}),Ir=a.useCallback(async()=>{if(!(!re||!ce||ae)){W(!0);try{const ve=re.daemonId||re.routeId,Te=jt(re),Ne=await t(ve,"list_saved_sessions",{agentType:Te,providerType:Te,kind:"cli",limit:50}),ke=(Ne==null?void 0:Ne.result)??Ne;V(Array.isArray(ke==null?void 0:ke.sessions)?ke.sessions:[])}catch(ve){console.error("Refresh saved sessions failed",ve),V([])}finally{W(!1)}}},[re,ae,ce,t]);a.useEffect(()=>{if(!T){F.current=null;return}if(!ce){F.current=null,V([]),W(!1);return}!Pe||ae||F.current!==Pe&&(F.current=Pe,Ir())},[Ir,T,ae,ce,Pe]);const bi=a.useCallback(async ve=>{if(!re||!ce||!ve.providerSessionId||!ve.workspace)return;const Te=re.daemonId||re.routeId,Ne=jt(re);try{X(ve.providerSessionId);const ke=await t(Te,"launch_cli",{cliType:Ne,dir:ve.workspace,resumeSessionId:ve.providerSessionId,initialModel:ve.currentModel}),$e=(ke==null?void 0:ke.result)??ke,lt=typeof($e==null?void 0:$e.sessionId)=="string"?$e.sessionId:typeof($e==null?void 0:$e.id)=="string"?$e.id:"";lt&&i(bs=>{const os=new URLSearchParams(bs);return os.set("activeTab",lt),os},{replace:!0}),E(!1)}catch(ke){console.error("Resume saved session failed",ke)}finally{X(null)}},[re,ce,t,i]);nu({urlActiveTab:C&&!Oe?c:null,conversations:Ke,resolveConversationBySessionId:it,normalizedGroupAssignments:Ct,hasHydratedStoredLayout:C&&!Oe?_:!0,hydrateStoredLayout:C&&!Oe?G:()=>{},setGroupActiveTabIds:D,setFocusedGroup:j,setSearchParams:i,historyModalOpen:T,activeConv:O,isRefreshingHistory:li,ides:h,handleRefreshHistory:ui});const Ln=a.useCallback(async(ve,Te)=>{const Ne=Te||Y||O;if(!Ne||!Xe(Ne)&&!Ve(Ne))return;const ke=jt(Ne),$e=Ne.routeId||Ne.daemonId||"";try{await t($e,"stop_cli",{cliType:ke,targetSessionId:Ne.sessionId,mode:ve})}catch(lt){console.error("Stop CLI failed:",lt)}},[O,Y,t]),gi=a.useCallback(async ve=>{const Te=ve||O;!Te||!Xe(Te)&&!Ve(Te)||(oe(Te),se(!0))},[O]),yi=a.useMemo(()=>!O||!Xe(O)||Ve(O)?null:ms(O),[O]),vi=a.useCallback(async ve=>{if(!(!O||!Xe(O)||Ve(O)||ms(O)===ve))try{await t(zt(O)||O.routeId,"set_cli_view_mode",{targetSessionId:O.sessionId,cliType:jt(O),mode:ve})}catch(Ne){gp(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},[O,t]),{versionMismatchDaemons:wi,hasRequiredVersionDaemons:Rn,appVersion:ji,versionBannerDismissed:ki,setVersionBannerDismissed:Ni,upgradingDaemons:Si,handleBannerUpgrade:Ci}=uu({ides:h,sendDaemonCommand:t}),Dn=a.useCallback(ve=>{de(ve.tabKey),i(Te=>{const Ne=new URLSearchParams(Te),ke=Jc(ve);return ke?Ne.set("activeTab",ke):Ne.delete("activeTab"),Ne},{replace:!0})},[i]),En=a.useCallback(ve=>{Ge(ve.tabKey),Dn(ve)},[Dn,Ge]),Ii=a.useCallback(ve=>{dt(ve.tabKey)},[dt]);return e.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[e.jsx(jl,{wsStatus:d,showReconnected:k}),e.jsx(kl,{terminalBackend:Be,isStandalone:Le,machineLabel:Fe,machineKey:st}),(!ki||Rn)&&e.jsx(xp,{daemons:wi,targetVersion:ji,required:Rn,upgradingDaemons:Si,onUpgrade:Ci,onDismiss:()=>Ni(!0)}),e.jsx(cp,{showMobileChatMode:Oe,isMobile:C,activeConv:O,chatIdes:ot,wsStatus:d,isConnected:N,onOpenHistory:ve=>{ve&&Ue(ve),E(!0)},onOpenRemote:A,onStopCli:gi,activeCliViewMode:yi,onSetActiveCliViewMode:vi,mobileChatConversations:Ae,ides:h,actionLogs:ie,sendDaemonCommand:t,setLocalUserMessages:ue,setActionLogs:ne,isStandalone:Le,initialDataLoaded:y,userName:m.userName,requestedMobileTabKey:Se,onRequestedMobileTabConsumed:Me,requestedMachineId:p,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:x,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:We,isSplitMode:wt,numGroups:pt,groupSizes:z,groupedConvs:bt,clearedTabs:fe,focusedGroup:w,setFocusedGroup:j,moveTabToGroup:Tt,splitTabRelative:q,closeGroup:B,handleResizeStart:U,detectedIdes:Ce,handleLaunchIde:di,groupActiveTabIds:$,setGroupActiveTabIds:D,groupTabOrders:K,setGroupTabOrders:R,toggleHiddenTab:gt,visibleConversations:ct,hiddenConversations:rt,requestedDesktopTabKey:le,onRequestedDesktopTabConsumed:Me,onDesktopActiveTabChange:de,onHideConversation:Ii,onShowHiddenConversation:En,onShowAllHiddenConversations:at,scrollToBottomRequest:ye,machineEntries:xe,onBrowseMachineDirectory:qe,onSaveMachineWorkspace:He,onLaunchMachineIde:as,onLaunchMachineProvider:Ws,onListMachineSavedSessions:ci}),e.jsx("style",{children:`
59
- body { overflow: hidden; overscroll-behavior: none; }
60
- `}),e.jsx(fp,{historyModalOpen:T,historyTargetConv:re,ides:h,isHistoryCreatingChat:pi,isHistoryRefreshingHistory:ce?!1:mi,savedHistorySessions:je,isSavedHistoryLoading:ae,isResumingSavedHistorySessionId:be,onCloseHistory:()=>E(!1),onNewHistoryChat:xi,onSwitchHistorySession:fi,onRefreshHistory:ce?Ir:hi,onResumeSavedHistorySession:bi,remoteDialogConv:Z,remoteDialogIdeEntry:Ie,connectionStates:M,actionLogs:ie,localUserMessages:he,sendDaemonCommand:t,setLocalUserMessages:ue,setActionLogs:ne,isStandalone:Le,userName:m.userName,onOpenRemoteHistory:ve=>{ve&&Ue(ve),E(!0)},onRemoteConversationChange:Ue,onCloseRemoteDialog:ee,cliStopDialogOpen:H,cliStopTargetConv:Y,onCancelCliStop:()=>{se(!1),oe(null)},onStopCliNow:async()=>{se(!1),await Ln("hard",Y),oe(null)},onSaveCliAndStop:async()=>{se(!1),await Ln("save",Y),oe(null)},toasts:v,onDismissToast:ve=>I(Te=>Te.filter(Ne=>Ne.id!==ve)),onClickToast:ve=>{if(ve.targetKey){const Te=Q(ve.targetKey);Te&&(j(Ct.get(Te.tabKey)??0),En(Te),we({tabKey:Te.tabKey,nonce:Date.now()}))}},showOnboarding:u,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function vp({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[l,p]=a.useState(null),[x,m]=a.useState(null),[h,y]=a.useState(!1),[S,I]=a.useState(null),[u,b]=a.useState(!1),[v,d]=a.useState(""),N=a.useRef(null),M=a.useCallback(T=>{N.current=T},[]),k=a.useCallback((T,E,H=!1)=>{c(se=>[...se.slice(-100),{timestamp:Date.now(),level:T,message:E}]),setTimeout(()=>{var se;return(se=o.current)==null?void 0:se.scrollIntoView({behavior:"smooth"})},100),H&&ht.showToast(E,T==="error"||T==="warn"?"warning":"success")},[o]),f=a.useCallback(T=>{const E=T instanceof Error?T.message:String(T||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),g=a.useCallback(async(T,E)=>{var H;if(!t||l)return!1;p(T),k("info",`Launching ${Ze(T)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const se={ideType:T,enableCdp:!0};(H=E==null?void 0:E.workspace)!=null&&H.trim()?se.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(se.useDefaultWorkspace=!0);const Y=await r(t,"launch_ide",se);return k(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${Ze(T)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(se){return k("error",`Launch error: ${se.message}`,!0),!1}finally{p(null)}},[t,l,k,r]),w=a.useCallback(async T=>{if(!t)return{success:!1};const{cliType:E,dir:H,workspaceId:se,useDefaultWorkspace:Y,useHome:oe,argsStr:je,model:V,resumeSessionId:ae}=T;if(!E)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const W=je?je.split(/\s+/).filter(Boolean):void 0,be=(H==null?void 0:H.trim())||(se?"(saved id)":Y?"(default workspace)":oe?"(home)":"");k("info",`Launching ${E}${be?` in ${be}`:""}${V?` (model: ${V})`:""}...`),m(E);try{const X={cliType:E,cliArgs:W,initialModel:V||void 0};H!=null&&H.trim()?X.dir=H.trim():se?X.workspaceId=se:Y?X.useDefaultWorkspace=!0:oe&&(X.useHome=!0),ae&&(X.resumeSessionId=ae);const J=await r(t,"launch_cli",X),ie=(J==null?void 0:J.result)||J;return J!=null&&J.success?(k("info",`${E} launched`,!0),(ie==null?void 0:ie.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(ie==null?void 0:ie.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ie==null?void 0:ie.sessionId}):(k("error",`Failed: ${(J==null?void 0:J.error)||(ie==null?void 0:ie.error)}`,!0),(J==null?void 0:J.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&I({cliType:E,argsStr:je,model:V}),{success:!1,sessionId:ie==null?void 0:ie.sessionId})}catch(X){return f(X)?(k("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${X.message}`,!0),{success:!1})}finally{m(null)}},[t,k,f,r]),j=a.useCallback(async(T,E,H,se)=>t?T?E.trim()?w({cliType:T,dir:E,argsStr:H,model:se}):(I({cliType:T,argsStr:H,model:se}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[t,k,w]),$=a.useCallback(async(T,E,H)=>{if(t&&window.confirm(`Stop ${T}?
61
- This will terminate the process.`))try{const se=await r(t,"stop_cli",{cliType:T,dir:E,targetSessionId:H});se!=null&&se.success?k("info",`${T} stopped`,!0):k("error",`Stop failed: ${(se==null?void 0:se.error)||"Unknown error"}`,!0)}catch(se){k("error",`Stop failed: ${se.message}`,!0)}},[t,k,r]),D=a.useCallback(async T=>{try{await r(T.daemonId,"restart_ide",{ideType:T.type}),k("info",`${Ze(T.type)} restart initiated`,!0)}catch(E){k("error",`Restart failed: ${E.message}`,!0)}},[k,r]),K=a.useCallback(async T=>{if(window.confirm(`Stop ${Ze(T.type)}?
62
- This will disconnect CDP and optionally kill the process.`))try{const E=await r(T.daemonId,"stop_ide",{ideType:T.type,killProcess:!0});E!=null&&E.success?k("info",`${Ze(T.type)} stopped`,!0):k("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){k("error",`Stop failed: ${E.message}`,!0)}},[k,r]),R=a.useCallback(async()=>{if(t)try{const T=await r(t,"detect_ides",{});k("info",`Found ${((T==null?void 0:T.result)||[]).length} IDE(s)`,!0)}catch(T){k("error",`Detection failed: ${T.message}`,!0)}},[t,k,r]),z=a.useCallback(async T=>{if(!t||!T.trim())return!1;y(!0);try{const E=await r(t,"workspace_add",{path:T.trim()});return E!=null&&E.success?(k("info",`Workspace added: ${T.trim()}`),!0):(k("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return k("error",E.message),!1}finally{y(!1)}},[t,k,r]),P=a.useCallback(async T=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const E=await r(t,"workspace_remove",{id:T});E!=null&&E.success?k("info","Workspace removed",!0):k("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){k("error",E.message,!0)}finally{y(!1)}}},[t,k,r]),C=a.useCallback(async T=>{var E;if(t){y(!0);try{const H=await r(t,"workspace_set_default",T===null?{clear:!0}:{id:T});if(H!=null&&H.success){k("info",T?"Default workspace updated":"Default workspace cleared",!0);const se=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";se&&((E=N.current)==null||E.call(N,se))}else k("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){k("error",H.message,!0)}finally{y(!1)}}},[t,k,r]),_=a.useCallback(async T=>{var H;if(!t||!T.trim())return;const E=T.trim();y(!0);try{const se=await r(t,"workspace_set_default",{path:E});se!=null&&se.success?(k("info","Default workspace set from history"),(H=N.current)==null||H.call(N,E)):k("error",(se==null?void 0:se.error)||"Could not set default (path missing on disk?)")}catch(se){k("error",se.message)}finally{y(!1)}},[t,k,r]),G=a.useCallback(async()=>{if(t)try{if(await r(t,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:t,registeredMachineId:s,nickname:v})}catch(T){k("warn",`Live nickname updated, but account sync failed: ${T.message}`)}k("info",`Nickname set to "${v||"(cleared)"}"`),b(!1)}catch(T){k("error",`Failed: ${T.message}`)}},[t,v,s,k,n,r]);return{logs:i,launchingIde:l,launchingAgentType:x,workspaceBusy:h,launchPick:S,setLaunchPick:I,editingNickname:u,setEditingNickname:b,nicknameInput:v,setNicknameInput:d,addLog:k,handleLaunchIde:g,runLaunchCliCore:w,handleLaunchCli:j,handleStopCli:$,handleRestartIde:D,handleStopIde:K,handleDetectIdes:R,handleWorkspaceAdd:z,handleWorkspaceRemove:P,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:_,handleSaveNickname:G,setOnDefaultWorkspaceChanged:M}}function wp({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var D;const{workspaceBusy:l,handleWorkspaceAdd:p,handleWorkspaceRemove:x,handleWorkspaceSetDefault:m}=i,[h,y]=a.useState(!1),[S,I]=a.useState(""),[u,b]=a.useState([]),[v,d]=a.useState(!1),[N,M]=a.useState(""),k=a.useCallback(async K=>{d(!0),M("");try{const R=await Nr(c,t,K);I(R.path),b(R.directories)}catch(R){M(R instanceof Error?R.message:"Could not load folder")}finally{d(!1)}},[t,c]),f=a.useCallback(()=>{var R;y(!0);const K=kr(s.platform,[s.defaultWorkspacePath,(R=s.workspaces[0])==null?void 0:R.path]);k(K)},[k,s.defaultWorkspacePath,s.platform,s.workspaces]),g=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,j=g&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,$=((D=s.loadavg)==null?void 0:D[0])||0;return e.jsxs("div",{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[e.jsx(Hs,{icon:e.jsx(eo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Kc(s.uptime):"Waiting…"}),e.jsx(Hs,{icon:e.jsx(Nt,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Hs,{icon:e.jsx(gr,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Hs,{icon:e.jsx(rc,{size:16}),label:"ACPs",value:`${o.length}`})]}),e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx(Yn,{value:g?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:g?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),e.jsx(Yn,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:g?`${_r(s.totalMem-w)} / ${_r(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${_r(s.totalMem)} total`})]})]}),e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[e.jsx(ps,{size:14})," Workspaces"]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),e.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:K=>void m(K.target.value===""?null:K.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(K=>e.jsx("option",{value:K.id,children:K.label||K.path},K.id))]}),s.defaultWorkspacePath&&e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.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:f,children:"Select workspace…"}),e.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&e.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(K=>e.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:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[K.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:vr(K.path,K.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:K.path,children:K.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void x(K.id),children:"Remove"})]},K.id))})]}),h&&e.jsx(Sr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:u,busy:v,error:N,confirmLabel:"Add workspace",onClose:()=>y(!1),onNavigate:K=>{k(K)},onConfirm:K=>{(async()=>{if(!K)return;await p(K)&&y(!1)})()}})]})}function jp(t){if(!t||typeof t!="object")return null;const s=t,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 kp(t,s,r){const n=[];for(const[o,i]of Object.entries(t.settings)){const c=i;if(c.length===0)continue;const l=s.find(p=>p.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:t.values[o]||{}})}return n}const $a=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Np=[{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 Sp({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,l]=a.useState("codex-cli"),[p,x]=a.useState([]),[m,h]=a.useState(""),[y,S]=a.useState([]),[I,u]=a.useState(""),b=a.useRef(null),v=a.useRef(null),d=w=>{x(j=>j.includes(w)?j.filter($=>$!==w):[...j,w])},N=()=>x([...$a]),M=()=>x([]);a.useEffect(()=>{var w;(w=b.current)==null||w.scrollIntoView({behavior:"smooth"})},[y]),a.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const k=a.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const w=await r(t,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&o==="running"&&(i("done"),S(j=>[...j,`
63
- ✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[t,s.type,r,o]),f=async()=>{if(p.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${p.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),u("");try{const w=await r(t,"provider_auto_fix",{providerType:s.type,functions:p,agent:c,...m?{comment:m}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(S(j=>[...j,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),u((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),u((w==null?void 0:w.message)||"Connection failed")}}},g=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),S(w=>[...w,`
64
- ⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.current)}catch{}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.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:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),e.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),e.jsx("div",{className:"flex gap-2",children:Np.map(w=>e.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),e.jsx("button",{onClick:M,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:$a.map(w=>e.jsxs("button",{onClick:()=>d(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:p.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:p.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:p.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[p.includes(w)?"☑ ":"☐ ",w]},w))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:m,onChange:w=>h(w.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")&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),e.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:[y.map((w,j)=>e.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},j)),o==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:b})]}),I&&e.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:I})]})]}),e.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[e.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&p.length>0&&`${p.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),e.jsxs("div",{className:"flex gap-2",children:[o==="config"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:f,disabled:p.length===0,className:"machine-btn",style:{background:p.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:p.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:p.length>0?"#a78bfa":void 0,opacity:p.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:g,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{i("config"),S([]),u("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Cp({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var k;const i=s.filter(f=>f.category==="ide"),[c,l]=a.useState(((k=i[0])==null?void 0:k.type)||""),[p,x]=a.useState(""),[m,h]=a.useState(""),[y,S]=a.useState(!1),[I,u]=a.useState(""),[b,v]=a.useState(!1),d=f=>{const g=f.toLowerCase().replace(/[^a-z0-9-]/g,"");x(g),(!m||m===N(p))&&h(N(g))},N=f=>f.split("-").map(g=>g.charAt(0).toUpperCase()+g.slice(1)).join(" "),M=async()=>{if(!(!p||!m||!c)){S(!0),u("");try{const f=await r(t,"provider_clone",{type:p,name:m,category:"ide",location:"user",cloneFrom:c});f!=null&&f.success||f!=null&&f.created?(v(!0),o==null||o(p)):u((f==null?void 0:f.error)||"Failed to create provider")}catch(f){u((f==null?void 0:f.message)||"Connection failed")}S(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),e.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:b?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),e.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[e.jsx("code",{className:"text-violet-400",children:p})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",p,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",p]})," or use Auto-Fix to implement scripts."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(f=>e.jsxs("button",{onClick:()=>l(f.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===f.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===f.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:f.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===f.type?"#a78bfa":"var(--text-secondary)"},children:f.displayName})]},f.type))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),e.jsx("input",{value:p,onChange:f=>d(f.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"}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",e.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",p||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:m,onChange:f=>h(f.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"})]}),I&&e.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:I})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:b?e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:M,disabled:!p||!m||y,className:"machine-btn",style:{background:p&&m?"rgba(34,197,94,0.12)":void 0,borderColor:p&&m?"rgba(34,197,94,0.3)":void 0,color:p&&m?"#86efac":void 0,opacity:!p||!m||y?.4:1},children:y?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ip({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[l,p]=a.useState(null),[x,m]=a.useState("all"),[h,y]=a.useState(null),[S,I]=a.useState(!1),u=a.useCallback(async()=>{if(t){c(!0);try{const v=await r(t,"get_provider_settings",{}),d=jp(v);if(d){const N=kp(d,s);N.sort((M,k)=>M.category.localeCompare(k.category)||M.displayName.localeCompare(k.displayName)),o(N)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const b=async(v,d,N)=>{p(`${v}.${d}`),o(M=>M.map(k=>k.type===v?{...k,values:{...k.values,[d]:N}}:k));try{const M=await r(t,"set_provider_setting",{providerType:v,key:d,value:N});M!=null&&M.success||u()}catch{u()}p(null)};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(v=>e.jsx("button",{onClick:()=>m(v),className:`machine-btn text-[10px] px-2 py-0.5 ${x===v?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.toUpperCase()},v))]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>I(!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"}),e.jsx("button",{onClick:u,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),x!=="all"&&n.filter(v=>v.category===x).length>1&&(()=>{const v=n.filter(k=>k.category===x),d=new Map;for(const k of v)for(const f of k.schema){if(f.type!=="boolean")continue;const g=d.get(f.key),w=!!(k.values[f.key]??f.default);g?(g.onCount+=w?1:0,g.total+=1):d.set(f.key,{label:f.label||f.key,onCount:w?1:0,total:1})}const N=[...d.entries()].filter(([,k])=>k.total===v.length);if(N.length===0)return null;const M=async(k,f)=>{for(const g of v)await b(g.type,k,f)};return e.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[e.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",x.toUpperCase()," providers (",v.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(([k,f])=>{const g=f.onCount===f.total,w=f.onCount===0;return e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:"text-text-secondary font-medium",children:f.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",f.onCount,"/",f.total,")"]}),e.jsx("button",{onClick:()=>void M(k,!0),disabled:g,className:`machine-btn text-[9px] px-1.5 py-px ${g?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void M(k,!1),disabled:w,className:`machine-btn text-[9px] px-1.5 py-px ${w?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},k)})})]})})(),i&&n.length===0?e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):e.jsx("div",{className:"flex flex-col gap-2",children:n.filter(v=>x==="all"||v.category===x).map(v=>e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx("span",{className:"text-lg",children:v.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:v.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:v.category==="acp"?"rgba(139,92,246,0.08)":v.category==="cli"?"rgba(59,130,246,0.08)":v.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:v.category==="acp"?"#a78bfa":v.category==="cli"?"#60a5fa":v.category==="ide"?"#86efac":"var(--status-warning)"},children:v.category}),v.category==="ide"&&e.jsx("button",{onClick:()=>y(s.find(d=>d.type===v.type)||{type:v.type,name:v.displayName,displayName:v.displayName,icon:v.icon,category:v.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"})]}),e.jsx("div",{className:"flex flex-col gap-2",children:v.schema.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[d.label||d.key,l===`${v.type}.${d.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),d.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:d.description})]}),e.jsx("div",{className:"shrink-0",children:d.type==="boolean"?e.jsx("button",{onClick:()=>b(v.type,d.key,!(v.values[d.key]??d.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:v.values[d.key]??d.default?"#8b5cf6":"var(--border-subtle)"},children:e.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:v.values[d.key]??d.default?21:3}})}):d.type==="number"?e.jsx("input",{type:"number",value:Number(v.values[d.key]??d.default??0)||0,min:d.min,max:d.max,onChange:N=>{const M=parseInt(N.target.value)||0;d.min!==void 0&&M<d.min||d.max!==void 0&&M>d.max||b(v.type,d.key,M)},className:"machine-input w-20 text-center text-[11px]"}):d.type==="select"&&d.options?e.jsx("select",{value:String(v.values[d.key]??d.default??""),onChange:N=>b(v.type,d.key,N.target.value),className:"machine-input text-[11px]",children:d.options.map(N=>e.jsx("option",{value:N,children:N},N))}):e.jsx("input",{type:"text",value:String(v.values[d.key]??d.default??""),onBlur:N=>b(v.type,d.key,N.target.value),className:"machine-input w-[120px] text-[11px]"})})]},d.key))})]},v.type))}),h&&e.jsx(Sp,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>y(null)}),S&&e.jsx(Cp,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),u()}})]})}function Mp({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState(0),[c,l]=a.useState(!0),[p,x]=a.useState("debug"),m=a.useRef(null),h=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const y=async()=>{try{const I=await s(t,"get_logs",{count:200,minLevel:p,since:o}),u=(I==null?void 0:I.result)||I;if(I!=null&&I.success&&Array.isArray(u==null?void 0:u.logs)&&u.logs.length>0){n(v=>[...v,...u.logs.map(N=>({timestamp:N.ts,level:N.level,message:`[${N.category}] ${N.message}`}))].slice(-300));const b=Math.max(...u.logs.map(v=>v.ts));i(b)}}catch{}};y();const S=setInterval(y,3e3);return()=>clearInterval(S)},[t,c,o,p,s]),a.useEffect(()=>{if(c&&r.length>0){const y=h.current?"smooth":"instant";setTimeout(()=>{var S;(S=m.current)==null||S.scrollIntoView({behavior:y}),h.current=!0},50)}},[r.length,c]),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-3",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(y=>e.jsx("button",{onClick:()=>{x(y),n([]),i(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${p===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:[r.length," entries"]}),e.jsx("button",{onClick:()=>l(!c),className:`machine-btn ${c?"text-green-500 border-green-500/30":""}`,children:c?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),i(0)},className:"machine-btn",children:"Clear"})]})]}),e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[200px] max-h-[500px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[r.length===0&&e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((y,S)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:y.level==="error"?"#ef4444":y.level==="warn"?"var(--status-warning)":y.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(y.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:y.level==="error"?"#ef4444":y.level==="warn"?"var(--status-warning)":y.level==="debug"?"#475569":"#8b5cf6"},children:y.level==="error"?"ERR":y.level==="warn"?"WRN":y.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:y.message})]},S)),e.jsx("div",{ref:m})]})]})}function Vr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Gr(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ba(t){if(!t)return"unknown";const s=Date.now()-t,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 Ap(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Tp(t){const s=typeof(t==null?void 0:t.runtimeRecoveryState)=="string"?String(t.runtimeRecoveryState):"";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 _p(t){switch(t){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 Pp(t){var r;const s=new Map;for(const n of t){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 Lp({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[l,p]=a.useState(!1),x=Ko(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),m=x.diagnostics,h=x.loading,y=x.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(f=>[f.sessionId||f.id,f])),[s]),I=a.useCallback(async()=>{if(t){p(!0);try{const f=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),g=Vr(f);if(!(g!=null&&g.success))throw new Error((g==null?void 0:g.error)||"Could not load session host diagnostics");y(g.diagnostics||g.result||null),o("")}catch(f){const g=f instanceof Error?f.message:"Could not load session host diagnostics";o(g)}finally{p(!1)}}},[y,t,r]),u=a.useCallback(async(f,g)=>{const w=`${f}:${g.sessionId}`;if(!(f==="session_host_stop_session"&&!window.confirm(`Stop ${g.displayName}?
65
- This will terminate the hosted runtime.`))){c(w);try{const j=await r(t,f,{sessionId:g.sessionId}),$=Vr(j);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const D=f==="session_host_resume_session"?"resumed":f==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${D}: ${g.displayName}`,"success"),await I()}catch(j){const $=j instanceof Error?j.message:"Session host action failed";ht.showToast($,"warning"),o($)}finally{c(j=>j===w?null:j)}}},[t,I,r]),b=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
66
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const g=await r(t,"session_host_prune_duplicate_sessions",{}),w=Vr(g);if(!(w!=null&&w.success))throw new Error((w==null?void 0:w.error)||"Duplicate prune failed");const j=w.result||{},$=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,D=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;ht.showToast(`Pruned ${$} duplicate runtime(s) across ${D} group(s)`,"success"),await I()}catch(g){const w=g instanceof Error?g.message:"Duplicate prune failed";ht.showToast(w,"warning"),o(w)}finally{c(g=>g==="session_host_prune_duplicate_sessions"?null:g)}}},[t,I,r]),v=a.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((f,g)=>(g.lastActivityAt||0)-(f.lastActivityAt||0)),[m==null?void 0:m.sessions]),d=a.useMemo(()=>Pp(v),[v]),N=a.useMemo(()=>v.reduce((f,g)=>{var w;return f+(((w=g.attachedClients)==null?void 0:w.length)||0)},0),[v]),M=a.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),k=a.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(f=>f.level==="warn"||f.level==="error")||null,[m==null?void 0:m.recentLogs]);return e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Hosted CLI runtime diagnostics and recovery controls."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d>0&&e.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${d})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${m?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:m?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||l,children:[e.jsx(xs,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&e.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:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(es,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-amber-100",children:"Session host diagnostics unavailable"}),e.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Clients"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:N})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),e.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ba(m.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Gr(m.hostStartedAt)})]})]}),k&&e.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:[e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[e.jsx(es,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Gr(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[e.jsx(gr,{size:14})," Hosted Runtimes"]}),v.length===0?e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No hosted runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:v.map(f=>{var R;const g=i===`session_host_resume_session:${f.sessionId}`,w=i===`session_host_restart_session:${f.sessionId}`,j=i===`session_host_stop_session:${f.sessionId}`,$=Tp(f.meta),D=S.get(f.sessionId),K=f.attachedClients.length===1?"1 client":`${f.attachedClients.length} clients`;return e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:f.displayName||(D==null?void 0:D.cliName)||f.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_p(f.lifecycle)}`,children:f.lifecycle}),$&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:$})]}),e.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:"text-text-primary/90",children:f.workspaceLabel||(D==null?void 0:D.runtimeWorkspaceLabel)||f.workspace||"No workspace"}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:"font-mono text-text-primary",children:f.runtimeKey}),f.osPid?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/90",children:["pid ",f.osPid]})]}):null]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:((R=f.writeOwner)==null?void 0:R.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Ap(f.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(mn,{size:11})," ",K]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Ba(f.lastActivityAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(f.lifecycle==="interrupted"||f.lifecycle==="failed"||f.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",f)},children:g?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",f)},children:w?"Restarting…":"Restart"}),(f.lifecycle==="running"||f.lifecycle==="starting"||f.lifecycle==="interrupted")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{u("session_host_stop_session",f)},children:j?"Stopping…":"Stop"})]})]})},f.sessionId)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),M.length===0?e.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."}):e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:M.map(f=>{var w;const g=v.find(j=>j.sessionId===f.sessionId);return e.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary font-medium",children:(g==null?void 0:g.displayName)||((w=S.get(f.sessionId))==null?void 0:w.cliName)||f.sessionId}),e.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[f.action,f.lifecycle?` · ${f.lifecycle}`:"",f.detail?` · ${f.detail}`:"",f.error?` · ${f.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${f.success===!1?"text-red-300":"text-text-secondary"}`,children:Gr(f.timestamp)})]},`${f.sessionId}:${f.timestamp}:${f.action}`)})})]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",e.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Rp({machine:t,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return e.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:e.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[e.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),e.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."}),e.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(t.workspaces||[]).length===0?e.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(t.workspaces||[]).map(i=>e.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:[e.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!t.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),e.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"}),e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function qr({icon:t,children:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[t,e.jsx("span",{children:s})]})}function Yr({children:t,className:s=""}){return e.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:t})}function Dp({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),p=r.slice(0,4),m=Is(t,"0.8.48"),h=y=>y==="ide"?"IDE":y==="cli"?"CLI":"ACP";return e.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&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(qr,{icon:e.jsx(Kt,{size:13}),children:"Current Chats"}),e.jsx(Yr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(y=>{const S=sn(y);return e.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(y),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Qe(y)}),S>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:bn(S)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:rs(y)})]},y.tabKey)})})})]}),p.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(qr,{icon:e.jsx(eo,{size:13}),children:"Recent Launches"}),e.jsx(Yr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(y=>e.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(y),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:y.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[h(y.kind),y.subtitle?` · ${y.subtitle}`:""]})]},y.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(qr,{icon:e.jsx(es,{size:13}),children:"Daemon Update"}),e.jsx(Yr,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"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."}),e.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:[e.jsx(xs,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ep(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const $p={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 tr(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Bp(t){const s=t instanceof Error?t.message:String(t||"");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({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:p,initialWorkspacePath:x}){const m=fs(),{handleLaunchIde:h,handleStopCli:y,handleRestartIde:S,handleStopIde:I,handleDetectIdes:u,launchingIde:b,launchingAgentType:v,addLog:d}=c,[N,M]=a.useState(null),k=a.useCallback(A=>{A&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(A)}`})},[m]),f=$p[t],g=t==="ide",w=t==="acp",j=a.useMemo(()=>n.filter(A=>A.category===t&&(t==="ide"||A.installed!==!1)),[t,n]),$=a.useMemo(()=>new Map(j.map(A=>[A.type,A.displayName||A.type])),[j]),[D,K]=a.useState(""),[R,z]=a.useState(""),[P,C]=a.useState([]),[_,G]=a.useState(""),[T,E]=a.useState(""),[H,se]=a.useState([]),[Y,oe]=a.useState(!1),[je,V]=a.useState(""),[ae,W]=a.useState(!1),[be,X]=a.useState(null),[J,ie]=a.useState(x?"__custom__":p||s.defaultWorkspaceId||""),[ne,he]=a.useState(x||""),[ue,fe]=a.useState([]),[te,pe]=a.useState(!1),[de,ye]=a.useState(""),[we,L]=a.useState([]),[ge,F]=a.useState(!1),[me,Ce]=a.useState(""),xe=a.useRef(null),[Le,Be]=a.useState(null),Fe=a.useRef("__home__"),[st,ze]=a.useState("__home__"),[dt,gt]=a.useState(!1),Ge=a.useRef(0),at=ue.filter(A=>!o.some(ee=>ee.type===A&&xt(ee.status)!=="stopped")),ot=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!J&&ie(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(x){ie("__custom__"),he(x);return}p&&(ie(p),he(""))},[p,x]),a.useEffect(()=>{g||D&&(j.some(A=>A.type===D)||(K(""),E("")))},[j,g,D]);const Ke=(()=>{if(J==="__custom__")return ne.trim();if(!J)return"";const A=(s.workspaces||[]).find(ee=>ee.id===J);return(A==null?void 0:A.path)||""})(),ct=a.useCallback(A=>{const ee=ot.current[A];ee&&(clearTimeout(ee),delete ot.current[A]),fe(re=>re.includes(A)?re.filter(ce=>ce!==A):re)},[]),ut=a.useRef(new Set),it=a.useCallback(async A=>{if(l){F(!0),Ce("");try{const ee=await Nr(l,r,A);ye(ee.path),he(ee.path),L(ee.directories)}catch(ee){Ce(ee instanceof Error?ee.message:"Could not load folder")}finally{F(!1)}}},[r,l]),Q=a.useCallback(()=>{var ee;if(!l)return;ie("__custom__"),pe(!0);const A=kr(s.platform,[ne.trim(),Ke,s.defaultWorkspacePath,(ee=s.workspaces[0])==null?void 0:ee.path]);it(A)},[ne,it,s.defaultWorkspacePath,s.platform,s.workspaces,Ke,l]),_e=a.useCallback(A=>{const ee=String(A.workspace||"").trim();if(!ee)return;const re=(s.workspaces||[]).find(ce=>tr(ce.path)===tr(ee));if(re){ie(re.id),he("");return}ie("__custom__"),he(ee)},[s.workspaces]),Re=a.useCallback(A=>{const ee=String(A.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ce=>tr(ce.path)===tr(ee));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),We=a.useCallback(async A=>{if(!l||!A||t!=="cli"){se([]),oe(!1),V("");return}const ee=Ge.current+1;Ge.current=ee,oe(!0),V("");try{const re=await l(r,"list_saved_sessions",{providerType:A,kind:"cli",limit:30});if(Ge.current!==ee)return;const ce=(re==null?void 0:re.result)??re;se(Array.isArray(ce==null?void 0:ce.sessions)?ce.sessions:[])}catch(re){if(Ge.current!==ee)return;se([]),V(re instanceof Error?re.message:"Could not load saved sessions")}finally{Ge.current===ee&&oe(!1)}},[t,r,l]),Ct=a.useMemo(()=>{if(t!=="cli"||!D)return null;const A=$.get(D)||D;return{routeId:r,daemonId:r,providerSessionId:T||void 0,transport:"pty",mode:"chat",agentName:A,agentType:D,status:"idle",title:A,messages:[],ideType:D,workspaceName:Ke,displayPrimary:A,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${D}`}},[t,r,$,Ke,T,D]),pt=a.useCallback(A=>{if(t==="ide"||!A){C([]);return}C(oi(r,A))},[t,r]);a.useEffect(()=>{if(E(""),pt(D),t!=="cli"||!D){se([]),V(""),oe(!1);return}We(D)},[t,pt,We,D]),a.useEffect(()=>{if(!T)return;const A=H.find(ee=>ee.providerSessionId===T);A!=null&&A.canResume||E("")},[H,T]);const wt=a.useCallback((A,ee)=>{xe.current=ee,Fe.current=A.selectedWorkspaceKey||"__home__",ze(A.selectedWorkspaceKey||"__home__"),Be(A)},[]),bt=a.useCallback(()=>{xe.current&&(gt(!0),xe.current().finally(()=>{xe.current=null,gt(!1),Be(null)}))},[]),Tt=a.useCallback(A=>{if(!A)return;fe(re=>re.includes(A)?re:[...re,A]);const ee=ot.current[A];ee&&clearTimeout(ee),ot.current[A]=setTimeout(()=>{fe(re=>re.includes(A)?re.filter(ce=>ce!==A):re),delete ot.current[A]},2e4)},[]);a.useEffect(()=>{for(const ee of o)xt(ee.status)!=="stopped"&&(ue.includes(ee.type)&&!ut.current.has(ee.type)&&(ut.current.add(ee.type),d("info",`${$.get(ee.type)||ee.type} launched`,!0)),ct(ee.type));const A=new Set(o.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));ut.current.forEach(ee=>{!ue.includes(ee)&&!A.has(ee)&&ut.current.delete(ee)})},[d,ct,o,ue,$]),a.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[B,U]=a.useState({}),[q,O]=a.useState(null);a.useEffect(()=>{if(!g||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),re=(ee==null?void 0:ee.result)||ee;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&U(re.ideExtensions)}catch{}})()},[g,r,l]);const le=A=>g?Ze(A.type):t==="cli"?A.cliName:A.acpName,Se=g?s.detectedIdes||[]:[],Me=a.useCallback(async A=>{const ee=(A==null?void 0:A.type)||D,re=(A==null?void 0:A.workspacePath)??Ke;if(g){await h(ee,re?{workspace:re}:void 0)&&Tt(ee);return}const ce=await c.runLaunchCliCore({cliType:ee,dir:A!=null&&A.workspaceId?void 0:re||void 0,workspaceId:(A==null?void 0:A.workspaceId)||void 0,useHome:(A==null?void 0:A.useHome)||!(A!=null&&A.workspaceId)&&!re,argsStr:(A==null?void 0:A.argsStr)??(R||void 0),model:(A==null?void 0:A.model)??(w&&_||void 0),resumeSessionId:(A==null?void 0:A.resumeSessionId)||!w&&t==="cli"&&ee===D&&T||void 0});if(ce.success||ce.pending){const Pe=(A==null?void 0:A.argsStr)??R;!g&&(Pe!=null&&Pe.trim())&&(ii(r,ee,Pe),pt(ee)),Tt(ee),ce.success&&ce.sessionId&&k(ce.sessionId)}},[c,h,w,g,R,_,pt,Tt,r,k,Ke,T,D]),Z=()=>{var ce;const A=g?Ze(D):$.get(D)||D,{options:ee,selectedKey:re}=Zt({machine:s,currentWorkspaceId:J&&J!=="__custom__"?J:null,currentWorkspacePath:Ke});wt({title:`Launch ${A}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:ee,selectedWorkspaceKey:re,details:[{label:"Mode",value:f.label},{label:"Provider",value:A},...!g&&t==="cli"&&T?[{label:"Resume",value:((ce=H.find(Pe=>Pe.providerSessionId===T))==null?void 0:ce.title)||T}]:[],...!g&&R.trim()?[{label:"Arguments",value:R.trim()}]:[],...w&&_.trim()?[{label:"Model",value:_.trim()}]:[]]},async()=>{const Pe=ee.find(Ae=>Ae.key===Fe.current);Pe!=null&&Pe.workspaceId?(ie(Pe.workspaceId),he("")):Pe!=null&&Pe.workspacePath?(ie("__custom__"),he(Pe.workspacePath)):(ie(""),he("")),await Me({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Ie=A=>{g?I(A):y(A.type,A.workspace,A.id)},De=a.useCallback(async(A,ee,re=!1)=>{if(A.mode===ee){re&&A.sessionId&&k(A.sessionId);return}if(!l||!A.sessionId){re&&A.sessionId&&k(A.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:A.sessionId,cliType:A.type,mode:ee}),re&&k(A.sessionId)}catch(ce){Bp(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},[r,k,l]),Ue=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:J,onChange:A=>{const ee=A.target.value;if(ie(ee),ee==="__custom__"&&l){Q();return}ee!=="__custom__"&&he("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(A=>e.jsxs("option",{value:A.id,children:[A.id===s.defaultWorkspaceId?"⭐ ":"",vr(A.path,A.label)]},A.id)),e.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),e.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),J==="__custom__"&&(l?e.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:Q,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ne,onChange:A=>he(A.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}))]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:J==="__custom__"?Ke?e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:J===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"No workspace selected. This launches in the home directory."})]});return e.jsxs("div",{children:[e.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${f.accent} relative overflow-hidden`,children:[e.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",f.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:g?Se.length>0?Se.map(A=>{const ee=o.find(Oe=>(Oe.type||"").toLowerCase()===(A.type||"").toLowerCase()&&xt(Oe.status)!=="stopped"),re=A.running||!!ee,ce=!!ee&&ee.cdpConnected,Pe=ue.includes(A.type||A.id||""),Ae=D===(A.type||"");return e.jsxs("button",{onClick:()=>{if(ce&&ee){const Oe=ee.sessionId;Oe?m(`/dashboard?activeTab=${encodeURIComponent(Oe)}`,{state:{openRemoteForTabKey:Oe}}):m("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Pe||K(Oe=>Oe===(A.type||"")?"":A.type||"")},disabled:!!b||Pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ce?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ae?"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:b&&b!==A.type?.4:1},children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(A.type)}),re&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ce?"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"}`})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:A.name||Ze(A.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-green-400":Pe?"text-orange-400":Ae?"text-accent-primary":"text-text-muted"}`,children:ce?"Open Session":Pe?"Starting...":Ae?"Configure":"Select"})]})]},A.type)}):e.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.",e.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[e.jsx(Qi,{size:14})," Scan System"]})]}):j.length>0?j.map(A=>{const ee=D===A.type,re=ue.includes(A.type),Pe=!!o.find(Ae=>Ae.type===A.type&&xt(Ae.status)!=="stopped");return e.jsxs("button",{onClick:()=>K(Ae=>Ae===A.type?"":A.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:A.icon}),Pe&&e.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)]"})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:A.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":ee?"Configure":"Select"})]})]},A.type)}):e.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 ",t.toUpperCase()," providers available.",e.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."})]})}),D&&(g?Se.find(A=>A.type===D):j.find(A=>A.type===D))&&e.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:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:g?Ze(D):$.get(D)||D})]}),Ue,!g&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&t==="cli"&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume from History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void We(D),disabled:!D||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{D&&(W(!0),We(D))},disabled:!D,children:"Open History"})]})]}),T?(()=>{const A=H.find(ee=>ee.providerSessionId===T);return A?e.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:A.title||A.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:A.providerSessionId}),e.jsx("div",{children:A.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>E(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),je&&e.jsx("div",{className:"text-[10px] text-red-400",children:je})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),e.jsx("input",{type:"text",placeholder:"Leave empty for default",value:_,onChange:A=>G(A.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"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:R,onChange:A=>z(A.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"}),P.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:P.map(A=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>z(A),title:A,children:A},A))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:Z,disabled:!!v||!!b||ue.includes(D),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:v===D||b===D?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ue.filter(A=>!o.some(ee=>ee.type===A&&xt(ee.status)!=="stopped")).length,")"]}),o.length===0&&at.length===0?e.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 ",f.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map(A=>e.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:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(A)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:g?Ze(A):$.get(A)||A}),e.jsx("div",{className:"text-[11px] text-text-muted",children:v===A?"Launching process...":"Waiting for process and session to register..."})]})]}),e.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:${A}`)),o.map(A=>{const ee=g?A:null,re=w?A:null,ce=!g&&!w?A:null,Pe=xt(A.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(A.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[le(A),(ee==null?void 0:ee.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:A.workspace||"—"}),(re==null?void 0:re.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ce==null?void 0:ce.mode)&&e.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.runtimeKey&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),e.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ce.runtimeKey]}),e.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 Ae;(Ae=navigator.clipboard)==null||Ae.writeText(`adhdev attach ${ce.runtimeKey}`),M(ce.runtimeKey||null),window.setTimeout(()=>{M(Oe=>Oe===ce.runtimeKey?null:Oe)},1200)},children:N===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&e.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ep(ce.runtimeWriteOwner)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Ae=A.sessionId;if(Ae){m(`/dashboard?activeTab=${encodeURIComponent(Ae)}`,{state:{openRemoteForTabKey:Ae}});return}m("/dashboard",{state:{openRemoteForTabKey:A.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:e.jsx(Nt,{size:13})}),e.jsx("button",{onClick:()=>{const Ae=A.workspace||"",{options:Oe,selectedKey:rt}=Zt({machine:s,currentWorkspacePath:Ae});wt({title:`Restart ${Ze(A.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Oe,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(A.type)}]},async()=>{const Ye=Oe.find(He=>He.key===Fe.current),qe=(Ye==null?void 0:Ye.workspacePath)??"";if(qe&&qe!==Ae){await Me({type:A.type,workspacePath:qe});return}await S(A)})},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:e.jsx(xs,{size:14})})]}),w&&e.jsx("button",{onClick:()=>{const Ae=A.sessionId;Ae&&k(Ae)},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:!A.sessionId,children:e.jsx(Kt,{size:14})}),ce&&Pe!=="stopped"&&e.jsxs(e.Fragment,{children:[ce.mode&&e.jsx(jn,{mode:ce.mode,onChange:Ae=>void De(ce,Ae,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Ae=A.sessionId;Ae&&k(Ae)},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:!A.sessionId,children:ce.mode==="chat"?e.jsx(Kt,{size:14}):e.jsx(Nt,{size:13})})]}),Pe==="stopped"?e.jsx("button",{onClick:()=>{const Ae=A.workspace||"",Oe=g?Ze(A.type):le(A),{options:rt,selectedKey:Ye}=Zt({machine:s,currentWorkspacePath:Ae});wt({title:`Launch ${Oe}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:rt,selectedWorkspaceKey:Ye,details:[{label:"Mode",value:f.label},{label:"Provider",value:Oe}]},async()=>{const qe=rt.find(He=>He.key===Fe.current);await Me({type:A.type,workspaceId:(qe==null?void 0:qe.workspaceId)??null,workspacePath:(qe==null?void 0:qe.workspacePath)??"",useHome:!(qe!=null&&qe.workspaceId)&&!(qe!=null&&qe.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:ue.includes(A.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:ue.includes(A.type)?"⏳":e.jsx(xn,{size:14})}):e.jsx("button",{onClick:()=>Ie(A),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:e.jsx(vt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ae=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${io(Ae.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ae.name," · ",xt(Ae.status)]},Ae.id))}),ee&&(B[ee.type]||[]).length>0&&l&&e.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[e.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(B[ee.type]||[]).map(Ae=>e.jsxs("button",{disabled:q===`${ee.type}.${Ae.type}`,onClick:async()=>{const Oe=`${ee.type}.${Ae.type}`;O(Oe);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ae.type,enabled:!Ae.enabled}),U(rt=>({...rt,[ee.type]:(rt[ee.type]||[]).map(Ye=>Ye.type===Ae.type?{...Ye,enabled:!Ye.enabled}:Ye)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{O(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 ${Ae.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Ae.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ae.name,e.jsx("span",{className:"text-[9px] font-normal",children:Ae.enabled?"ON":"OFF"})]},Ae.type))})]})]},A.id)})]}),te&&l&&e.jsx(Sr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:de,directories:we,busy:ge,error:me,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:A=>{it(A)},onConfirm:A=>{he(A),ie("__custom__"),pe(!1)}}),Le&&e.jsx(_n,{title:Le.title,description:Le.description,details:Le.details,workspaceOptions:Le.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:A=>{Fe.current=A,ze(A)},confirmLabel:Le.confirmLabel,busy:dt,onConfirm:bt,onCancel:()=>{xe.current=null,Be(null)}}),ae&&Ct&&e.jsx(kn,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:H,isSavedSessionsLoading:Y,isResumingSavedSessionId:be,onClose:()=>W(!1),onNewChat:()=>{E(""),W(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{We(D)},onResumeSavedSession:A=>{if(!A.canResume||be)return;const ee=Re(A);E(A.providerSessionId),_e(A),X(A.providerSessionId),W(!1),Me({type:A.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:A.providerSessionId}).finally(()=>{X(re=>re===A.providerSessionId?null:re)})}})]})}const Ka=[{id:"ide",label:"IDE",helper:"Open a graphical workspace and attach CDP"},{id:"cli",label:"CLI",helper:"Launch a terminal-first workspace on this machine"},{id:"acp",label:"ACP",helper:"Launch an ACP-backed workspace on this machine"}];function Kp({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:l,initialCategory:p="ide",initialWorkspaceId:x,initialWorkspacePath:m,sendDaemonCommand:h}){var u;const[y,S]=a.useState(p);a.useEffect(()=>{S(p)},[p]);const I=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[e.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[e.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),e.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[e.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Ka.map(b=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:I[b.id]})]},b.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=Ka.find(b=>b.id===y))==null?void 0:u.helper})]}),y==="ide"&&e.jsx(Xr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:m}),y==="cli"&&e.jsx(Xr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:m}),y==="acp"&&e.jsx(Xr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:m})]})}function Wp({onNicknameSynced:t}={}){var ne,he,ue,fe,te,pe,de,ye,we;const{id:s}=Ei(),r=fs(),n=un(),{sendCommand:o}=St(),i=Ks(),c=ho(),l=c.ides||[],p=c.initialLoaded??!0,x=l.find(L=>L.id===s&&L.type==="adhdev-daemon"),m=l.some(L=>L.type==="adhdev-daemon"),[h,y]=a.useState("workspace"),[S,I]=a.useState("ide"),u=a.useRef(null),[b,v]=a.useState(null),d=a.useRef("__home__"),[N,M]=a.useState("__home__"),[k,f]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{!s||!x||!(!x.workspaces||!x.availableProviders||!x.detectedIdes||!x.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,x,s]),Pd(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const w=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=vp({machineId:s,registeredMachineId:(x==null?void 0:x.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:g});a.useEffect(()=>ht.onToast(ge=>{c.setToasts(me=>{if(me.some(Le=>Le.message===ge.message&&ge.timestamp-Le.timestamp<3e3))return me;const xe={id:ge.id,message:ge.message,type:ge.type,timestamp:ge.timestamp,targetKey:ge.targetKey,actions:ge.actions};return[...me.slice(-4),xe]});const F=ge.duration||5e3;setTimeout(()=>c.setToasts(me=>me.filter(Ce=>Ce.id!==ge.id)),F)}),[c]);const $=(x==null?void 0:x.availableProviders)||[],D={};for(const L of $)D[L.type]=L.icon;const K=L=>D[L]||"",R=x?{id:x.id,hostname:co(x,{fallbackId:x.id}),platform:((ne=x.machine)==null?void 0:ne.platform)||"unknown",arch:((he=x.machine)==null?void 0:he.arch)||"",cpus:((ue=x.machine)==null?void 0:ue.cpus)||0,totalMem:((fe=x.machine)==null?void 0:fe.totalMem)||0,freeMem:(te=x.machine)==null?void 0:te.freeMem,availableMem:(pe=x.machine)==null?void 0:pe.availableMem,loadavg:(de=x.machine)==null?void 0:de.loadavg,uptime:(ye=x.machine)==null?void 0:ye.uptime,release:((we=x.machine)==null?void 0:we.release)||"",cdpConnected:!!x.cdpConnected,machineNickname:x.machineNickname||null,p2p:x.p2p?{screenshotActive:!1,...x.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:x.detectedIdes||[],workspaces:x.workspaces||[],defaultWorkspaceId:x.defaultWorkspaceId??x.activeWorkspaceId??null,defaultWorkspacePath:x.defaultWorkspacePath??x.activeWorkspacePath??null}:null,z=l.filter(L=>L.daemonId===s&&L.type!=="adhdev-daemon").filter(L=>!Rs(L)&&!ds(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,version:L.version||"",instanceId:L.instanceId||"",status:L.status,workspace:L.workspace||null,terminals:L.terminals||0,aiAgents:Fc(L.aiAgents||(L.agents||[]).map(ge=>({id:ge.name,name:ge.name,status:ge.status,version:ge.version}))),activeChat:L.activeChat||null,chats:L.chats||[],childSessions:L.childSessions||[],cdpConnected:L.cdpConnected||!1,daemonId:s})),P=l.filter(L=>L.daemonId===s&&Rs(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,cliName:L.cliName||L.type,status:L.status,workspace:L.workspace||"",activeChat:L.activeChat||null,providerSessionId:L.providerSessionId,mode:L.mode,runtimeKey:L.runtimeKey,runtimeDisplayName:L.runtimeDisplayName,runtimeWorkspaceLabel:L.runtimeWorkspaceLabel,runtimeWriteOwner:L.runtimeWriteOwner||null,runtimeAttachedClients:L.runtimeAttachedClients||[],daemonId:s})),C=l.filter(L=>L.daemonId===s&&ds(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,acpName:L.cliName||L.type,status:L.status,workspace:L.workspace||"",activeChat:L.activeChat||null,providerSessionId:L.providerSessionId,currentModel:L.currentModel,currentPlan:L.currentPlan,daemonId:s})),_=x?kt(x,{fallbackId:s}):"",G="workspace",T=n.state,E=T==null?void 0:T.initialMachineTab,H=T==null?void 0:T.initialWorkspaceCategory,se=T==null?void 0:T.initialWorkspaceId,Y=T==null?void 0:T.initialWorkspacePath,oe=E==="ides"||E==="clis"||E==="acps"?"workspace":E||G,je=E==="ides"?"ide":E==="clis"?"cli":E==="acps"?"acp":H,V=[...z.map(L=>{var ge,F,me,Ce,xe;return{id:`ide:${L.type}:${L.workspace||""}`,label:((ge=L.activeChat)==null?void 0:ge.title)||L.type,kind:"ide",providerType:L.type,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,timestamp:((xe=(Ce=(me=(F=L.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),...P.map(L=>{var ge,F,me,Ce,xe;return{id:`cli:${L.type}:${L.workspace||""}`,label:((ge=L.activeChat)==null?void 0:ge.title)||L.cliName,kind:"cli",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,timestamp:((xe=(Ce=(me=(F=L.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),...C.map(L=>{var ge,F,me,Ce,xe;return{id:`acp:${L.type}:${L.workspace||""}`,label:((ge=L.activeChat)==null?void 0:ge.title)||L.acpName,kind:"acp",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:L.currentModel||L.workspace||void 0,workspace:L.workspace||void 0,currentModel:L.currentModel,timestamp:((xe=(Ce=(me=(F=L.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}})].sort((L,ge)=>ge.timestamp-L.timestamp).map(({timestamp:L,...ge})=>ge),ae=((x==null?void 0:x.recentLaunches)||[]).length>0?((x==null?void 0:x.recentLaunches)||[]).map(L=>({id:L.id,label:L.title||L.providerName||L.providerType,kind:L.kind,providerType:L.providerType,providerSessionId:L.providerSessionId,subtitle:L.currentModel||L.workspace||void 0,workspace:L.workspace,currentModel:L.currentModel})):V,W=a.useMemo(()=>{var ge;const L=((ge=c.connectionStates)==null?void 0:ge[s||""])||void 0;return l.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").flatMap(F=>Nn(F,{},{connectionStates:s&&L?{[s]:L}:void 0,defaultConnectionState:L})).filter(F=>!(F.transport==="pty"&&F.mode==="terminal")).sort((F,me)=>sn(me)-sn(F))},[l,c.connectionStates,s]),be=a.useCallback(L=>{const ge=L.sessionId||L.tabKey;ge&&r(`/dashboard?activeTab=${encodeURIComponent(ge)}`)},[r]),X=a.useCallback(()=>{u.current&&(f(!0),u.current().finally(()=>{u.current=null,f(!1),v(null)}))},[]),J=a.useCallback(L=>{if(!R)return;const{options:ge,selectedKey:F}=Zt({machine:R,currentWorkspacePath:L.workspace}),me=async()=>{I(L.kind),y("workspace")};u.current=async()=>{const Ce=ge.find(Be=>Be.key===d.current),xe=(Ce==null?void 0:Ce.workspacePath)??null,Le=(Ce==null?void 0:Ce.workspaceId)??null;if(L.kind==="ide"&&L.providerType){await j.handleLaunchIde(L.providerType,xe?{workspace:xe}:void 0);return}if((L.kind==="cli"||L.kind==="acp")&&L.providerType){await j.runLaunchCliCore({cliType:L.providerType,dir:Le?void 0:xe||"",workspaceId:Le||void 0,model:L.kind==="acp"?L.currentModel:void 0,resumeSessionId:L.providerSessionId});return}await me()},d.current=F,M(F),v({title:`Launch ${L.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ge,details:[{label:"Mode",value:L.kind.toUpperCase()},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]})},[j,R]);if(a.useEffect(()=>{y(oe)},[G,oe,s]),a.useEffect(()=>{je&&I(je)},[je,s]),!R)return p?e.jsxs("div",{className:"p-10 text-center text-text-muted",children:[e.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),e.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),e.jsx("button",{onClick:w,className:"machine-btn-back",children:"← Back"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:14})," Workspace"]}),count:z.length+P.length+C.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(br,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ec,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ji,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.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:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[e.jsx("button",{onClick:w,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:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:j.nicknameInput,onChange:L=>j.setNicknameInput(L.target.value),onKeyDown:L=>{L.key==="Enter"&&j.handleSaveNickname(),L.key==="Escape"&&j.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]"}),e.jsx("button",{onClick:j.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"}),e.jsx("button",{onClick:()=>j.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"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{j.setEditingNickname(!0),j.setNicknameInput(R.machineNickname||"")},title:"Click to set nickname",children:_}),e.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"})]}),e.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:[e.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[R.platform," · ",R.arch]}),e.jsxs("span",{children:[R.cpus," cores"]}),(x==null?void 0:x.version)&&e.jsxs("span",{children:["v",x.version]}),R.p2p.available&&e.jsxs("span",{children:["P2P ",R.p2p.state==="connected"?"connected":R.p2p.state]}),R.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:R.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(L=>e.jsxs("button",{onClick:()=>y(L.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===L.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[L.label,L.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===L.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L.count})]},L.id))})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:e.jsx("div",{className:"max-w-7xl mx-auto h-full",children:e.jsxs("div",{className:"h-full",children:[h==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Dp,{machineEntry:x,providers:$,recentLaunches:ae,currentConversations:W,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:J,onOpenConversation:be}),e.jsx(Kp,{machine:R,machineId:s,providers:$,ideSessions:z,cliSessions:P,acpSessions:C,actions:j,getIcon:K,initialCategory:S,initialWorkspaceId:se,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx(Ip,{machineId:s,providers:$,sendDaemonCommand:o}),h==="overview"&&e.jsx(wp,{machineId:s,machine:R,ideSessions:z,cliSessions:P,acpSessions:C,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(Lp,{machineId:s,cliSessions:P,sendDaemonCommand:o}),h==="logs"&&e.jsx(Mp,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&R&&e.jsx(Rp,{machine:R,launchPick:j.launchPick,actions:j}),b&&e.jsx(_n,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:L=>{d.current=L,M(L)},confirmLabel:b.confirmLabel,busy:k,onConfirm:X,onCancel:()=>{u.current=null,v(null)}}),e.jsx(ko,{toasts:c.toasts||[],onDismiss:L=>c.setToasts(ge=>ge.filter(F=>F.id!==L)),onClickToast:L=>{L.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(L.targetKey)}`)}}),e.jsx("style",{children:`
67
- @keyframes toast-in {
68
- from { opacity: 0; transform: translateX(40px); }
69
- to { opacity: 1; transform: translateX(0); }
70
- }
71
- `})]})}class Op{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(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 Et=new Op;function Hp(){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 sr=Hp(),Wa=3e3,Up=3e4;let Rt=null,zp=0;const hr=new Map;let Gt=null,As=null;function Oa(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function ks(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function Fp(t){return t==="connected"?"connected":t}async function ir(t,s,r){const n=Rl(t,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++zp}_${Date.now()}`;return new Promise((c,l)=>{const p=setTimeout(()=>{hr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);hr.set(i,{resolve:x=>{clearTimeout(p),c(x)},reject:x=>{clearTimeout(p),l(x)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function dn(t,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Vp{constructor(s){nt(this,"daemonId");nt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return ir(this.daemonId,s,r)}async sendInput(s,r){return ir(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Gt&&(clearInterval(Gt),Gt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await ir(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());Et.emitScreenshot(this.daemonId,o)}}catch{}};r(),Gt=setInterval(r,2e3)}stopScreenshots(s){Gt&&(clearInterval(Gt),Gt=null)}}let At=null;function Gp(t){return(!At||At.daemonId!==t)&&(At=new Vp(t)),At}function qp({children:t}){const s=a.useRef(lr()),r=lr();s.current=r;const{setUserName:n}=Qt(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,l]=a.useState("disconnected"),p=a.useCallback((u,b)=>{l(u),As==null||As(u,b)},[]),x=a.useRef(null),m=a.useRef(),h=a.useRef(Wa),y=a.useRef(!0),S=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{y.current=!0,S.current=!1;function u(){var d,N;if(!y.current||((d=x.current)==null?void 0:d.readyState)===WebSocket.OPEN||((N=x.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;p("connecting"),console.log(`[Standalone WS] Connecting to ${sr}...`),ks("connect_attempt",{url:sr,reason:I.current,delayMs:h.current});let v;try{v=new WebSocket(sr)}catch(M){console.error("[Standalone WS] Failed to create WebSocket:",M),b();return}x.current=v,v.onopen=()=>{if(!y.current){v.close();return}p("connected"),h.current=Wa,ks("open",{url:sr,reason:I.current}),Ot.resubscribeAll({sendData:dn}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=M=>{var k,f;try{const g=JSON.parse(M.data);if((g.type==="command_result"||g.type==="error")&&g.requestId){const w=hr.get(g.requestId);w&&(hr.delete(g.requestId),g.type==="error"?w.reject(new Error(((k=g.data)==null?void 0:k.message)||"Command failed")):w.resolve(g.data));return}if(g.type==="session_output"){const w=g.sessionId||g.cliId||g.cliType;w&&Et.emitSessionOutput(w,typeof g.data=="string"?g.data:"",typeof g.seq=="number"?g.seq:void 0);return}if(g.type==="runtime_snapshot"){Et.emitRuntimeSnapshot(g.sessionId,typeof g.text=="string"?g.text:"",typeof g.seq=="number"?g.seq:0,!!g.truncated);return}if(g.type==="topic_update"){const w=g.update;w&&Ot.publish(w);return}if(g.type==="status"||g.type==="initial_state"){const w=g.data;if(!w)return;const{injectEntries:j,markLoaded:$,getIdes:D}=s.current,K=w.instanceId||"standalone",R=D().find(C=>C.id===K),z=Gp(K);Et.register(K,z),Et.setState(K,"connected"),p("connected",K),Et.emitStatus(K,w);const P=ur(w,{daemonId:K,existingDaemon:R,existingEntries:D()});Oa("ws_status",{type:g.type,daemonId:K,sessions:(w.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(w.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Oa("entries",{daemonId:K,entries:P.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),P.length>0&&j(P,{authoritativeDaemonIds:[K]}),$(),c.current!==K&&((f=i.current)==null||f.call(i),c.current=K,i.current=Ot.subscribe({sendData:dn},K,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${K}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const _=s.current.getIdes(),G=_.find(E=>E.id===K),T=ur(C.status,{daemonId:K,existingDaemon:G,existingEntries:_,timestamp:C.timestamp});T.length>0&&s.current.injectEntries(T),C.userName&&o.current&&o.current(C.userName)}))}}catch(g){console.error("[Standalone WS] Parse error:",g)}},v.onclose=M=>{y.current&&(At==null||At.stopScreenshots(),At&&Et.setState(At.daemonId,"disconnected"),p("disconnected"),x.current=null,I.current=`close:${M.code}${M.wasClean?":clean":":unclean"}`,ks("close",{code:M.code,reason:M.reason||"",wasClean:M.wasClean}),b())},v.onerror=M=>{S.current||!y.current||(I.current="error",ks("error",{message:M instanceof Event?"event":String(M),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",M))}}function b(){if(!y.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),ks("schedule_reconnect",{reason:I.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Up),u()},v)}return u(),()=>{var v;y.current=!1,S.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),x.current&&(x.current.onerror=null,x.current.onclose=null,x.current.close(),x.current=null,Rt=null),At&&(At.stopScreenshots(),Et.unregister(At.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function Yp({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(As=(c,l)=>{r(c),l&&o(l)},()=>{As=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",l=Fp(s),p={};return n&&(p[n]=l),p.standalone=l,{wsStatus:s,isConnected:c,connectionStates:p}},[s,n]);return e.jsx(Ui,{connectionOverrides:i,children:e.jsx(qp,{children:t})})}const Xp=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Ya,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Ut,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(br,{}),label:"Settings"}];function Jp({children:t}){const s=fs(),r=un(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),o(!1)},p=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},x=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"})]}),n&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:m=>m.key==="Escape"&&o(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:Xp.map(m=>e.jsxs("div",{className:x(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(Xa,{})}),!i&&e.jsxs(e.Fragment,{children:["Docs",e.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),e.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:[e.jsx("span",{className:"nav-icon",children:e.jsx(Ja,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.48"]}),e.jsx(pd,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:p,title:i?"Expand sidebar":"Collapse sidebar",children:[e.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&e.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),e.jsx("main",{className:"main-content relative",children:e.jsx("div",{className:"main-content-inner",children:t})})]})}const Zp=[{icon:e.jsx(Ut,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(Za,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(_s,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Xa,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Qp=[{icon:e.jsx(to,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Ya,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(yr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(Xi,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(mn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Zi,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],em=[{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 tm(){return e.jsxs(_o,{icon:e.jsx(Ja,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:e.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.48"]}),children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),e.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."}),e.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."})]}),e.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[e.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 ↗"}),e.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 ↗"}),e.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 ↗"})]})]})}),e.jsx(Pt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Zp.map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.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:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Co.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Mo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Io.map(t=>`${t.icon} ${t.name}`)}].map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[e.jsx("div",{className:"text-[10px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),e.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(s=>e.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))})]},t.label))})}),e.jsx(Pt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Qp.map(t=>e.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:e.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary",children:[e.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),e.jsx("tbody",{children:em.map((t,s)=>e.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[e.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?e.jsx("span",{className:"text-emerald-500",children:"✓"}):e.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),e.jsx("td",{className:"px-4 py-2.5 text-center",children:e.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),e.jsx(Po,{icon:e.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:e.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[e.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),e.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[e.jsx(pc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function sm(){const{ides:t}=Qt(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=St(),{userName:o}=Qt(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const l=h=>{const y=h.target.value.trim();s!=null&&s.id&&y!==o&&n(s.id,"set_user_name",{userName:y}).catch(console.error)},[p,x]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=h=>{x(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(_o,{icon:e.jsx(br,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(od,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(Pt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[e.jsx("span",{className:"text-text-muted",children:"Version"}),e.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.48"]}),e.jsx("span",{className:"text-text-muted",children:"Status"}),e.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),e.jsx("span",{className:"text-text-muted",children:"WebSocket"}),e.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),e.jsx("span",{className:"text-text-muted",children:"HTTP"}),e.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),e.jsx(Pt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(h=>e.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${h.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:h.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:h.type})]},h.type))})}),e.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(hd,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(Pt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),e.jsx(vd,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),e.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."}),e.jsx(Md,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),e.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."}),e.jsx(Td,{})]})]})}),e.jsx(Pt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(md,{}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(uc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:p,onChange:m})]})}),e.jsx(Pt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:e.jsx("div",{className:"flex flex-col gap-3",children:e.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:[e.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[e.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Yi,{size:16,className:"text-text-secondary"})," Display Name"]}),e.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),e.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:h=>c(h.target.value),onBlur:l,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}ud();Cd();const rm=Ga({baseUrl:""});function Ha(){const{ides:t,initialLoaded:s}=Qt();if(!s)return e.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=t.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?e.jsx(Qr,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Qr,{to:"/dashboard",replace:!0})}function nm(){return e.jsx($i,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Vi,{client:rm,children:e.jsx(Yp,{children:e.jsx(qi,{value:{sendCommand:ir,sendData:dn},children:e.jsx(Jp,{children:e.jsxs(Bi,{children:[e.jsx(Ft,{path:"/dashboard",element:e.jsx(yp,{})}),e.jsx(Ft,{path:"/machine",element:e.jsx(Ha,{})}),e.jsx(Ft,{path:"/machines/:id",element:e.jsx(Wp,{})}),e.jsx(Ft,{path:"/machines",element:e.jsx(Ha,{})}),e.jsx(Ft,{path:"/about",element:e.jsx(tm,{})}),e.jsx(Ft,{path:"/settings",element:e.jsx(sm,{})}),e.jsx(Ft,{path:"*",element:e.jsx(Qr,{to:"/dashboard",replace:!0})})]})})})})})})}hl({connectionManager:Et});Ki(document.getElementById("root")).render(e.jsx(nm,{}));