@adhdev/daemon-standalone 0.8.41 → 0.8.43

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,59 +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 pi=Object.defineProperty;var fi=(t,s,r)=>s in t?pi(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var Xe=(t,s,r)=>fi(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as Ca,a as Ia,b as xi,c as hi,u as ds,R as Ye,d as Ma,t as bi,e as gi,D as yi,f as vi,g as wi,h as Zr,i as ji,k as ki,B as Ni,l as Si,m as Ot,N as Ur,n as Ci}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 Aa=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}),_a=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function An(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 jr(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,u=s.versionUpdateRequired===!0||t.versionUpdateRequired===!0,m=s.versionUpdateReason??t.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),m&&(n.versionUpdateReason=m),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),u&&(n.versionUpdateRequired=!0),n)}function rr(t){return Array.isArray(t)?t.map(rr):!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,rr(r)]))}function Ii(t,s){try{return JSON.stringify(rr(t))===JSON.stringify(rr(s))}catch{return!1}}function Bs(t,s,r){return Ii(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function Mi(t,s,r){var m,x,p,h,g,S,I;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of t){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const y=An(d),l=An(b);if(y>l){const C=(m=d.chats)!=null&&m.length?d.chats:b.chats,M=jr(b,d,{...b,...d,chats:C,_lastUpdate:n});i.set(d.id,Bs(b,M,n))}else if(y<l){const C={};if(d.status&&d.status!==b.status&&(C.status=d.status),d.cdpConnected!==void 0&&(C.cdpConnected=d.cdpConnected),(x=d.chats)!=null&&x.length&&!((p=b.chats)!=null&&p.length)&&(C.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(C.machineNickname=d.machineNickname),d.version!==void 0&&(C.version=d.version),d.serverVersion!==void 0&&(C.serverVersion=d.serverVersion),d.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const M=jr(b,d,{...b,...C,_lastUpdate:b._lastUpdate});i.set(d.id,Bs(b,M,n))}else Bs(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const C=d.timestamp||n,M=b._lastUpdate||b.timestamp||0;if(C>=M){const N=(h=d.chats)!=null&&h.length?d.chats:b.chats,f=jr(b,d,{...b,...d,chats:N,_lastUpdate:n});i.set(d.id,Bs(b,f,n))}else(g=d.chats)!=null&&g.length&&!((S=b.chats)!=null&&S.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(t.map(d=>d.id)),u=new Set;for(const d of t){const b=d.daemonId||((I=d.id)==null?void 0:I.split(":")[0]);b&&u.add(b)}for(const[d,b]of i){const y=b.daemonId||d.split(":")[0];if(!u.has(y))continue;if(o.has(y)&&!c.has(d)){i.delete(d);continue}const l=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&l>1e4||b.transport==="acp"&&!c.has(d)&&l>1e4||b.transport==="cdp-page"&&!c.has(d)&&l>3e4)&&i.delete(d)}for(const[d,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(d);return Array.from(i.values())}function Ai(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 _i({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,u]=a.useState([]),[m,x]=a.useState(void 0),p=a.useRef(r);a.useEffect(()=>{p.current=r},[r]);const h=a.useCallback((y,l)=>{n(C=>{let M=!1;const N=C.map(f=>f.id!==y||f.chats===l?f:(M=!0,{...f,chats:l}));return M?N:C})},[]),g=a.useCallback((y,l)=>{n(C=>{const M=C.length===0?y:Mi(y,C,l);return Ai(C,M)?C:M})},[]),S=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:g,markLoaded:S,getIdes:()=>p.current}),[g,S]),d=s,b=a.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:o,toasts:c,setToasts:u,wsStatus:(d==null?void 0:d.wsStatus)??"connected",isConnected:(d==null?void 0:d.isConnected)??!0,connectionStates:(d==null?void 0:d.connectionStates)??{},connectionTransports:(d==null?void 0:d.connectionTransports)??{},showReconnected:(d==null?void 0:d.showReconnected)??!1,retryConnection:d==null?void 0:d.retryConnection,isP2PActive:(d==null?void 0:d.isP2PActive)??!1,p2pStates:(d==null?void 0:d.p2pStates)??{},userRole:d==null?void 0:d.userRole,userName:m,setUserName:x}),[r,h,o,c,d==null?void 0:d.wsStatus,d==null?void 0:d.isConnected,d==null?void 0:d.connectionStates,d==null?void 0:d.connectionTransports,d==null?void 0:d.showReconnected,d==null?void 0:d.retryConnection,d==null?void 0:d.isP2PActive,d==null?void 0:d.p2pStates,d==null?void 0:d.userRole,m]);return e.jsx(_a.Provider,{value:I,children:e.jsx(Aa.Provider,{value:b,children:t})})}function Yt(){return a.useContext(Aa)}function nr(){return a.useContext(_a)}function Ta(t){const{baseUrl:s,getToken:r,onUnauthorized:n}=t;function o(u){return u.startsWith("http")?u:`${s}${u.startsWith("/")?"":"/"}${u}`}function i(u){const m=r==null?void 0:r(),x=o(u),p=u.startsWith("http")?new URL(x):new URL(x,typeof window<"u"?window.location.origin:"http://localhost");return m&&p.searchParams.set("token",m),!u.startsWith("http")&&!s?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function c(u,m={}){const x={"Content-Type":"application/json",...m.headers||{}},p=r==null?void 0:r();p&&(x.Authorization=`Bearer ${p}`);const h=o(u),g=new AbortController,S=setTimeout(()=>g.abort(),15e3);try{const I=await fetch(h,{...m,headers:x,signal:g.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const d=await I.json().catch(()=>({error:I.statusText}));throw new Error(d.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:u=>c(`/api/v1/daemons/${u}/status`),sendCommand:(u,m,x={})=>c(`/api/v1/daemons/${u}/command`,{method:"POST",body:JSON.stringify({type:m,payload:x})}),execTerminal:(u,m,x)=>c(`/api/v1/daemons/${u}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:x})}),sendAgentMessage:(u,m,x)=>c(`/api/v1/shortcuts/${u}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:x})}),getAgentStatus:u=>c(`/api/v1/shortcuts/${u}/status`),approveAgent:(u,m,x)=>c(`/api/v1/shortcuts/${u}/approve`,{method:"POST",body:JSON.stringify({agentType:m,action:x?"approve":"reject"})}),getMuxState:u=>c(`/api/v1/mux/${encodeURIComponent(u)}/state`),getMuxSocketInfo:u=>c(`/api/v1/mux/${encodeURIComponent(u)}/socket-info`),controlMux:(u,m,x={})=>c(`/api/v1/mux/${encodeURIComponent(u)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:x})}),getMuxEventsUrl:u=>i(`/api/v1/mux/${encodeURIComponent(u)}/events`),getRuntimeEventsUrl:u=>i(`/api/v1/runtime/${encodeURIComponent(u)}/events`),request:c}}const Ti=Ta({baseUrl:"http://localhost:3847"}),Pi=a.createContext(Ti);function Ri({client:t,children:s}){return e.jsx(Pi.Provider,{value:t,children:s})}const Li={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Pa=a.createContext(Li);function Ei({value:t,children:s}){return e.jsx(Pa.Provider,{value:t,children:s})}function bt(){return a.useContext(Pa)}const De={size:18};function Ra({size:t=De.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 Qr({size:t=De.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 Bt({size:t=De.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 en({size:t=De.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 Di({size:t=De.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 $i({size:t=De.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 La({size:t=De.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 Bi({size:t=De.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 dr({size:t=De.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 Ea({size:t=De.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 Ki({size:t=De.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 Lt({size:t=De.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 xt({size:t=De.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 tn({size:t=De.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 Wi({size:t=De.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 cs({size:t=De.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 us({size:t=De.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 Xt({size:t=De.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 Ms({size:t=De.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 Da({size:t=De.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 $a({size:t=De.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 Ba({size:t=De.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 Oi({size:t=De.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 ur({size:t=De.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 Ui({size:t=De.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 sn({size:t=De.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 zi({size:t=De.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 ht({size:t=De.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 Ka({size:t=De.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 Hi({size:t=De.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 Fi({size:t=De.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 Vi({size:t=De.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 mr({size:t=De.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 qi({size:t=De.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 Gi({size:t=De.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 Yi({size:t=De.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 Xi({size:t=De.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 Ji({size:t=De.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 Zi({size:t=De.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 Qi({size:t=De.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 ec({size:t=De.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 tc({size:t=De.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 sc({size:t=De.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 _n(t){return!!t&&typeof t=="object"&&"text"in t}function rn(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:_n(i)?String(i.text||""):"").join(r):_n(t)?o=String(t.text||""):o=String(t||""),n?o.replace(/\s+/g," ").trim():o}function Jt(t){return rn(t,{normalizeWhitespace:!0})}function Wa(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function rc(t,s,r){return Number(t.receivedAt||r[ns(t,s)]||0)||0}function nc(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ns(t,s){const r=t,n=rn(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 Tn=5e3,ac=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(Ca,{remarkPlugins:[Ia],children:s.text}),e.jsx("span",{className:"action-time",children:Wa(s.timestamp)})]})},(t,s)=>t.log===s.log),oc=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:u}){var M,N,f;const m=(s.role||"").toLowerCase(),x=m==="user"||m==="human",p=s.kind||(m==="tool"?"tool":"standard"),h=rn(s.content,{joiner:`
4
- `});if(p==="thought"){const w=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(Fi,{size:13}),e.jsx("span",{children:w})]}),e.jsx("div",{className:"chat-msg-body",children:h})]})}if(p==="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(p==="terminal"){const w=(N=s.meta)!=null&&N.isRunning?"⏳":"✅",v=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:w}),e.jsx("span",{children:v})]}),e.jsx("pre",{className:"chat-msg-body",children:h})]})}if(p==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:h.slice(0,100)});const g=s.meta,I=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",d=h,b=i&&!x&&!I&&d.length>Tn,y=b&&!c?d.slice(0,Tn):d,l=I,C=!l&&nc(y);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${x?"self-end":"self-start"}`,children:(d||x)&&e.jsxs("div",{className:`chat-bubble ${x?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${d?"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:Wa(r)})]}),d&&e.jsx("div",{className:"chat-markdown",children:l?e.jsx("pre",{className:"chat-preformatted",children:y}):C?e.jsx(Ca,{remarkPlugins:[Ia,xi,hi],children:y}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),b&&e.jsx("button",{onClick:u,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(d.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),ic=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:u="",receivedAtMap:m={},emptyState:x,onLoadMore:p,isLoadingMore:h,hasMoreHistory:g,hiddenLiveCount:S=0,loadError:I,scrollToBottomRequestNonce:d},b){var ge;const y=a.useRef(null),l=a.useRef(null),C=a.useRef(null),M=a.useRef(0),N=a.useRef(""),f=a.useRef(!1),w=a.useRef(null),v=a.useRef(!1),k=a.useRef(null),$=a.useRef(!1),[L,B]=a.useState(new Set),A=a.useRef(!1),q=()=>{const W=y.current;return W?W.scrollHeight-W.scrollTop-W.clientHeight<200:!0},R=a.useCallback((W="auto")=>{const V=y.current;V&&V.scrollTo({top:V.scrollHeight,behavior:W})},[]),j=a.useCallback(()=>{var ie;const W=y.current,V=(ie=window.getSelection)==null?void 0:ie.call(window);if(!W||!V||V.rangeCount===0||V.isCollapsed){$.current=!1;return}const D=V.anchorNode,ve=V.focusNode;$.current=!!(D&&ve&&W.contains(D)&&W.contains(ve))},[]),K=a.useCallback((W="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,R(W)})},[R]),Y=s.length>0?`${s.length}:${(((ge=s[s.length-1])==null?void 0:ge.content)||"").length}`:"0:0";a.useEffect(()=>{const W=!f.current,V=N.current!==u;if(N.current=u,W||V){f.current=!0,A.current=!1,v.current=!0,$.current||K("auto"),M.current=s.length;return}s.length>M.current?!A.current&&!$.current&&K("auto"):q()&&!A.current&&!$.current&&K("auto"),M.current=s.length},[Y,u,c,s.length,K]),a.useEffect(()=>{d&&(A.current=!1,v.current=!0,k.current!=null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{v.current=!1,k.current=null},180),$.current||K("auto"))},[K,d]),a.useEffect(()=>()=>{w.current!=null&&cancelAnimationFrame(w.current),k.current!=null&&window.clearTimeout(k.current)},[]),a.useEffect(()=>{const W=l.current;if(!W)return;const V=()=>{k.current!=null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{v.current=!1,k.current=null},180)},D=new ResizeObserver(()=>{v.current&&($.current||(K("auto"),V()))});return D.observe(W),()=>{D.disconnect(),k.current!=null&&(window.clearTimeout(k.current),k.current=null)}},[K,u]),a.useImperativeHandle(b,()=>({scrollToBottom:(W="smooth")=>{R(W)}}),[R]),a.useEffect(()=>{const W=y.current;if(!W)return;let V;const D=()=>{clearTimeout(V),V=setTimeout(()=>{A.current=!q()},50)};return W.addEventListener("scroll",D,{passive:!0}),()=>{W.removeEventListener("scroll",D),clearTimeout(V)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",j),()=>document.removeEventListener("selectionchange",j)),[j]);const _=a.useRef(0),E=a.useRef(!1);a.useEffect(()=>{const W=y.current;if(!W||!E.current||_.current===0)return;const V=W.scrollHeight-_.current;V>0&&(W.scrollTop=V),_.current=0,E.current=!1},[s.length]);const O=()=>{const W=y.current;W&&(_.current=W.scrollHeight),E.current=!0,p==null||p()},U=a.useMemo(()=>{const W=s.map((ie,J)=>({type:"message",data:ie,index:J,ts:rc(ie,J,m)}));if(!r||r.length===0)return W;const V=[...r].sort((ie,J)=>ie.timestamp-J.timestamp).map((ie,J)=>({type:"action",data:ie,index:J,ts:ie.timestamp})),D=[];let ve=0;for(const ie of W){for(;ve<V.length&&ie.ts>0&&V[ve].ts<ie.ts;)D.push(V[ve++]);D.push(ie)}for(;ve<V.length;)D.push(V[ve++]);return D},[s,r,m]),X=S>0||!!g,re=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return e.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:l,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..."}),X&&!h&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:O,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:re})}),U.length===0&&!X&&(x||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),U.map(W=>{if(W.type==="action"){const te=W.data;return e.jsx(ac,{log:te},`action-${W.index}`)}const V=W.data,D=W.index,ve=ns(V,D),ie=V.receivedAt||m[ve],J=`${u}-${ve}`,pe=L.has(J);return e.jsx(oc,{message:V,receivedAt:ie,agentName:n,userName:o,isCliMode:i,isTextExpanded:pe,onToggleTextExpanded:()=>B(te=>{const ce=new Set(te);return pe?ce.delete(J):ce.add(J),ce})},`msg-${ve}`)}),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:C})]})})}),cc=a.memo(ic,(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),lc="modulepreload",dc=function(t){return"/"+t},Pn={},uc=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(m=>{if(m=dc(m),m in Pn)return;Pn[m]=!0;const x=m.endsWith(".css"),p=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${p}`))return;const h=document.createElement("link");if(h.rel=x?"stylesheet":lc,x||(h.as="script"),h.crossOrigin="",h.href=m,u&&h.setAttribute("nonce",u),document.head.appendChild(h),x)return new Promise((g,S)=>{h.addEventListener("load",g),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return o.then(c=>{for(const u of c||[])u.status==="rejected"&&i(u.reason);return s().catch(i)})};let Rn=!1;const Oa=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,u]=a.useState(null),m=a.useRef([]),x=a.useRef(!1),p=a.useRef(!1),h=a.useRef(!1),g=()=>{const S=i.current;if(S){x.current&&(S.clear(),x.current=!1);for(const I of m.current)S.write(I);m.current=[],p.current&&(S.fit(),p.current=!1),h.current&&(S.bumpResize(),h.current=!1)}};return a.useImperativeHandle(o,()=>({write:S=>{i.current?i.current.write(S):m.current.push(S)},clear:()=>{i.current?i.current.clear():(m.current=[],x.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.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():p.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():h.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const S=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(S)},[c]),a.useEffect(()=>{let S=!1;return uc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(I=>{Rn||(Rn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||u(()=>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"}})});Oa.displayName="CliTerminal";function Ks({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 Ln({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,u=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:u}})})]}):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, ${u}, ${u}cc)`}})}),o&&e.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function mc({cursorPos:t,viewportRef:s,imgRef:r}){var l;if(!t||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(l=s.current)==null?void 0:l.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,u=n.naturalHeight||o.height,m=c/u,x=o.width/o.height;let p,h,g,S;m>x?(p=o.width,h=o.width/m,g=0,S=(o.height-h)/2):(h=o.height,p=o.height*m,g=(o.width-p)/2,S=0);const I=o.left-i.left+g+p*t.nx,d=o.top-i.top+S+h*t.ny,b=Math.max(8,Math.min(i.width-8,I)),y=Math.max(8,Math.min(i.height-8,d));return e.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 pc({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:u,handleImeSubmit:m,isConnActive:x,zoom:p,isMobile:h,mobileFillZoom:g,onZoomOut:S,onZoomReset:I,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:l}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:C=>C.stopPropagation(),onChange:C=>u(C.target.value),onKeyDown:C=>{m(C)},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(C=>!C),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"})]}),p>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*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"}),y&&y.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),l&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:l})]})]}),o&&e.jsxs("div",{onTouchStart:C=>C.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: ",p<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(p*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:C=>{C.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:C=>{C.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:C=>{C.stopPropagation(),d()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function fc({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 xc(){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 En(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 Ls(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!xc())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,u])=>[c,En(u)]))}),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,En(s[c])]))}),r.current=s})}function hc({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:u,panYRef:m,setPanX:x,setPanY:p,setZoom:h,lastWheelTimeRef:g,onAction:S,setLastActionStatus:I,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:l}){const[C,M]=a.useState(null),N=a.useRef(null),f=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),k=a.useRef(null),$=a.useRef(0),L=a.useRef(null),B=a.useRef(1),A=a.useRef({x:0,y:0}),q=a.useRef(!1),R=a.useRef(n),j=a.useRef(S),K=30,Y=550,_=18,E=60,O=400,U=12,X=()=>{if(N.current)return;const W={nx:.5,ny:.5};N.current=W,M(W)};return a.useEffect(()=>{R.current=n,n==="mouse"&&X()},[n]),a.useEffect(()=>{j.current=S},[S]),a.useEffect(()=>{const W=t.current;if(!W)return;const V=te=>{if(!r.current)return null;const ce=r.current.getBoundingClientRect();return!ce.width||!ce.height?null:{nx:Math.max(0,Math.min(1,(te.clientX-ce.left)/ce.width)),ny:Math.max(0,Math.min(1,(te.clientY-ce.top)/ce.height))}},D=(te,ce)=>{if(!r.current)return{dnx:0,dny:0};const ne=r.current,fe=ne.getBoundingClientRect(),G=ne.naturalWidth||fe.width,se=ne.naturalHeight||fe.height,ee=G/se,ye=fe.width/fe.height;let we,P;return ee>ye?(we=fe.width,P=fe.width/ee):(P=fe.height,we=fe.height*ee),{dnx:te/we,dny:ce/P}},ve=(te,ce,ne)=>{if(ne<=1.05)return;const fe=-(te-.5)*100,G=-(ce-.5)*100,se=b(fe,G,ne);(Math.abs(se.x-u.current)>.1||Math.abs(se.y-m.current)>.1)&&(x(se.x),p(se.y),u.current=se.x,m.current=se.y)},ie=te=>{const ce=s.current;if(ce&&te.target instanceof Node&&ce.contains(te.target))te.preventDefault();else return;if(te.touches.length===1){const ne=te.touches[0];f.current={x:ne.clientX,y:ne.clientY,time:Date.now()},w.current={x:ne.clientX,y:ne.clientY},q.current||(v.current=!1),k.current=setTimeout(()=>{if(!v.current&&!q.current)if(v.current=!0,R.current==="mouse"){const fe=N.current||{nx:.5,ny:.5};I("Right Click"),d(fe.nx,fe.ny,"right"),j.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=V(ne);fe&&(I("Right Click"),d(fe.nx,fe.ny,"right"),j.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(te.touches.length===2){k.current&&clearTimeout(k.current),v.current=!0,q.current=!0;const ne=te.touches[1].clientX-te.touches[0].clientX,fe=te.touches[1].clientY-te.touches[0].clientY;L.current=Math.sqrt(ne*ne+fe*fe),B.current=c.current,A.current={x:(te.touches[0].clientX+te.touches[1].clientX)/2,y:(te.touches[0].clientY+te.touches[1].clientY)/2}}},J=te=>{const ce=s.current;if(ce&&te.target instanceof Node&&ce.contains(te.target)&&te.preventDefault(),te.touches.length===1&&w.current){const ne=te.touches[0],fe=ne.clientX-w.current.x,G=ne.clientY-w.current.y;if(!v.current&&f.current){const se=ne.clientX-f.current.x,ee=ne.clientY-f.current.y;Math.sqrt(se*se+ee*ee)>8&&(v.current=!0,k.current&&clearTimeout(k.current))}if(v.current)if(R.current==="mouse"){const se=D(fe,G),ee=N.current||{nx:.5,ny:.5},ye=Math.max(0,Math.min(1,ee.nx+se.dnx)),we=Math.max(0,Math.min(1,ee.ny+se.dny));N.current={nx:ye,ny:we},M({nx:ye,ny:we}),I(`Cursor: ${Math.round(ye*100)}%, ${Math.round(we*100)}%`),ve(ye,we,c.current);const P=Date.now();P-g.current>=30&&(g.current=P,j.current("input_mouseMoved",{nx:ye,ny:we}).catch(()=>{}))}else if(c.current>1){const se=s.current;if(se){const ee=se.clientWidth,ye=se.clientHeight,we=u.current+fe/ee*100,P=m.current+G/ye*100,ue=b(we,P,c.current);x(ue.x),p(ue.y),u.current=ue.x,m.current=ue.y}}else{const se=V(ne);if(se){const ee=Date.now();ee-g.current>=40&&(g.current=ee,I("Scroll"),j.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-G*2.5)}).catch(()=>{}))}}w.current={x:ne.clientX,y:ne.clientY};return}if(te.touches.length===2&&L.current!==null){const ne=te.touches[1].clientX-te.touches[0].clientX,fe=te.touches[1].clientY-te.touches[0].clientY,se=Math.sqrt(ne*ne+fe*fe)/L.current,ee=(te.touches[0].clientX+te.touches[1].clientX)/2,ye=(te.touches[0].clientY+te.touches[1].clientY)/2,we=ee-A.current.x,P=ye-A.current.y,ue=Math.abs(se-1)>.03;if(R.current==="mouse"){if(ue){const H=Math.max(i,Math.min(5,B.current*se));h(H),c.current=H}else if(Math.abs(we)>2||Math.abs(P)>2){const H=N.current||{nx:.5,ny:.5},le=Date.now();le-g.current>=30&&(g.current=le,I("Scroll"),j.current("input_wheel",{nx:H.nx,ny:H.ny,deltaX:Math.round(-we*3),deltaY:Math.round(-P*3)}).catch(()=>{}))}}else{const H=Math.max(i,Math.min(5,B.current*se));h(H),c.current=H;const le=s.current;if(le&&H>1){const Ce=le.clientWidth,me=le.clientHeight,_e=u.current+we/Ce*100,F=m.current+P/me*100,Q=b(_e,F,H);x(Q.x),p(Q.y),u.current=Q.x,m.current=Q.y}}A.current={x:ee,y:ye}}},pe=te=>{var ce;if(k.current&&clearTimeout(k.current),L.current=null,te.touches.length===1&&q.current){const ne=te.touches[0];f.current={x:ne.clientX,y:ne.clientY,time:Date.now()},w.current={x:ne.clientX,y:ne.clientY},v.current=!0;return}if(te.touches.length===0){if(q.current){q.current=!1,v.current=!1;return}if(te.changedTouches.length===1){const ne=te.changedTouches[0],fe=Date.now(),G=fe-(((ce=f.current)==null?void 0:ce.time)||0),se=f.current?ne.clientX-f.current.x:0,ee=f.current?ne.clientY-f.current.y:0,ye=Math.sqrt(se*se+ee*ee);if(R.current==="mouse"){if(G<K||G>Y||ye>_){v.current=!1;return}const we=N.current||V(ne);we&&(I(`Click: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),d(we.nx,we.ny,"left"),j.current("input_click",{...we}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(G<E||G>O||ye>U){v.current=!1;return}const we=V(ne);if(!we)return;fe-$.current<300?(I("Double tap"),d(we.nx,we.ny,"double"),j.current("input_click",{...we,clickCount:2}).catch(()=>{}),$.current=0):(I(`Tap: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),d(we.nx,we.ny,"left"),j.current("input_click",{...we}).catch(()=>{}),$.current=fe)}}v.current=!1}};return W.addEventListener("touchstart",ie,{passive:!1}),W.addEventListener("touchmove",J,{passive:!1}),W.addEventListener("touchend",pe,{passive:!1}),()=>{W.removeEventListener("touchstart",ie),W.removeEventListener("touchmove",J),W.removeEventListener("touchend",pe),k.current&&clearTimeout(k.current)}},[t,s,r,i,c,u,m,x,p,h,g,I,d,b]),{cursorPos:C,cursorPosRef:N,handleToggleInputMode:()=>{o(W=>{const V=W==="touch"?"mouse":"touch";return V==="mouse"&&X(),V})},handleZoomReset:()=>{const W=y?l:1;h(W),c.current=W,x(0),p(0),u.current=0,m.current=0}}}function Ua({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),u=a.useRef(null),m=a.useRef(null),[x,p]=a.useState(null),[h,g]=a.useState(""),[,S]=a.useState(!1),[I,d]=a.useState([]),b=a.useRef(0),[y,l]=a.useState(!1),[C,M]=a.useState(!1),N=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[f,w]=a.useState(N?"mouse":"touch"),[v,k]=a.useState(1),$=a.useRef(!1),[L,B]=a.useState(1),[A,q]=a.useState(0),[R,j]=a.useState(0);Ls("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:f,zoom:L,panX:A,panY:R,isMenuOpen:y,isImeOpen:C});const K=a.useRef(0),Y=a.useRef(L),_=a.useRef(A),E=a.useRef(R);a.useEffect(()=>{Y.current=L},[L]),a.useEffect(()=>{_.current=A},[A]),a.useEffect(()=>{E.current=R},[R]),a.useEffect(()=>{var G;(G=c.current)==null||G.focus()},[]);const O=r==="connected",U=n,X=O?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=O?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!N||$.current||!U)return;const G=m.current,se=u.current;if(!G||!se)return;const ee=()=>{const ye=se.clientWidth,we=se.clientHeight,P=G.naturalWidth,ue=G.naturalHeight;if(!P||!ue||!ye||!we)return;const H=Math.min(ye/P,we/ue),Ce=Math.max(ye/P,we/ue)/H;Ce>1.01&&(k(Ce),B(Ce),Y.current=Ce),$.current=!0};G.complete&&G.naturalWidth?ee():G.addEventListener("load",ee,{once:!0})},[U,N]);const ge=.5;a.useEffect(()=>{L<=ge&&(q(0),j(0))},[L,ge]);const W=(G,se,ee)=>{if(ee<=ge)return{x:0,y:0};const ye=(ee-1)/(2*ee)*100,we=(ee-1)/(2*ee)*100;return{x:Math.max(-ye,Math.min(ye,G)),y:Math.max(-we,Math.min(we,se))}},V=(G,se)=>{if(!m.current)return null;const ee=m.current.getBoundingClientRect();return!ee.width||!ee.height?null:{nx:Math.max(0,Math.min(1,(G-ee.left)/ee.width)),ny:Math.max(0,Math.min(1,(se-ee.top)/ee.height))}},D=(G,se,ee)=>{const ye=u.current;if(!ye)return;const we=ye.getBoundingClientRect(),P=++b.current;d(ue=>[...ue,{id:P,x:G-we.left,y:se-we.top,type:ee}]),setTimeout(()=>d(ue=>ue.filter(H=>H.id!==P)),600)},ve=(G,se,ee)=>{const ye=m.current,we=u.current;if(!ye||!we)return;const P=ye.getBoundingClientRect(),ue=we.getBoundingClientRect(),H=ye.naturalWidth||P.width,le=ye.naturalHeight||P.height,Ce=H/le,me=P.width/P.height;let _e,F,Q,ae;Ce>me?(_e=P.width,F=P.width/Ce,Q=0,ae=(P.height-F)/2):(F=P.height,_e=P.height*Ce,Q=(P.width-_e)/2,ae=0);const de=P.left-ue.left+Q+_e*G,Se=P.top-ue.top+ae+F*se,Me=++b.current;d(Le=>[...Le,{id:Me,x:de,y:Se,type:ee}]),setTimeout(()=>d(Le=>Le.filter(Ee=>Ee.id!==Me)),600)},ie=async G=>{var ee;const se=V(G.clientX,G.clientY);if(se){p(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),D(G.clientX,G.clientY,"left"),(ee=c.current)==null||ee.focus();try{const ye=await t("input_click",{nx:se.nx,ny:se.ny});ye!=null&&ye.success||s(`❌ Click failed: ${ye==null?void 0:ye.error}`)}catch(ye){s(`❌ Click error: ${ye.message||ye}`)}}},J=async(G,se,ee,ye=0)=>{try{await t("input_key",{type:ee?"char":"keyDown",key:G,code:se,text:ee?G:void 0,unmodifiedText:ee?G:void 0,modifiers:ye})}catch(we){s(`❌ Key error: ${we.message||we}`)}},pe=async G=>{if(G.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(G.key)&&G.preventDefault();let ee=0;G.altKey&&(ee|=1),G.ctrlKey&&(ee|=2),G.metaKey&&(ee|=4),G.shiftKey&&(ee|=8),p(`Key: ${G.key}`),await J(G.key,G.code,G.key.length===1,ee)},te=async G=>{if(G.key==="Enter"){if(G.nativeEvent.isComposing)return;if(h){const se=h;g(""),p(`IME Sent: ${se}`);try{const ee=await t("input_type",{text:se});ee!=null&&ee.success||s(`❌ IME error: ${ee==null?void 0:ee.error}`)}catch(ee){s(`❌ IME error: ${ee.message}`)}}else p("Key: Enter"),await J("Enter","Enter",!1)}};a.useEffect(()=>{const G=c.current;if(!G)return;const se=ee=>{var ye;if((ye=m.current)!=null&&ye.contains(ee.target)){ee.preventDefault();const we=Date.now();if(we-K.current<40)return;K.current=we;const P=V(ee.clientX,ee.clientY);if(!P)return;p(`Scroll: ${Math.round(ee.deltaY)}`),t("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(ee.deltaX),deltaY:Math.round(ee.deltaY)}).catch(()=>{})}};return G.addEventListener("wheel",se,{passive:!1}),()=>G.removeEventListener("wheel",se)},[t]);const{cursorPos:ce,handleToggleInputMode:ne,handleZoomReset:fe}=hc({containerRef:c,viewportRef:u,imgRef:m,inputMode:f,setInputMode:w,minZoom:ge,zoomRef:Y,panXRef:_,panYRef:E,setPanX:q,setPanY:j,setZoom:B,lastWheelTimeRef:K,onAction:t,setLastActionStatus:p,spawnRippleFromNormalized:ve,clampPan:W,isMobile:N,mobileFillZoom:v});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:pe,onContextMenu:G=>G.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[e.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[U?e.jsx("img",{ref:m,src:U,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${A}%, ${R}%)`,transformOrigin:"center center",cursor:f==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:G=>G.preventDefault(),onDragStart:G=>G.preventDefault()}):e.jsx(fc,{waitingLabel:X,waitingHint:re,transportType:i}),f==="mouse"&&U&&e.jsx(mc,{cursorPos:ce,viewportRef:u,imgRef:m}),I.map(G=>{const ee={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[G.type];return e.jsxs("div",{style:{position:"absolute",left:G.x,top:G.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ee}, 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(${ee}, 0.9)`,boxShadow:`0 0 12px rgba(${ee}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},G.id)})]}),e.jsx(pc,{inputMode:f,onToggleInputMode:ne,isImeOpen:C,setIsImeOpen:M,isMenuOpen:y,setIsMenuOpen:l,imeText:h,setImeText:g,handleImeSubmit:te,isConnActive:O,zoom:L,isMobile:N,mobileFillZoom:v,onZoomOut:()=>B(G=>Math.max(.5,G-.25)),onZoomReset:fe,onZoomIn:()=>B(G=>Math.min(5,G+.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 za(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 u=Math.floor(c/60);if(u<60)return`${u}m${r}`;const m=Math.floor(u/60);if(m<24)return`${m}h${r}`;const x=Math.floor(m/24);return x<7?`${x}d${r}`:new Date(t).toLocaleDateString()}const Ha=t=>za(t);function bc(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ms(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 Es(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...bc(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 As(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 _s(t,s,r){const n=As(t,s),o=ms(t),i=o.isReconnecting,c=o.isConnecting,u=o.isGenerating,m=o.isWaiting,x=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||m,p=n.inboxBucket==="working"||u,h=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:h,requiresAction:x,isWorking:p,isReconnecting:i,isConnecting:c,isGenerating:u,isWaiting:m,inboxBucket:x?"needs_attention":p?"working":h?"task_complete":"idle"}}function gc(t,s,r){return _s(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function yc(t,s,r){return As(t,r||new Map).surfaceHidden}function Fa({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ms(t).isWaiting||!t.modalButtons)return null;const i=u=>{r||(n(u),s(u))},c=u=>u.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(Xt,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((u,m)=>{const x=c(u).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(x),h=/^(reject|deny|delete|remove|abort)/.test(x),g=r===u,S=r!==null;return e.jsx("button",{onClick:()=>i(u),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!g?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}: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:g?"⏳ ...":c(u)},m)})})]})]})}const gt=new Map;function Dn({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:u,acpModes:m}){var ge;const{sendCommand:x}=bt(),p=!!(u||m),h=`${t}:${s||n}`,g=gt.get(h),[S,I]=a.useState(!1),[d,b]=a.useState(!1),[y,l]=a.useState((g==null?void 0:g.models)||[]),[C,M]=a.useState((g==null?void 0:g.modes)||[]),N=W=>W?typeof W=="string"?W:typeof W=="object"?W.name||W.id||JSON.stringify(W):String(W):"",[f,w]=a.useState(N(i)),[v,k]=a.useState(N(c)),[$,L]=a.useState(!1),[B,A]=a.useState(!1),q=a.useRef(0),R=W=>W.map(V=>typeof V=="string"?V:(V==null?void 0:V.name)||(V==null?void 0:V.id)||String(V));a.useEffect(()=>{if(u){const W=u.find(V=>V.category==="model");if(W){const V=R(W.options.map(ve=>ve.value));l(V),W.currentValue&&w(N(W.currentValue));const D=gt.get(h)||{models:[],modes:[]};gt.set(h,{...D,models:V})}}if(m&&m.length>0){const W=R(m.map(D=>D.id));M(W);const V=gt.get(h)||{models:[],modes:[]};gt.set(h,{...V,modes:W})}else if(u){const W=u.find(V=>V.category!=="model");if(W){const V=R(W.options.map(ve=>ve.value));M(V),W.currentValue&&k(N(W.currentValue));const D=gt.get(h)||{models:[],modes:[]};gt.set(h,{...D,modes:V})}}},[u,m,h]),a.useEffect(()=>{I(!1),b(!1),w(N(i)),k(N(c));const W=gt.get(h);W?(l(W.models),M(W.modes)):(l([]),M([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>q.current&&w(N(i))},[i]),a.useEffect(()=>{c&&Date.now()>q.current&&k(N(c))},[c]);const j=a.useCallback(async(W,V={})=>{const D={...V,...s&&{targetSessionId:s}};return await x(t,W,D)},[t,s,x]),K=async()=>{var W,V;if(y.length>0){I(!S);return}if(p){I(!0);return}L(!0);try{const D=await j("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),ve=(D==null?void 0:D.models)||((W=D==null?void 0:D.result)==null?void 0:W.models)||[],ie=R(ve);l(ie),D!=null&&D.current&&w(N(D.current)),(V=D==null?void 0:D.result)!=null&&V.current&&w(N(D.result.current));const J=gt.get(h)||{models:[],modes:[]};gt.set(h,{...J,models:ie}),I(!0)}catch{}finally{L(!1)}},Y=async()=>{var W,V;if(C.length>0){b(!d);return}if(p){b(!0);return}A(!0);try{const D=await j("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),ve=(D==null?void 0:D.modes)||((W=D==null?void 0:D.result)==null?void 0:W.modes)||[],ie=R(ve);M(ie),D!=null&&D.current&&k(N(D.current)),(V=D==null?void 0:D.result)!=null&&V.current&&k(N(D.result.current));const J=gt.get(h)||{models:[],modes:[]};gt.set(h,{...J,modes:ie}),b(!0)}catch{}finally{A(!1)}},_=async W=>{I(!1);const V=f;w(W),q.current=Date.now()+5e3;try{const D=p?await j("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:W}):await j("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:W});if((D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change model")}catch(D){console.warn("Model change failed",D),w(V),q.current=0}},E=p&&!(m&&m.length>0)&&(u==null?void 0:u.some(W=>W.category!=="model")),O=E?(ge=u==null?void 0:u.find(W=>W.category!=="model"))==null?void 0:ge.configId:void 0,U=async W=>{b(!1);const V=v;k(W),q.current=Date.now()+5e3;try{let D;if(p&&E&&O?D=await j("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:O,value:W}):p?D=await j("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:W}):D=await j("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:W}),(D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change mode")}catch(D){console.warn("Mode change failed",D),k(V),q.current=0}},re={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:re},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?`${re}55`:"transparent",border:"1px solid",color:f?"var(--text-primary)":"var(--text-muted)"},onClick:K,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),$?"...":f||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),S&&y.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"}),y.map(W=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W===f?`${re}18`:"transparent",color:W===f?re:"var(--text-secondary)",fontWeight:W===f?600:400,borderLeft:W===f?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:V=>{V.currentTarget.style.background=`${re}12`},onMouseLeave:V=>{V.currentTarget.style.background=W===f?`${re}18`:"transparent"},onClick:()=>_(W),children:W},W))]})]})]}),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:d?`${re}55`:"transparent",border:"1px solid",color:v?"var(--text-primary)":"var(--text-muted)"},onClick:Y,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:E?"🧠":"⚡"}),B?"...":v||(E?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),d&&C.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"}),C.map(W=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W===v?`${re}18`:"transparent",color:W===v?re:"var(--text-secondary)",fontWeight:W===v?600:400,borderLeft:W===v?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:V=>{V.currentTarget.style.background=`${re}12`},onMouseLeave:V=>{V.currentTarget.style.background=W===v?`${re}18`:"transparent"},onClick:()=>U(W),children:W},W))]})]})]})]})}const $n=new Map,vc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function wc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:u,serverMode:m,acpConfigOptions:x,acpModes:p}){const{sendCommand:h}=bt(),g=`${t}:${s||n}`,S=vc[n]||"#94a3b8",[I,d]=a.useState({}),b=a.useRef(0),y={...u?{model:u}:{},...m?{mode:m}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&d({})},[c]);const[l,C]=a.useState($n.get(g)||{}),[M,N]=a.useState(null),[f,w]=a.useState(null),v=a.useCallback(async(j,K={})=>{const Y={...K,...s&&{targetSessionId:s}};return await h(t,j,Y)},[t,s,h]),k=a.useCallback(async(j,K={},Y)=>{const _=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const E=await v("invoke_provider_script",{..._,scriptName:j,...K});return(E==null?void 0:E.success)===!1&&Y?await v(Y,{..._,...K}):E}catch(E){if(!Y)throw E;return await v(Y,{..._,...K})}},[v,n,r]);if(!i||i.length===0)return e.jsx(Dn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:u,serverMode:m,acpConfigOptions:x,acpModes:p});const $=i.filter(j=>j.placement==="bar").sort((j,K)=>(j.order??50)-(K.order??50));if($.length===0)return e.jsx(Dn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:u,serverMode:m,acpConfigOptions:x,acpModes:p});const L=async j=>{var Y,_,E;if(M===j.id){N(null);return}if((((Y=j.options)==null?void 0:Y.map(O=>O.value))||l[j.id]||[]).length>0){N(j.id);return}if(j.dynamic&&j.listScript){w(j.id);try{const O=Ws(j.listScript),U=await k(j.listScript,{},O),re=((U==null?void 0:U.models)||(U==null?void 0:U.modes)||((_=U==null?void 0:U.result)==null?void 0:_.models)||((E=U==null?void 0:U.result)==null?void 0:E.modes)||(U==null?void 0:U.options)||[]).map(ge=>typeof ge=="string"?ge:(ge==null?void 0:ge.name)||(ge==null?void 0:ge.id)||(ge==null?void 0:ge.value)||String(ge));C(ge=>{const W={...ge,[j.id]:re};return $n.set(g,W),W}),N(j.id)}catch{}finally{w(null)}}},B=async(j,K)=>{N(null),d(Y=>({...Y,[j.id]:K})),b.current=Date.now()+5e3;try{if(!j.setScript)return;await k(j.setScript,{model:j.id==="model"?K:void 0,mode:j.id==="mode"?K:void 0,value:K},Ws(j.setScript))}catch{}},A=async j=>{var U;const K=((U=j.options)==null?void 0:U.map(X=>X.value))||l[j.id]||[];if(K.length===0)return;const Y=String(y[j.id]||""),E=(K.indexOf(Y)+1)%K.length,O=K[E];if(typeof O=="string"){d(X=>({...X,[j.id]:O})),b.current=Date.now()+5e3;try{if(!j.setScript)return;await k(j.setScript,{value:O},Ws(j.setScript))}catch{}}},q=async j=>{const Y=!y[j.id];d(_=>({..._,[j.id]:Y})),b.current=Date.now()+5e3;try{if(!j.setScript)return;await k(j.setScript,{value:Y},Ws(j.setScript))}catch{}},R=async j=>{if(j.invokeScript)try{await k(j.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:"│"}),$.map(j=>{var O;const K=String(y[j.id]||""),Y=M===j.id,_=f===j.id,E=((O=j.options)==null?void 0:O.map(U=>U.value))||l[j.id]||[];switch(j.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:Y?`${S}55`:"transparent",border:"1px solid",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>L(j),children:[j.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:j.icon}),_?"...":K||j.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),Y&&E.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(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:j.label.toUpperCase()}),E.map(U=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:U===K?`${S}18`:"transparent",color:U===K?S:"var(--text-secondary)",fontWeight:U===K?600:400,borderLeft:U===K?`2px solid ${S}`:"2px solid transparent"},onMouseEnter:X=>{X.currentTarget.style.background=`${S}12`},onMouseLeave:X=>{X.currentTarget.style.background=U===K?`${S}18`:"transparent"},onClick:()=>B(j,U),children:U},U))]})]})]},j.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:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>A(j),title:`Click to cycle: ${E.join(" → ")}`,children:[j.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:j.icon}),K||j.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},j.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:K?`${S}44`:"transparent",background:K?`${S}14`:"var(--surface-tertiary)",color:K?S:"var(--text-muted)"},onClick:()=>q(j),children:[j.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:j.icon}),j.label]},j.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:()=>R(j),children:[j.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:j.icon}),j.resultDisplay==="inline"&&K?`${j.label}: ${K}`:j.label]},j.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:K?"var(--text-primary)":"var(--text-muted)"},children:[j.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:j.icon}),K?`${j.label}: ${K}`:j.label]},j.id);default:return null}})]})}function Ws(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const jc=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[u,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const x=()=>{const p=u.trim();!p||n||(m(""),o(p))};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:u,onChange:p=>m(p.target.value),onPaste:p=>{const h=p.clipboardData.getData("text");h&&m(g=>g+h),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),x()}},onBlur:p=>{if(window.innerWidth<768){const h=p.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:!u.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.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:u.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var kc=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Nc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function at(t,s){if(Nc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":kc.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 Va(t){return at(t)==="generating"}function He(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Sc(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 kr(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function pr(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 Cc(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 Ic(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Mc(t){return Cc(t.trim().replace(/\.local$/i,""))}function Ac(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function qa(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&&!Ic(c));if(r&&r!=="Unknown")return Mc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function ft(t,s={}){return Ac(t)||qa(t,s)}function Ts(t){return t.transport==="pty"}function as(t){return t.transport==="acp"}function Bn(t,s){return He(t)}function Kn(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=He(r||"").trim().toLowerCase();return n===o||n===i||n===c}function _c(t){return at(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Tc(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=at(n.status);if(!i){s.set(o,{...n,status:c});continue}const u=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(u<0||m<u)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Pc(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 Rc(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&&Pc(s.receivedAt)||0}function Lc(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function zr(t){return Math.max(Lc(t),Rc(t.activeChat))}function Ec(t,s,r,n,o,i){const c=s-t;if(c!==0)return c;const u=r.localeCompare(n);return u!==0?u:o.localeCompare(i)}function nn(t,s){return Ec(zr(t),zr(s),ft(t,{fallbackId:t.id}),ft(s,{fallbackId:s.id}),t.id,s.id)}const ze=t=>t.transport==="pty",ls=(t,s)=>ze(t)?t.mode||"terminal":"chat",Ga=(t,s)=>ze(t)&&ls(t)==="terminal",Oe=t=>t.transport==="acp";function Rt(t){return t.streamSource!=="agent-stream"}function Kt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function Ya(t){return t.machineName||""}function ar(t){return Kt(t)}function pt(t){return t.agentType||""}function an(t){return t.hostIdeType||""}function fr(t){return t.displayPrimary||t.agentName||"Agent"}function on(t){return[t.displaySecondary,Ya(t)].filter(Boolean)}function Ds(t){return t.agentName||He(pt(t))}function Dc(t){var s,r;if(!Rt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return He(an(t)||pt(t))}function cn(t){return Rt(t)?t.sessionId:t.nativeSessionId}function Wn(t){return Rt(t)?"native":t.tabKey}function $c(t){return t.sessionId}function Bc(t,s){if(s)return Rt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function Kc(t,s){const r=pt(t),n=Rt(t)?s!=null&&s.type?He(s.type):He(an(t)||r):Ds(t);return{isNativeConversation:Rt(t),isCli:ze(t),isAcp:Oe(t),isCliTerminal:Ga(t),providerType:r,displayLabel:n,targetEntry:Bc(t,s)}}function Xa({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ds(),c=Kt(t),u=Ya(t),m=t.transport==="cdp-page"||t.transport==="cdp-webview",x=t.streamSource==="agent-stream"&&!!t.agentName,p=!x&&(t.transport==="pty"||t.transport==="acp"),h=Ds(t),g=Dc(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 d=cn(t);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:g,children:[e.jsx(xt,{size:12}),e.jsx("span",{children:g})]}):e.jsxs("span",{className:"conversation-meta-chip",title:g,children:[e.jsx(xt,{size:12}),e.jsx("span",{children:g})]})),x&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Ms,{size:12}),e.jsx("span",{children:h})]}),p&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Ms,{size:12}),e.jsx("span",{children:h})]}),u&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:u,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:u})]}):e.jsxs("span",{className:"conversation-meta-chip",title:u,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:u})]}))]})}function On(t,s){return`${t}:${s}`}function Wc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Os(t,s){Wc()&&console.debug(`[subscription-manager] ${t}`,s)}class Oc{constructor(){Xe(this,"active",new Map)}subscribe(s,r,n,o){var u;const i=On(n.topic,n.key),c=this.active.get(i);if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const m={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,m),Os("subscribe",{daemonId:r,topic:n.topic,key:n.key}),(u=s.sendData)==null||u.call(s,r,n)}return()=>{var p;const m=this.active.get(i);if(!m||(m.handlers.delete(o),m.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};Os("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(p=s.sendData)==null||p.call(s,r,x)}}publish(s){const r=On(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,n.handlers.forEach(o=>{o(s)}))}resubscribeAll(s){var r;Os("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);Os("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 $t=new Oc;function Uc(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 Us(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),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 zc(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 or(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,u=c||t.timestamp||Date.now(),m=t.sessions||[],{topLevel:x,childrenByParent:p}=zc(m),h=Uc(i,n),g=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"),d=x.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:u,...t.version&&{version:t.version},...g&&{machine:g,platform:g.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 y=h.get(b.id),l=Us(b,y),C=(p.get(b.id)||[]).map(M=>Us(M,h.get(M.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:l.workspace,terminals:0,childSessions:C,agents:C.map(M=>({id:M.id,name:M.providerName||M.providerType,type:M.providerType,status:M.status})),activeChat:l.activeChat,chats:[],cdpConnected:l.cdpConnected,...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.currentAutoApprove!==void 0&&{currentAutoApprove:l.currentAutoApprove},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:u})}for(const b of I){const y=h.get(b.id),l=Us(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:b.id,cliName:l.providerName||l.providerType,mode:l.mode||(y==null?void 0:y.mode)||"terminal",workspace:l.workspace||"",activeChat:l.activeChat,...l.resume!==void 0&&{resume:l.resume},...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:u,_isCli:!0})}for(const b of d){const y=h.get(b.id),l=Us(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:b.id,cliName:l.providerName||l.providerType,mode:"chat",workspace:l.workspace||"",activeChat:l.activeChat,...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.acpConfigOptions!==void 0&&{acpConfigOptions:l.acpConfigOptions},...l.acpModes!==void 0&&{acpModes:l.acpModes},...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:u,_isAcp:!0})}return r}const Nr=new Map,Sr=new Map,Cr=new Set,js=new Map,Hc=1200;function Fc(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 Un(t,s){const r=js.get(t);!r||r.size===0||(js.delete(t),r.forEach(n=>n(s)))}function Vc(t,s){return new Promise(r=>{const n=js.get(t)||new Set;js.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&js.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function $s(){const{sendCommand:t,sendData:s}=bt(),{injectEntries:r,getIdes:n}=nr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,u=Sr.get(o)||0;if(!(i!=null&&i.force)&&Cr.has(o)&&u>0||!(i!=null&&i.force)&&u>0&&Date.now()-u<c)return;const m=Nr.get(o);if(m)return m;const x=(async()=>{if(s&&!Cr.has(o)&&(Cr.add(o),$t.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(C=>C.id===o),l=or(d.status,{daemonId:o,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});l.length>0&&r(l),Sr.set(o,Date.now()),Un(o,!0)}),!(i!=null&&i.force)&&await Vc(o,Hc)))return;const p=await t(o,"get_status_metadata"),h=Fc(p);if(!h)return;const g=n(),S=g.find(d=>d.id===o),I=or(h,{daemonId:o,existingDaemon:S,existingEntries:g,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),Sr.set(o,Date.now()),Un(o,!0)})().finally(()=>{Nr.delete(o)});return Nr.set(o,x),x},[n,r,t,s])}function Zt(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function Ja(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=Jt(t.content),i=Jt(s.content);if(!o||o!==i)return!1;const c=Zt(t),u=Zt(s);return c&&u?Math.abs(c-u)<=15e3:!!t._localId!=!!s._localId}function zn(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),Zt(t)&&(s+=1),s}function qc(t,s){const r=zn(t),n=zn(s);return n!==r?n>r?s:t:Jt(s.content).length>=Jt(t.content).length?s:t}function ks(t){const s=[];for(const r of t){const n=s.findIndex(o=>Ja(o,r));if(n>=0){s.splice(n,1,qc(s[n],r));continue}s.push(r)}return s}function Hn(t){return[...t].sort((s,r)=>{const n=Zt(s),o=Zt(r);return n&&o&&n!==o?n-o:0})}function Fn(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${Jt(t==null?void 0:t.content).slice(0,100)}`}function Vn(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=>Ja(i,n));return o>=0?(r.splice(o,1),!1):!0})}function Gc(t,s){const r=new Set(s.map(n=>Fn(n)));return t.filter(n=>!r.has(Fn(n)))}function Yc(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Xc(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 qn(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 Za(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return Xc([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function Jc(t){return{knownMessageCount:t.length,lastMessageSignature:Za(t[t.length-1])}}function Zc(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return ks([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return ks([...t.slice(0,n),...r])}case"full":default:return r}}const Qc=60,Gn=60;function Hr({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:x,isInputActive:p=!0}){var V,D,ve,ie;const h=a.useRef(new Map),g=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:I,sendData:d}=bt(),b=$s();Ls("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const y=Ye.useMemo(()=>ms(t),[t.status,t.connectionState]),l=a.useRef(new Map),C=a.useCallback(J=>(l.current.has(J)||l.current.set(J,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:Qc}),l.current.get(J)),[]),M=a.useCallback((J,pe)=>{const te=C(J);l.current.set(J,{...te,...pe}),N(ce=>ce+1)},[C]),[,N]=a.useState(0),f=t.tabKey,w=C(f),v=w.messages,k=w.hasMore,$=w.error,L=g.current.get(f),B=t.messages.filter(J=>!!(J!=null&&J._localId)),A=L?ks([...L,...B]):t.messages,q=Math.max(0,A.length-w.visibleLiveCount),R=fr(t),j=ar(t),K=t.sessionId||"",Y=t.providerSessionId||K,_=a.useMemo(()=>Kc(t,s),[t,s]),[E,O]=a.useState(!1);a.useEffect(()=>{const J=_.targetEntry;j&&(!J||J.providerControls===void 0||J.controlValues===void 0||_.isAcp&&(J.acpConfigOptions===void 0||J.acpModes===void 0))&&b(j,{minFreshMs:3e4}).catch(()=>{})},[j,_.isAcp,(V=_.targetEntry)==null?void 0:V.providerControls,(D=_.targetEntry)==null?void 0:D.controlValues,(ve=_.targetEntry)==null?void 0:ve.acpConfigOptions,(ie=_.targetEntry)==null?void 0:ie.acpModes,b]),a.useEffect(()=>{if(!j||!K||!d)return;const J=g.current.get(f)||[],pe=S.current.get(f),te=pe&&pe.knownMessageCount?pe:Jc(J),ce=`daemon:${j}:session:${K}`;return $t.subscribe({sendData:d},j,{type:"subscribe",topic:"session.chat_tail",key:ce,params:{targetSessionId:K,historySessionId:Y,knownMessageCount:te.knownMessageCount,lastMessageSignature:te.lastMessageSignature,...te.knownMessageCount?{}:{tailLimit:Gn}}},fe=>{const G=g.current.get(f)||[],se=Zc(G,fe),ee=Math.max(se.length,Number(fe.totalMessages||0));S.current.set(f,{knownMessageCount:ee,lastMessageSignature:typeof fe.lastMessageSignature=="string"?fe.lastMessageSignature:Za(se[se.length-1])}),qn(G)!==qn(se)&&(g.current.set(f,se),N(we=>we+1))})},[j,Y,d,K,f]);const U=a.useCallback(async()=>{if(E)return;const J=t.tabKey,pe=C(J);if(A.length>pe.visibleLiveCount){M(J,{visibleLiveCount:Math.min(A.length,pe.visibleLiveCount+Gn),error:null});return}O(!0),M(J,{error:null});try{const te=ar(t);if(!te){M(J,{hasMore:!1});return}const ce=pt(t),ne=await I(te,"chat_history",{agentType:ce,offset:pe.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),fe=Yc(ne),G=fe.messages||[];if(G.length>0){const se=C(J);M(J,{messages:[...G,...se.messages],offset:se.offset+G.length,hasMore:!!fe.hasMore})}else M(J,{hasMore:!!fe.hasMore})}catch(te){const ce=(te==null?void 0:te.message)||"";ce.includes("P2P not available")||ce.includes("channel not open")||ce.includes("P2P not connected")||ce.includes("timeout")?M(J,{error:"Connection not ready — tap to retry"}):M(J,{hasMore:!1,error:"Failed to load history"})}finally{O(!1)}},[E,t,A.length,I,C,M]),{allMessages:X,receivedAtMap:re}=a.useMemo(()=>{const J=q>0?A.slice(-w.visibleLiveCount):A;if(v.length===0){const ne=Hn(ks(J)),fe={};return ne.forEach((G,se)=>{const ee=`${t.tabKey}:${ns(G,se)}`;let ye=Zt(G)||h.current.get(ee)||0;ye||(ye=Date.now(),h.current.set(ee,ye)),fe[ns(G,se)]=ye}),{allMessages:ne,receivedAtMap:fe}}const pe=Gc(v,J),te=Hn(ks([...pe,...J])),ce={};return te.forEach((ne,fe)=>{const G=`${t.tabKey}:${ns(ne,fe)}`;let se=Zt(ne)||h.current.get(G)||0;se||(se=Date.now(),h.current.set(G,se)),ce[ns(ne,fe)]=se}),{allMessages:te,receivedAtMap:ce}},[t.tabKey,q,v,A,w.visibleLiveCount]),ge=a.useMemo(()=>c.filter(J=>J.routeId===t.tabKey).sort((J,pe)=>J.timestamp-pe.timestamp),[c,t.tabKey]),W=a.useMemo(()=>{if(A.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((y.isGenerating||t.status==="streaming")&&O(!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(Ms,{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(cs,{size:14})," Open ",R," 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(Da,{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(cs,{size:14})," Open ",R," 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,A.length,R,y.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&e.jsx(Xa,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(cc,{messages:X,actionLogs:ge,agentName:Ds(t)||R||"Agent",userName:u,isCliMode:_.isCli||_.isAcp,isWorking:y.isGenerating,contextKey:t.tabKey,receivedAtMap:re,onLoadMore:U,isLoadingMore:E,hasMoreHistory:k,hiddenLiveCount:q,loadError:$??void 0,emptyState:W,scrollToBottomRequestNonce:x}),p&&!_.isCliTerminal&&(()=>{var J,pe,te,ce,ne,fe;return e.jsx(wc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:_.providerType,displayLabel:_.displayLabel,controls:(J=_.targetEntry)==null?void 0:J.providerControls,controlValues:(pe=_.targetEntry)==null?void 0:pe.controlValues,serverModel:((te=_.targetEntry)==null?void 0:te.currentModel)||void 0,serverMode:((ce=_.targetEntry)==null?void 0:ce.currentPlan)||void 0,acpConfigOptions:_.isAcp?(ne=_.targetEntry)==null?void 0:ne.acpConfigOptions:void 0,acpModes:_.isAcp?(fe=_.targetEntry)==null?void 0:fe.acpModes:void 0})})(),!_.isCliTerminal&&e.jsx(jc,{contextKey:t.tabKey,panelLabel:R,isSending:n,onSend:r,isActive:p})]})}let Qa=Yt;function eo(){return Qa()}class el{constructor(){Xe(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 to=new el;class tl{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 Ge=new tl;function sl(t){t.dashboardWS&&(to=t.dashboardWS),t.connectionManager&&(Ge=t.connectionManager),t.useDaemonsHook&&(Qa=t.useDaemonsHook)}function Ve(t){return fr(t)}function Qt(t){return on(t).join(" · ")}function so(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=Jt(s==null?void 0:s.content);return r||(t.title?t.title:Qt(t)||"No messages yet")}function ro(t,s){const{isReconnecting:r,isConnecting:n}=ms(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function rl(t,s){const r=["Chat",...on(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function os(t){return ro(t)||Qt(t)}function nl(t){return`${Ve(t)} · ${so(t)}`}function al(t){const s=an(t)||pt(t);return`${Ve(t)} — ${He(s)}`}function ol(t){return Ds(t)||"CLI"}function no(t){return t.title||Ds(t)||t.routeId}function il(t){return t?`Remote · ${Ve(t)||t.workspaceName||"Session"}`:"Remote"}function cl({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var E;const{ides:c}=Yt(),u=a.useRef(null),{sendCommand:m,sendData:x}=bt(),[p,h]=a.useState(""),[g,S]=a.useState(!1),[I,d]=a.useState(1),b=a.useRef(!1),y=a.useRef(0),l=a.useRef(!1),C=a.useRef(""),M=a.useRef(null),N=a.useRef(!1),f=a.useRef(null),w=t.tabKey,v=t.sessionId||"",k=t.daemonId||((E=t.routeId)==null?void 0:E.split(":")[0])||t.routeId||"",$=c.find(O=>O.id===k&&O.type==="adhdev-daemon"),L=($==null?void 0:$.terminalSizingMode)==="fit"?"fit":"measured",B=.6,A=1.15,q=()=>{if(typeof window>"u")return 1;const O=window.innerWidth||0;return O<=360?.68:O<=390?.74:O<=430?.82:O<=480?.9:1},R=()=>{var O,U;y.current=0,l.current=!1,C.current="",M.current=null,N.current=!1,f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),S(!1),(U=(O=r.current)==null?void 0:O.reset)==null||U.call(O)},j=()=>{var O,U;y.current=0,l.current=!1,C.current="",M.current=null,N.current=!1,f.current!==null&&(cancelAnimationFrame(f.current),f.current=null),S(!0),(U=(O=r.current)==null?void 0:O.reset)==null||U.call(O)},K=()=>{var U;if(f.current=null,!i)return;const O=C.current;O&&(C.current="",(U=r.current)==null||U.write(O))},Y=O=>{O&&(C.current+=O,i&&f.current===null&&(f.current=requestAnimationFrame(K)))},_=(O,U=0,X,re)=>{var ge,W,V,D,ve;U>0&&y.current>=U||U===0&&l.current||(y.current=U,S(!0),typeof X=="number"&&typeof re=="number"&&X>0&&re>0&&((W=(ge=r.current)==null?void 0:ge.resize)==null||W.call(ge,X,re)),(D=(V=r.current)==null?void 0:V.reset)==null||D.call(V),O&&((ve=r.current)==null||ve.write(O)))};return a.useEffect(()=>{R()},[v]),a.useEffect(()=>{var U;if(!v)return;const O=((U=Ge.onRuntimeEvent)==null?void 0:U.call(Ge,v,X=>{if(!(!X||X.sessionId!==v)){if(X.type==="runtime_snapshot"){if(!i){M.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}_(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){l.current=!0,typeof X.seq=="number"&&(y.current=Math.max(y.current,X.seq)),g||S(!0),typeof X.data=="string"&&Y(X.data);return}if(X.type==="session_cleared"){if(!i){N.current=!0,C.current="",M.current=null;return}j()}}}))||(()=>{});return()=>{O()}},[k,v,r,i,g]),a.useEffect(()=>{var U,X,re;if(!v)return;k&&((U=Ge.getState)==null?void 0:U.call(Ge,k))==="connected"&&(S(!0),(X=Ge.requestRuntimeSnapshot)==null||X.call(Ge,k,v).catch(()=>{}));const O=(re=Ge.onStateChange)==null?void 0:re.call(Ge,(ge,W)=>{var V;ge!==k||W!=="connected"||(S(!0),(V=Ge.requestRuntimeSnapshot)==null||V.call(Ge,k,v).catch(()=>{}))});return()=>{O==null||O()}},[k,v,r]),a.useEffect(()=>{s&&R()},[s,w,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const O=()=>{b.current||d(q())};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]),a.useEffect(()=>{var U;if(!i){(U=u.current)==null||U.blur();return}N.current&&(N.current=!1,j());const O=M.current;O&&(M.current=null,_(O.text,O.seq,O.cols,O.rows)),C.current&&f.current===null&&(f.current=requestAnimationFrame(K)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),a.useEffect(()=>()=>{f.current!==null&&(cancelAnimationFrame(f.current),f.current=null)},[]),a.useEffect(()=>{const O=U=>{var re;const X=U.detail;X!=null&&X.sessionId&&X.sessionId!==v||g&&((re=r.current)==null||re.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",O),()=>{window.removeEventListener("adhdev:fit-cli-terminal",O)}},[g,v,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,d(O=>Math.max(B,Number((O-.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,d(O=>Math.min(A,Number((O+.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(Oa,{ref:r,readOnly:!g||!i,sizingMode:L,onInput:O=>{g&&(x!=null&&x(k,{type:"pty_input",targetSessionId:v,data:O})||m(k,"pty_input",{targetSessionId:v,data:O}).catch(console.error))}})})}),!g&&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:u,type:"text",placeholder:`Send message to ${Ve(t)}...`,value:p,disabled:!g||!i||o,onChange:O=>h(O.target.value),onPaste:O=>{const U=O.clipboardData.getData("text");U&&h(X=>X+U),O.preventDefault()},onKeyDown:O=>{if(O.key!=="Enter")return;if(O.nativeEvent.isComposing){O.preventDefault();return}O.preventDefault();const U=p.trim();!g||!U||o||(h(""),n(U))},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 O=p.trim();!g||!O||o||(h(""),n(O))},disabled:!g||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:p.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function ll({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)"},u={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:u[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 dl({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 u=(r==null?void 0:r.trim())||"This machine",m=()=>{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:[u," 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:m,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function ln({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(ur,{size:n}):e.jsx(Lt,{size:n})})}function Yn({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=on(t);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:fr(t)}),(r||o.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,o.join(" · ")]})]})}function ul({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:u,activeCliViewMode:m,onSetCliViewMode:x,onOpenConversation:p,onHideConversation:h,hiddenConversations:g=[],onShowConversation:S,onShowAllHidden:I,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:l,onOpenNewSession:C}){const{ides:M,p2pStates:N={}}=Yt(),f=!!t&&ze(t)&&!Oe(t),w=!!t&&Oe(t),v=m||(t?Ga(t)?"terminal":"chat":null),[k,$]=a.useState(!1),L=a.useRef(null),B=a.useRef(null),A=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",q=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",R=M.filter(D=>D.type==="adhdev-daemon"),j=a.useMemo(()=>Es(M),[M]),K=Object.values(N),Y=K.filter(D=>D==="connected").length,_=K.filter(D=>D==="connecting"||D==="new"||D==="checking").length,O=r!=="connected"||R.length===0?null:_>0&&Y===0?"P2P connecting...":Y>0&&s===0?"Waiting for IDE...":null,U=a.useMemo(()=>o.filter(D=>!yc(D,o,j)),[o,j]),X=a.useMemo(()=>U.filter(D=>_s(D,j).requiresAction),[U,j]),re=a.useMemo(()=>U.filter(D=>{const ve=(t==null?void 0:t.tabKey)===D.tabKey;return _s(D,j,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ve}).unread}),[t,U,j]),ge=a.useMemo(()=>[...X,...re].slice(0,9),[X,re]),W=X.length+re.length;a.useEffect(()=>{if(!d)return;const D=ve=>{var ie;(ie=L.current)!=null&&ie.contains(ve.target)||b(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[d,b]),a.useEffect(()=>{if(!y)return;const D=ve=>{var ie;(ie=B.current)!=null&&ie.contains(ve.target)||l(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[y,l]),a.useEffect(()=>{if(!y&&!d)return;const D=ve=>{if(!ve.altKey)return;const ie=ve.code.match(/^Digit([1-9])$/);if(!ie)return;const J=Number(ie[1])-1,pe=y?g[J]:void 0,te=d?ge[J]:void 0,ce=pe||te;if(ce){if(ve.preventDefault(),ve.stopPropagation(),pe){S==null||S(pe),l(!1);return}p==null||p(ce),b(!1)}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[g,y,d,ge,l,b,p,S]);const V=D=>{if(!D)return;const ve=o.find(ie=>ie.tabKey===D);ve&&(h==null||h(ve))};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(Lt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Ve(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:A,boxShadow:q}})})]}),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:A,boxShadow:q}}),O&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",O]}),C&&e.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(zi,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(f||w||!Oe(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:Qt(t)||Ve(t),children:Ve(t)}),(f||w)&&u&&e.jsxs(e.Fragment,{children:[f&&x&&v&&e.jsx(ln,{mode:v,onChange:x,compact:!0}),e.jsx("button",{onClick:()=>u(t),className:"btn btn-secondary btn-sm",title:w?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:e.jsx(ht,{size:14})})]}),!Oe(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(tn,{size:14})}),!f&&!Oe(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(xt,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:L,children:[e.jsxs("div",{className:`dashboard-header-hidden${k?" is-drop-target":""}`,ref:B,onDragEnter:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),$(!0))},onDragOver:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),D.dataTransfer.dropEffect="move",$(!0))},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||$(!1)},onDrop:D=>{const ve=D.dataTransfer.getData("text/tab-key");D.preventDefault(),$(!1),V(ve)},children:[e.jsxs("button",{type:"button",onClick:()=>l(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx($a,{size:16}),g.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:g.length})]}),y&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),g.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),l(!1)},children:"Restore all"})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Ve(t)})]}),g.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:g.map(D=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(D),l(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Ve(D)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[g.indexOf(D)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",g.indexOf(D)+1]}):null,Qt(D)]})]},D.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(mr,{size:16}),W>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:W})]}),d&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[X.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),X.map(D=>e.jsx(Yn,{conversation:D,isAttention:!0,shortcutIndex:ge.indexOf(D)>=0?ge.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.tabKey))]}),re.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),re.map(D=>e.jsx(Yn,{conversation:D,shortcutIndex:ge.indexOf(D)>=0?ge.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.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 dn({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:u,onNewChat:m,onSwitchSession:x,onRefreshHistory:p,onResumeSavedSession:h}){var y;const g=s.find(l=>l.id===t.routeId),S=(g==null?void 0:g.chats)||[],I=(y=g==null?void 0:g.activeChat)==null?void 0:y.id,d=ze(t)&&!Oe(t),b=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:u,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:d?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:al(t)})]}),e.jsx("button",{onClick:u,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(ht,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!d&&e.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),d?e.jsx(e.Fragment,{children:o.map(l=>{const C=t.providerSessionId===l.providerSessionId,M=C||!l.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{M||!h||h(l)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${C?"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 ${C?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ml(l.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.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:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:C?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>e.jsxs("div",{onClick:()=>{x(t.routeId,l.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${I===l.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===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.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:[l.id.substring(0,12),"..."]}),I===l.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},l.id)),(d&&!i&&o.length===0||!d&&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(Vi,{size:32})}),e.jsx("div",{className:"text-[13px]",children:d?"No saved sessions found yet.":"No recent chat sessions found."})]}),d&&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:p,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(us,{size:13})," ",d?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Ma.createPortal(b,document.body)}const Xn={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 ao({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=Xn[n.type]||Xn.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(ht,{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:u=>{u.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const pl=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function fl(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function xl(t){return t.sessionId||t.instanceId||t.agentType}function Ir(t,s){return t||s}function Jn(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 oo(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=ft(r,{fallbackId:r.id}));return s}function io(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 un(t,s,r={}){return hl(t,s,io(t,r))}function hl(t,s,r={}){var g,S,I,d,b,y;const n=[],o=r.machineName,i=r.connectionState,c=fl(t),u=He(t.type),m=Array.isArray(t.childSessions)?t.childSessions.map(l=>{var C,M;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||He(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((C=l.activeChat)==null?void 0:C.messages)||[],activeModal:((M=l.activeChat)==null?void 0:M.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],x=pl(t),p=t.activeChat||{title:""},h=p.title&&String(p.title).trim()?String(p.title).trim():"";if(x){const l=t.sessionId||t.instanceId,C=Bn(t.type),M=(g=t.activeChat)==null?void 0:g.activeModal,N=M&&Array.isArray(M.buttons)&&M.buttons.length>0,f=at((S=t.activeChat)==null?void 0:S.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||at((b=(d=t.agents)==null?void 0:d[0])==null?void 0:b.status)||"idle",w=t.activeChat||{title:"",messages:[]};let v=w.title&&String(w.title).trim()?String(w.title).trim():"";const k=(y=t.activeChat)==null?void 0:y.id,$=t.chats;if(k&&Array.isArray($)&&$.length>0){const j=$.find(K=>K.id===k||K.id&&String(K.id)===String(k));j!=null&&j.title&&String(j.title).trim()&&(v=String(j.title).trim())}const L=(ze(t)||Oe(t),t.type),B=(ze(t)||Oe(t))&&Kn(v,C,L)?"":v,A=w.messages||[],q=Jn(s,[t.id,l]),R=Vn(A,q);n.push({routeId:t.id,sessionId:l,providerSessionId:t.providerSessionId,nativeSessionId:l,transport:t.transport,daemonId:t.daemonId||void 0,mode:ze(t)?t.mode||"terminal":"chat",agentName:C,agentType:L,status:f,title:B,messages:[...A,...R],resume:t.resume,hostIdeType:!ze(t)&&!Oe(t)?t.type:void 0,workspaceName:c,displayPrimary:c||B||(ze(t)?t.mode==="chat"?C:"Terminal":C),displaySecondary:u,cdpConnected:t.cdpConnected,lastMessagePreview:t.lastMessagePreview,lastMessageRole:t.lastMessageRole,lastMessageAt:t.lastMessageAt,lastMessageHash:t.lastMessageHash,lastUpdated:t.lastUpdated,modalButtons:N?M.buttons:void 0,modalMessage:N?M.message:void 0,streamSource:"native",tabKey:Ir(l,t.id),machineName:o,connectionState:i})}if(x&&(ze(t)||Oe(t)))return n;for(const l of m){const C=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,M=_c(l),N=xl(l),f=`${t.id}:${N}`,w=l.title&&String(l.title).trim()||"",v=Kn(w,l.agentName,l.agentType)?"":w,k=l.messages||[],$=Jn(s,[f,l.sessionId,l.instanceId]),L=Vn(k,$);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||k.length>0||L.length>0||C||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(M))&&n.push({routeId:t.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:l.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:M,title:v,messages:[...k,...L],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||v||u,displaySecondary:`${u} · ${l.agentName}`,cdpConnected:t.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||t.lastUpdated,modalButtons:C?l.activeModal.buttons:void 0,modalMessage:C?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ir(l.sessionId||l.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:Bn(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:t.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,streamSource:"native",tabKey:Ir(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function bl(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 gl(t,s){const r=bl(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:"🏄"}],lo=[{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:"🧩"}],uo=[{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:"🟠"}],yl=co,vl=lo,wl=uo,mo="adhdev_notification_prefs",Zn={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function jl(){try{const t=localStorage.getItem(mo);if(t){const s=JSON.parse(t);return{...Zn,...s}}}catch{}return{...Zn}}function kl(t){try{localStorage.setItem(mo,JSON.stringify(t))}catch{}}let Pt=jl(),Zs=[];function Nl(){Zs.forEach(t=>t())}function Sl(t){Pt={...Pt,...t},kl(Pt),Nl()}function Cl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return Zs.push(r),()=>{Zs=Zs.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Sl(r)},[]);return[{...Pt},s]}function Ns(t){if(!Pt.globalEnabled)return!1;switch(t){case"disconnect":return Pt.disconnectAlert;case"completion":return Pt.completionAlert;case"approval":return Pt.approvalAlert;case"browser":return Pt.browserNotifications;default:return!0}}const Il={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ml(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function po(){return"Notification"in window&&Notification.permission==="granted"}let Ut=null;async function Al(){if(Ut!==null)return Ut;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ut=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Ut=!!await t.pushManager.getSubscription(),Ut):(Ut=!1,!1)}catch{return Ut=!1,!1}}function Fr(t,s,r){if(po())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 _l(t,s={}){const r={...Il,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Al().then(u=>{i.current=u})},[]);const c=a.useCallback((u,m,x)=>{const p=Date.now();p-o.current<r.throttleMs||(o.current=p,Fr(u,m,x))},[r.throttleMs]);a.useEffect(()=>{var u;if(!(!r.enabled||!po())&&Ns("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of t)n.current.set(m.id,at(m.status,{activeModal:m.activeModal}));return}for(const m of t){const x=n.current.get(m.id),p=at(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&Ns("approval")&&p==="waiting_approval"&&x!=="waiting_approval"){const g=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,g.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ns("completion")&&Va(x)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&x!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Tl=/^(run|approve|accept|yes|allow|always)/,Pl=/^(run|approve|accept|yes|allow|always|proceed|save)/,Rl=/^(reject|deny|delete|remove|abort|cancel|no)/;function mn(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ll(t){const s=mn(t).toLowerCase();return Tl.test(s)?"primary":Rl.test(s)?"danger":"default"}function El(t){return Pl.test(mn(t).toLowerCase())?"approve":"reject"}function Dl(t){return t.map((s,r)=>({label:mn(s),variant:Ll(s),action:El(s),button:s,buttonIndex:r}))}function $l(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
29
- ${n}`}function Bl(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Kl(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 Wl{constructor(){Xe(this,"dedupMap",new Map);Xe(this,"DEDUP_WINDOW_MS",5e3);Xe(this,"DEDUP_MAX_SIZE",50);Xe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Xe(this,"toastCallbacks",[]);Xe(this,"systemMessageCallbacks",[]);Xe(this,"clearSystemMessageCallbacks",[]);Xe(this,"resolveActionFn",null);Xe(this,"viewRequestRespondFn",null);Xe(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,d;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),u=`${i}:${s.event}:${c}`;if(this.isDuplicate(u))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,x=(m==null?void 0:m.type)||"";let p=He(x);const h=this.resolveOwningDaemon(s);if(h){const b=ft(h,{fallbackId:h.id});b&&(p=!x||x==="adhdev-daemon"?b:`${b}/${p}`)}let g="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";g=`✅ ${p} 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(g=`⚡ ${p} approval needed`,S="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:$l(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const y=this.resolveActionFn,l=Dl(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{y(b,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),C=Bl(p,s.modalMessage,g),M=Date.now();this.emitToast({id:M,message:C,type:S,timestamp:M,targetKey:n||b,actions:l,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${p} agent is taking a long time${b}`,S="warning",Ns("browser")&&!document.hasFocus()&&Fr(`⚠️ ${p} — 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",y=s.requestId,l=s.orgId;if(g=`👁️ ${b} wants to view your session`,S="warning",y&&l&&this.viewRequestRespondFn){const C=Date.now(),M=Kl(l,y,this.viewRequestRespondFn,(N,f)=>console.error(`[EventManager] ${N} view request failed:`,f));this.emitToast({id:C,message:g,type:S,timestamp:C,actions:M,duration:3e4}),g=""}Ns("browser")&&!document.hasFocus()&&Fr("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(g){const b=Date.now();this.emitToast({id:b,message:g,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ot=new Wl;function es(...t){return bi(gi(t))}function Ol({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:es("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 fo({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:u}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Ol,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",i,c),children:u})})]})}function St({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:es("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 xo({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:es("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 Ul={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"},zl={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Hl({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:es("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ul[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:zl[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 Fl={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"},Vl={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ql({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:es("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Fl[t],r),children:[e.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Vl[t])}),n]})}function Gl(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Vr(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function Qs(t){return t==="system"?Gl():t}function Yl(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Qs(Vr()))}function pn(){const[t,s]=a.useState(Vr),[r,n]=a.useState(()=>Qs(Vr()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),u=m=>{t==="system"&&n(m.matches?"light":"dark")};return c.addEventListener("change",u),()=>c.removeEventListener("change",u)},[t]);const o=a.useCallback(c=>{s(c),n(Qs(c));try{localStorage.setItem("theme",c)}catch{}},[]),i=a.useCallback(()=>{s(c=>{const u=c==="dark"?"light":c==="light"?"system":"dark";n(Qs(u));try{localStorage.setItem("theme",u)}catch{}return u})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Qn={dark:"Dark",light:"Light",system:"System"};function Xl({collapsed:t}){const{preference:s,cycleTheme:r}=pn(),n=s==="dark"?e.jsx(Gi,{size:16}):s==="light"?e.jsx(qi,{size:16}):e.jsx(Yi,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Qn[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:Qn[s]})]})}function Ht({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 Jl({onPrefChange:t}){const[s,r]=Cl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(mr,{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(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xt,{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(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Xi,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ji,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ms,{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 ir(t){const s=t.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Zl(t,s){const r=ir(t),n=ir(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 ho(t,s){const r=t.version||null;return t.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ss(t,s){if(t.versionUpdateRequired===!0)return!0;const r=t.version||null;if(!r||!s||r===s||Zl(r,s)>=0)return!1;const n=ir(r),o=ir(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Ql(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Mr(t,s){return t instanceof Error?t.message:s}function ed({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(xo,{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(sd,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function ea({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 Ma.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:u=>u.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 td(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...yl,...vl,...wl].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 sd({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var q,R;const[i,c]=a.useState("idle"),[u,m]=a.useState(""),[x,p]=a.useState(null),[h,g]=a.useState("idle"),[S,I]=a.useState(""),d=t.version||null,b=((q=t.machine)==null?void 0:q.platform)||((R=t.system)==null?void 0:R.platform)||"",y=ft(t,{fallbackId:t.id}),l=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",C=s.filter(j=>j.daemonId===t.id&&j.transport==="cdp-page"),M=s.filter(j=>j.daemonId===t.id&&j.transport==="pty"),N=s.filter(j=>j.daemonId===t.id&&j.transport==="acp"),f=t.p2p,w=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const j=Ql(await r(t.id,"daemon_upgrade",{}));j.alreadyLatest?(c("done"),m(`Already on v${j.version||"latest"}.`)):j.upgraded||j.success?(c("done"),m(`Upgrade to v${j.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(j.error||"Upgrade failed"))}catch(j){c("error"),m(Mr(j,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){g("loading");try{await n(t.id),g("done"),I("Machine disconnected.")}catch(j){g("error"),I(Mr(j,"Failed to disconnect"))}}},k=async()=>{if(p(null),!!o){g("loading");try{await o(t.id),g("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(j){g("error"),I(Mr(j,"Failed to revoke token"))}}},$="0.8.41",L=ho(t,$),B=Ss(t,$),A=C.length+M.length+N.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:l}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y}),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),"…"]}),d&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!L&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&e.jsx("button",{onClick:w,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":`${B?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&e.jsx("button",{onClick:()=>p("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:()=>p("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(ql,{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&&A>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),A>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(j=>{const K=td(j.type),Y=j.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:K.icon}),e.jsx("span",{children:K.name}),Y!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Y?"bg-green-400":"animate-pulse"}`,style:Y?void 0:{background:"var(--status-warning)"},title:Y?"CDP connected":"CDP connecting..."})]},j.id)}),M.map(j=>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:j.cliName||"CLI"})]},j.id)),N.map(j=>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:j.cliName||"ACP"})]},j.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(u||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||u})]}),x==="disconnect"&&e.jsx(ea,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
30
-
31
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
32
-
33
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>p(null)}),x==="revoke"&&e.jsx(ea,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
34
-
35
- This will:
36
- • Immediately disconnect the machine
37
- • Delete the machine registration
38
- • Require restarting "adhdev-standalone" on that machine
39
-
40
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>p(null)})]})}const rd=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function nd(){const{preference:t,setPreference:s}=pn();return e.jsx("div",{className:"flex gap-2",children:rd.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 ad(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 od(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Ar(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ta(t){const{r:s,g:r,b:n}=od(t);return .2126*Ar(s)+.7152*Ar(r)+.0722*Ar(n)}function sa(t,s){const r=ta(t),n=ta(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function bo(t){const s=ad(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return sa(s,r)>=sa(s,n)?r:n}const qr={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},Gr={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},id=[{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"}}}],go="adhdev-chat-theme",yo="adhdev-chat-theme-custom";function er(){if(typeof window>"u")return"ember";try{return localStorage.getItem(go)||"ember"}catch{return"ember"}}function Ct(t){try{const s=localStorage.getItem(yo);if(s){const r=JSON.parse(s);return{...t==="dark"?qr:Gr,...r[t]}}}catch{}return t==="dark"?qr:Gr}function zs(t,s){try{localStorage.setItem(yo,JSON.stringify({dark:t,light:s}))}catch{}}function yt(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 cr(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 cd={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Cs(t,s){var o;const r=(o=cd[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",cr(r,24)),n.style.setProperty("--accent-on-primary",bo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${cr(r,18)})`),n.style.setProperty("--border-accent",yt(r,.35)),n.style.setProperty("--nav-active-bg",yt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${yt(r,.06)}`)}function Ft(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",yt(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",yt(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",yt(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",yt(t.borderSubtle,.5)),s.style.setProperty("--border-default",yt(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",cr(t.accentColor,30)),s.style.setProperty("--accent-on-primary",bo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${cr(t.accentColor,40)})`),s.style.setProperty("--border-accent",yt(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",yt(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${yt(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 ${yt(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 fn(){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 ld(t){try{localStorage.setItem(go,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(Ct(s))}else fn(),Cs(t,Vt()?"dark":"light")}function dd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=er();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(Ct(s))}else fn(),Cs(t,Vt()?"dark":"light")}function Vt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function nt({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 bs({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 ud({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>Ct(r));a.useEffect(()=>{o(Ct(r))},[r]);const i=a.useCallback((c,u)=>{o(m=>{const x={...m,[c]:u},h=Ct(r==="dark"?"light":"dark");return r==="dark"?zs(x,h):zs(h,x),Ft(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(bs,{title:"App Background",children:[e.jsx(nt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(nt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(nt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(bs,{title:"App Text",children:[e.jsx(nt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(nt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(nt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(bs,{title:"Borders & Accent",children:[e.jsx(nt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(nt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(nt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(bs,{title:"Chat Bubbles",children:[e.jsx(nt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(nt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(nt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(nt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(bs,{title:"Chat Layout",children:[e.jsx(nt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(nt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(nt,{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?qr:Gr,m=Ct(t?"light":"dark");t?zs(c,m):zs(m,c),o(c),Ft(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(er),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Ct("dark"));a.useEffect(()=>{n(Vt());const m=new MutationObserver(()=>{const h=Vt();n(h);const g=er();g==="custom"?Ft(Ct(h?"dark":"light")):Cs(g,h?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const x=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const h=Vt();n(h);const g=er();g==="custom"?Ft(Ct(h?"dark":"light")):Cs(g,h?"dark":"light")};return x.addEventListener("change",p),()=>{m.disconnect(),x.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ft(Ct(r?"dark":"light")):(fn(),Cs(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(Ct(r?"dark":"light"))},[r]);const c=m=>{s(m),ld(m)},u=[...id,{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:u.map(m=>{const x=t===m.id,p=r?m.preview.dark:m.preview.light,h=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(m.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:p.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.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:p.assistantBubble,border:p.assistantBorder,color:p.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:m.id==="custom"?"🎨 Custom":m.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),t==="custom"&&e.jsx(ud,{dark:r,onColorsChange:m=>i(m)})]})}const vo="adhdev_mobileDashboardMode_v1";function wo(){try{return localStorage.getItem(vo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function pd(t){try{localStorage.setItem(vo,t)}catch{}}function fd(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(wo()==="chat")},[]),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Lt,{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),pd(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function xd(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 hd(t,s){const{sendData:r}=bt(),{injectEntries:n,getIdes:o}=nr(),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 u=c.map(m=>$t.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},x=>{const p=o().find(g=>g.id===m),h=xd(p,m,x);n([h])}));return()=>{u.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function jo(t,s){const{sendData:r}=bt(),[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 u=$t.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}:{}}},m=>{o(m.diagnostics),c(!1)});return()=>{u()}},[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 bd(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function ko(t){const{sendData:s}=bt(),[r,n]=a.useState({});return a.useEffect(()=>{const o=bd(t);if(!o||!t.sessionId||!s){n({});return}const i=$t.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 No="adhdev_hiddenTabs";function gd(){try{const t=localStorage.getItem(No);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ss(t){try{localStorage.setItem(No,JSON.stringify([...t]))}catch{}}function yd(){const[t,s]=a.useState(gd),r=a.useCallback(x=>{s(p=>{const h=new Set(p);return h.has(x)?h.delete(x):h.add(x),ss(h),h})},[]),n=a.useCallback(x=>{s(p=>{if(p.has(x))return p;const h=new Set(p);return h.add(x),ss(h),h})},[]),o=a.useCallback(x=>{s(p=>{if(!p.has(x))return p;const h=new Set(p);return h.delete(x),ss(h),h})},[]),i=a.useCallback(()=>{s(x=>{if(x.size===0)return x;const p=new Set;return ss(p),p})},[]),c=a.useCallback((x,p)=>{s(h=>{const g=new Set(h);for(const S of p)g.add(S);return ss(g),g})},[]),u=a.useCallback((x,p)=>{s(h=>{const g=new Set(h);for(const S of p)g.delete(S);return ss(g),g})},[]),m=a.useCallback(x=>t.has(x),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:u,isHidden:m}}function vd({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Ml()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:no(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return _l(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(u=>{const m=Date.now(),x={};for(const[p,h]of Object.entries(u))m-h<5e3&&(x[p]=h);return Object.keys(x).length===Object.keys(u).length?u:x})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(u=>{const m=u.filter(x=>x.timestamp>c).slice(-100);return m.length===u.length?u:m})},6e4);return()=>clearInterval(i)},[n]),null}function wd(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 qt(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return wd(s==null?void 0:s.receivedAt)||0}function Yr(t,s=0){return qt(t)||t.lastUpdated||s||0}function So(t){return qt(t)||t.lastUpdated||0}function Co(t,s,r=So){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 Xr(t){var r;const s=at(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function jd(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!Xr(t)&&!t.title.trim()}function kd(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(Xr(r))-Number(Xr(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:Co(s,r)})[0]||null}function Et(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=kd(o);return n?i&&jd(n)?i:n:i||r[0]||null}function Nd(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 Hs(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 Sd(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 Cd(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 Id(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 Md(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Ad(t){const s=Md(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=Jt(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function _d({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),u=a.useRef([]),m=a.useRef([]),x=a.useMemo(()=>{const f=Nd(t);return Hs(i.current,f)?i.current:(i.current=f,f)},[t]),p=a.useMemo(()=>oo(t),[t]),h=a.useRef(new Map),g=a.useRef(new Map),S=a.useMemo(()=>{const f=new Map,w=[];for(const L of x){const{connectionState:B="new",machineName:A}=io(L,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),q=Cd(L,r),R=h.current.get(L.id);if(R&&R.ide===L&&R.connectionState===B&&R.machineName===A&&Id(R.localRefs,q)){f.set(L.id,R),w.push(...R.conversations);continue}const j=un(L,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),K={ide:L,connectionState:B,machineName:A,localRefs:q,conversations:j};f.set(L.id,K),w.push(...j)}h.current=f;const v=new Map,k=L=>{const B=Ad(L),A=g.current.get(L.tabKey);if(A&&A.signature===B)return v.set(L.tabKey,A),A.timestamp;const q={signature:B,timestamp:So(L)||(A==null?void 0:A.timestamp)||0};return v.set(L.tabKey,q),q.timestamp},$=[...w].sort((L,B)=>Co(L,B,k));return g.current=v,$},[x,r,s,p]),I=a.useMemo(()=>{const f=Sd(S,n);return Hs(c.current,f)?c.current:(c.current=f,f)},[S,n]),d=a.useMemo(()=>{const f=new Map,w=Array.from(new Set(I.map(v=>v.routeId)));for(const v of w){const k=Et(I,v);k&&f.set(v,k)}return f},[I]),b=a.useMemo(()=>{const f=new Map;for(const w of I)if(w.sessionId&&f.set(w.sessionId,w),w.streamSource==="native"&&w.sessionId){const v=d.get(w.routeId);v&&f.set(w.sessionId,v)}return f},[I,d]),y=a.useMemo(()=>{const f=new Map;for(const w of I)w.sessionId&&f.set(w.sessionId,w),f.set(w.routeId,d.get(w.routeId)||w),f.set(w.tabKey,w);return f},[I,d]),l=a.useCallback(f=>{if(f)return b.get(f)},[b]),C=a.useCallback(f=>{if(f)return y.get(f)},[y]),M=a.useMemo(()=>{const f=I.filter(w=>!o.has(w.tabKey));return Hs(u.current,f)?u.current:(u.current=f,f)},[I,o]),N=a.useMemo(()=>{const f=M.map(w=>w.tabKey);return Hs(m.current,f)?m.current:(m.current=f,f)},[M]);return{chatIdes:x,conversations:I,visibleConversations:M,visibleTabKeys:N,resolveConversationBySessionId:l,resolveConversationByTarget:C}}function Td({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var u;return t||!s?null:((u=r(s))==null?void 0:u.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var u;return!t||!s?null:((u=r(s))==null?void 0:u.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(u=>{const m=new URLSearchParams(u);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Pd({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{ot.setIdes(t)},[t]),a.useEffect(()=>{ot.setResolveAction((i,c,u)=>{s(i,c,u).catch(()=>{})})},[s]),a.useEffect(()=>{const i=ot.onToast(m=>{r(p=>p.some(g=>g.message===m.message&&m.timestamp-g.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const x=m.duration||5e3;setTimeout(()=>r(p=>p.filter(h=>h.id!==m.id)),x)}),c=ot.onSystemMessage((m,x)=>{var S,I;const p=o(m),h=(S=x._localId)==null?void 0:S.startsWith("sys_approval_"),g=!!(p&&(p.status==="waiting_approval"||(I=p.modalButtons)!=null&&I.length||p.modalMessage));h&&g||n(d=>({...d,[m]:[...d[m]||[],x]}))}),u=ot.onClearSystemMessage((m,x)=>{n(p=>{var h;return(h=p[m])!=null&&h.length?{...p,[m]:p[m].filter(g=>{var S;return!(g.role==="system"&&((S=g._localId)!=null&&S.startsWith(x)))})}:p})});return()=>{i(),c(),u()}},[r,n]),a.useEffect(()=>{const i=to.on("status_event",c=>{ot.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=u=>{var b;const m=u.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const x=m.targetSessionId||m.targetKey||m.daemonId,p=o(x),h=(p==null?void 0:p.routeId)||m.daemonId;if(!h)return;const g=Number(m.buttonIndex),S=m.button||((b=p==null?void 0:p.modalButtons)==null?void 0:b[g])||"Approve",I=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:d?"approve":"reject",button:S,...Number.isFinite(g)&&{buttonIndex:g},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var u;return(u=navigator.serviceWorker)==null?void 0:u.removeEventListener("message",i)}},[o,s])}const Rd="adhdev_dashboardLayout_v1",Ld="adhdev_dashboardDockview_v1",gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Io(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function Mo(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Ao(t){return`${Rd}:${t}`}function Ed(t){const s=Ao(t);return Io(s,null)}function Dd(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=Ao(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function _o(t){return`${Ld}:${t}`}function $d(t){const s=_o(t);return Io(s,null)}function Bd(t,s){try{const r=_o(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Kd(){return{groupAssignments:[...gs.groupAssignments],focusedGroup:gs.focusedGroup,groupActiveTabIds:{...gs.groupActiveTabIds},groupTabOrders:{...gs.groupTabOrders},groupSizes:[...gs.groupSizes]}}function Wd(){const[t]=a.useState(()=>Mo(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[u,m]=a.useState({}),[x,p]=a.useState([]),[h,g]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,I]=a.useState(!1),d=a.useCallback(()=>{if(S)return;const b=Ed(t)??Kd();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),p(b.groupSizes),I(!0)},[S,t]);return a.useEffect(()=>{S&&Dd(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:u,groupSizes:x})},[S,t,s,n,i,u,x]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=l=>g(l.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:u,setGroupTabOrders:m,groupSizes:x,setGroupSizes:p,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:d}}function Od(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 Ud({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:u,setSearchParams:m,historyModalOpen:x,activeConv:p,isRefreshingHistory:h,ides:g,handleRefreshHistory:S}){const I=a.useRef(!1),d=a.useRef(!1),b=a.useRef(null),y=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const l=r(t);if(!l)return;const C=n.get(l.tabKey)??0;c(M=>({...M,[C]:l.tabKey})),u(C),I.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(M=>{const N=new URLSearchParams(M);return N.delete("activeTab"),N},{replace:!0})},[t,s,r,n,o,i,c,u,m]),a.useEffect(()=>{if(!(d.current||o)&&s.length!==0){if(!t){i(),d.current=!0;return}if(I.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||o)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!x){y.current=!1;return}if(!p||y.current||h)return;const l=g.find(C=>C.id===p.routeId);l&&(!l.chats||l.chats.length===0||Od(l.chats,p))&&(y.current=!0,S())},[x,p,h,g,S]),a.useEffect(()=>{if(!p)return;let l=null,C=0,M=-1,N=0;const f=()=>{l=null;const w=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(k=>k.offsetParent!==null);if(w.length===0){C<18&&(C+=1,l=requestAnimationFrame(f));return}let v=0;for(const k of w)k.scrollTop=k.scrollHeight,v+=k.scrollHeight;v===M?N+=1:(N=0,M=v),C+=1,!(N>=2||C>=18)&&(l=requestAnimationFrame(f))};return l=requestAnimationFrame(f),()=>{l!=null&&cancelAnimationFrame(l)}},[p==null?void 0:p.tabKey])}function zd({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:u}){const[m,x]=a.useState(null),[p,h]=a.useState(null),g=a.useMemo(()=>{if(t||!n)return null;const y=u(n);return y&&!ze(y)&&!Oe(y)?y:null},[t,n,u]),S=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const l=m!=null&&m.tabKey?i.find(C=>C.tabKey===m.tabKey):o?i.find(C=>C.tabKey===o):null;return(l==null?void 0:l.routeId)===y?l:Et(i,y)},[i,m,o]),I=a.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);a.useEffect(()=>{g&&(x({routeId:g.routeId,tabKey:Wn(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=a.useCallback(y=>{y&&(x({routeId:y.routeId,tabKey:Wn(y)}),h(y))},[]),b=a.useCallback(()=>{x(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:I,remoteDialogActiveConv:p,setRemoteDialogActiveConv:h,openRemoteDialog:d,closeRemoteDialog:b}}function is(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:ze(t)||Oe(t)?{agentType:pt(t)}:t.streamSource==="agent-stream"?{agentType:pt(t)}:s}function Ps(t){return t?ar(t):""}function ys(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function _r(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 ra({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[u,m]=a.useState(!1),[x,p]=a.useState(!1),h=a.useCallback(async d=>{try{await t("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),g=a.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",l=await t(y,"switch_chat",{id:b,sessionId:b,...is(s)}),C=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?ys(o,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?ys(o,`⚠️ Switch error: ${C}`):ys(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),ys(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,t,o]),S=a.useCallback(async()=>{if(!(!s||u)){m(!0);try{const d=Ps(s);await t(d,"new_chat",{...is(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,u,t,c,i]),I=a.useCallback(async()=>{var d,b;if(!(!s||x)){p(!0);try{const y=Ps(s),l=async()=>t(y,"list_chats",{forceExpand:!0,...is(s)});let C=await l(),M=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);_r(M,s)&&(await new Promise(N=>setTimeout(N,450)),C=await l(),M=(C==null?void 0:C.chats)||((b=C==null?void 0:C.result)==null?void 0:b.chats)),C!=null&&C.success&&Array.isArray(M)&&(n(s.routeId,M),_r(M,s)&&!_r(r,s)&&ys(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,x,t,n,o]);return{isCreatingChat:u,isRefreshingHistory:x,handleLaunchIde:h,handleSwitchSession:g,handleNewChat:S,handleRefreshHistory:I}}function Hd(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 Fd(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function na(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 Fs(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,u]of t)!r.has(c)||u<=0||n.includes(u)||n.push(u);n.sort((c,u)=>c-u);const o={};n.forEach((c,u)=>{o[c]=u}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,u]of t){if(!r.has(c)||u<=0)continue;const m=o[u];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function aa(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 Vd(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 qd(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,u)=>c+u,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function oa(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 ia(t){return Array(t).fill(100/t)}function Gd({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:u,visibleConversations:m,visibleTabKeys:x}){const p=a.useRef(null),h=a.useMemo(()=>Fs(t,x),[t,x]),g=h.assignments,S=a.useMemo(()=>u?1:h.groupCount,[h.groupCount,u]),I=S>1,d=a.useCallback((N,f)=>{s(w=>{const v=new Map(Fs(w,x).assignments);return f===0?v.delete(N):v.set(N,f),v}),n(w=>({...w,[f]:N})),r(f)},[s,x,n,r]),b=a.useCallback(N=>{s(f=>{const w=Fs(f,x).assignments,v=new Map;for(const[k,$]of w)$!==N&&($>N?v.set(k,$-1):v.set(k,$));return v}),c(f=>{if(f.length<=1)return[];const w=[...f];w.splice(N,1);const v=w.reduce((k,$)=>k+$,0);return v>0?w.map(k=>k/v*100):[]}),r(0)},[s,x,c,r]),y=a.useCallback((N,f)=>{f.preventDefault();const w=p.current;if(!w)return;const v=f.clientX,k=w.offsetWidth,$=i.length===S?[...i]:ia(S),L=A=>{const R=(A.clientX-v)/k*100,j=[...$];j[N]=Math.max(15,$[N]+R),j[N+1]=Math.max(15,$[N+1]-R),c(j)},B=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",B),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",B)},[i,S,c]),l=a.useCallback((N,f,w)=>{if(S>=4)return;const v=w==="left"?f:f+1;s(k=>{const $=Fs(k,x).assignments,L=new Map;for(const B of m){const A=$.get(B.tabKey)??0,q=A>=v?A+1:A;q>0&&L.set(B.tabKey,q)}return v>0&&L.set(N,v),L}),c(k=>{const $=k.length===S?[...k]:ia(S),L=$[f]??100/S,B=Math.max(15,L/2),A=Math.max(15,L/2),q=[...$];q[f]=B,q.splice(v,0,A);const R=q.reduce((j,K)=>j+K,0);return q.map(j=>j/R*100)}),n(k=>{const $=oa(k,v);return $[v]=N,$}),o(k=>{const $=oa(k,v);return $[v]=[N],$}),r(v)},[S,s,x,m,c,n,o,r]);a.useEffect(()=>{Hd(t,g)||s(g)},[t,g,s]),a.useEffect(()=>{const{mapping:N,usedGroups:f}=h;n(w=>{const v=aa(w,N);return na(w,v)?w:v}),o(w=>{const v=aa(w,N);return na(w,v)?w:v}),r(w=>{const v=u?0:Vd(w,f,N);return w===v?w:v}),c(w=>{const v=u?[]:qd(w,f,h.groupCount);return Fd(w,v)?w:v})},[h,u,n,o,r,c]);const C=a.useMemo(()=>{const N=Array.from({length:S},()=>[]);for(const f of m){const w=g.get(f.tabKey)??0,v=Math.min(w,S-1);N[v].push(f)}return N},[m,g,S]),M=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:g,numGroups:S,isSplitMode:I,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:l,clearAllSplits:M}}function Yd({ides:t,sendDaemonCommand:s}){const r="0.8.41",n=a.useMemo(()=>t.filter(p=>p.type!=="adhdev-daemon"?!1:ho(p,r)).sort((p,h)=>Number(Ss(h,r))-Number(Ss(p,r))),[r,t]),o=a.useMemo(()=>n.some(p=>Ss(p,r)),[r,n]),[i,c]=a.useState(!1),[u,m]=a.useState({}),x=a.useCallback(async p=>{var h,g;m(S=>({...S,[p]:"upgrading"}));try{const S=await s(p,"daemon_upgrade",{});(h=S==null?void 0:S.result)!=null&&h.upgraded||(g=S==null?void 0:S.result)!=null&&g.success?m(I=>({...I,[p]:"done"})):m(I=>({...I,[p]:"error"}))}catch{m(S=>({...S,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:x}}function ca(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function xn(t){return t instanceof Error?t.message:String(t||"")}function la(t){const s=xn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function da(t,s){const r=xn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function xr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[u,m]=a.useState(!1),x=a.useRef(!1),p=a.useRef(null),h=a.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||x.current)return;const y=s.tabKey,l=Date.now(),C=p.current;if(C&&C.tabKey===y&&C.message===b&&l-C.timestamp<2e3)return;x.current=!0,m(!0),p.current={tabKey:y,message:b,timestamp:l};const M=`${l}-${Math.random().toString(36).slice(2,8)}`,N={role:"user",content:b,timestamp:l,_localId:M},f=!(ze(s)||Oe(s));f&&r(w=>({...w,[y]:[...w[y]||[],N]}));try{const w=Ps(s);if(!w)return;const v=await t(w,"send_chat",{message:b,...is(s)}),k=ca(v);if(f&&(k!=null&&k.deduplicated||(k==null?void 0:k.sent)===!1)){r($=>({...$,[y]:($[y]||[]).filter(L=>L._localId!==M)}));return}if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");setTimeout(()=>{const $=Date.now()-6e4;r(L=>{const B=L[y];if(!B)return L;const A=B.filter(q=>q.timestamp>$);return A.length===B.length?L:{...L,[y]:A}})},6e4)}catch(w){const v=xn(w);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",w),f&&r(k=>({...k,[y]:(k[y]||[]).filter($=>$._localId!==M)}))}finally{x.current=!1,m(!1)}},[s,t,r]),g=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,t]),S=a.useCallback(async d=>{if(s)try{const y=(s.modalButtons||[]).indexOf(d),l=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),M=Ps(s);if(!M)return;const N=await t(M,"resolve_action",{button:d,action:C?"approve":"reject",...y>=0&&{buttonIndex:y},...is(s)}),f=ca(N);f.success||n(w=>[...w,{routeId:s.tabKey,text:da(d,f==null?void 0:f.error),timestamp:Date.now()}])}catch(b){la(b)||console.error("[ModalButton] Error:",b),n(y=>[...y,{routeId:s.tabKey,text:la(b)?da(d,b):`❌ **${d}** 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(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:u,isFocusingAgent:i,handleSendChat:h,handleRelaunch:g,handleModalButton:S,handleFocusAgent:I}}const hn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:u,handleSendChat:m,isSendingChat:x,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:S,scrollToBottomRequestNonce:I,isInputActive:d=!0}){const b=ko(s),y=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(Fa,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.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(Xt,{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:u,children:"Relaunch with CDP"})]})}):null,y.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(cl,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:x,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(Hr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:x,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:S,scrollToBottomRequestNonce:I,isInputActive:d})})]}):e.jsx(Hr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:x,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:S,scrollToBottomRequestNonce:I,isInputActive:d})]})},(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 Xd({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:u,onBack:m,onOpenNativeConversation:x,onOpenMachine:p,onOpenHistory:h,onOpenRemote:g,onHideConversation:S,onStopCli:I,cliViewMode:d,onSetCliViewMode:b,handleSendChat:y,handleFocusAgent:l,handleModalButton:C,handleRelaunch:M}){const N=a.useRef(null),f=ze(t)&&!s,w=f&&d==="terminal",v=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center justify-between gap-3 ${v} 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:m,type:"button","aria-label":"Back",children:e.jsx(Qr,{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:Ve(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(Xa,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>x(t),onOpenMachine:()=>p(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[f&&d&&e.jsx(ln,{mode:d,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(ht,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(tn,{size:14})}),!s&&!f&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(t),type:"button",children:e.jsx(xt,{size:14})}),S&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(t),type:"button",title:"Close chat",children:e.jsx(ht,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(hn,{activeConv:t,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:N,handleModalButton:C,handleRelaunch:M,handleSendChat:y,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:u,actionLogs:o,userName:i})})]})}const Tr={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 Jd(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function To(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(Jd())},[]);const u=a.useCallback(()=>{navigator.clipboard.writeText(Tr[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:u,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:Tr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Tr[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 Po({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:xt},{key:"chats",label:"Chats",icon:Lt}];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 Vs({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 rs({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 vs({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 qs({item:t,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",u=s==="task_complete",{isReconnecting:m,isConnecting:x}=ms(t.conversation),p=Ve(t.conversation),h=Qt(t.conversation),g=ro(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",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",C="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(p)}),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 ${d}`,children:p}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:Ha(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${C} 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…"})]}):g==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:C,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:t.preview})]}),o&&!u&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&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 ua({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 Zd({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:u,onOpenConversation:m,onShowConversation:x,onShowAllHidden:p,onOpenNewSession:h,onOpenMachine:g,onOpenSettings:S,onSectionChange:I,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",l=c.length>0,C=s.length>0||r.length>0||n.length>0||o.length>0,M=t==="machines"?"Machines":"Chats",N=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 ${N}`,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(mr,{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(dr,{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:y?e.jsx(vs,{icon:e.jsx(ua,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(vs,{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(To,{})})}):e.jsx(rs,{children:c.map((w,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(w.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:u(w.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:w.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:w.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[w.unread," new"]}):w.total>0?`${w.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:w.subtitle}),w.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[w.total," chat",w.total!==1?"s":"",w.unread>0?` · ${w.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},w.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(Vs,{title:"Needs attention",className:"mb-0"}),e.jsx(rs,{children:s.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(qs,{item:w,type:"needs_attention",getAvatarText:u,onOpenConversation:m})},w.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(Vs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(rs,{children:r.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(qs,{item:w,type:"task_complete",getAvatarText:u,onOpenConversation:m})},w.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(Vs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(rs,{children:n.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(qs,{item:w,type:"working",getAvatarText:u,onOpenConversation:m})},w.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(Vs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(rs,{children:o.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(qs,{item:w,type:"earlier",getAvatarText:u,onOpenConversation:m})},w.conversation.tabKey))}):C?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?e.jsx(vs,{icon:e.jsx(ua,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?e.jsx(vs,{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(Lt,{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(vs,{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:p,children:"Restore all"})]}),e.jsx(rs,{className:"bg-bg-secondary/25",children:i.map((w,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(w),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:u(Ve(w))}),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:Ve(w)}),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:Qt(w)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},w.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(Po,{section:t,onSectionChange:I})]})}function Qd(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 hr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Qd(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 eu(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 br(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=(m,x)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${x}`:m==="/"||m==="\\"?`${i}${x}`:`${m.replace(/[\\/]+$/,"")}${i}${x}`,u=Array.isArray(n==null?void 0:n.files)?n.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:c(o,m.name)})).sort((m,x)=>m.name.localeCompare(x.name)):[];return{path:o,directories:u}}function gr({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:u,onNavigate:m,onConfirm:x}){const[p,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const g=eu(r),S=p.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:u,"aria-label":"Close folder browser",children:e.jsx(ht,{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:()=>{!g||o||m(g)},disabled:!g||o,children:[e.jsx(Qr,{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:p,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!S||o||(I.preventDefault(),m(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),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||m(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:()=>m(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(cs,{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:u,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 bn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:u=!1,showArgsInput:m,argsValue:x,onArgsChange:p,showModelInput:h,modelValue:g,onModelChange:S,historyProviderNode:I,onConfirm:d,onCancel:b}){const y=n==null?void 0:n.find(l=>l.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(ht,{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:l=>i(l.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:u,children:n.map(l=>e.jsx("option",{value:l.key,children:l.label},l.key))}),(y==null?void 0:y.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),I,r.map(l=>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:l.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:l.value})]},`${l.label}:${l.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:g||"",onChange:l=>S(l.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:u})]}),m&&p&&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:l=>p(l.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:u})]})]}),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:u,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:d,disabled:u,children:[e.jsx(sn,{size:14}),u?"Launching…":c]})]})]})})}function ma(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Gt(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 m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${ma(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",u=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!u&&i.push({key:`custom:${c}`,label:ma(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(x=>x.key===m))return{options:i,selectedKey:m}}return u?{options:i,selectedKey:`saved:${u.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Pr(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function tu({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ue,H,le,Ce;const c=$s(),[u,m]=a.useState(!1),x=(((ue=t.detectedIdes)==null?void 0:ue.length)||0)>0,p=a.useMemo(()=>(t.workspaces||[]).map(me=>({id:me.id,path:me.path,label:me.label})),[t]),h=t.defaultWorkspaceId||null,[g,S]=a.useState(h||((H=p[0])==null?void 0:H.id)||""),[I,d]=a.useState(""),[b,y]=a.useState(""),[l,C]=a.useState([]),[M,N]=a.useState(!1),[f,w]=a.useState(""),[v,k]=a.useState(!1),[$,L]=a.useState(Pr(x,s.length,r.length)),B=a.useRef(null),[A,q]=a.useState(null),R=a.useRef("__home__"),[j,K]=a.useState("__home__"),[Y,_]=a.useState(""),[E,O]=a.useState(""),[U,X]=a.useState(""),[re,ge]=a.useState([]),[W,V]=a.useState(!1),[D,ve]=a.useState(!1),ie=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const J=g==="__custom__"?I.trim():((le=p.find(me=>me.id===g))==null?void 0:le.path)||"",pe=g==="__custom__"&&!!J&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),te=g!=="__custom__"&&((Ce=p.find(me=>me.id===g))==null?void 0:Ce.path)||"",ce=a.useCallback(async me=>{N(!0),w("");try{const _e=await o(me);y(_e.path),d(_e.path),C(_e.directories)}catch(_e){w(_e instanceof Error?_e.message:"Could not load folder")}finally{N(!1)}},[o]),ne=a.useCallback(()=>{var _e,F;S("__custom__"),k(!0);const me=hr(t.platform,[I.trim(),te,(_e=p.find(Q=>Q.id===h))==null?void 0:_e.path,(F=p[0])==null?void 0:F.path]);ce(me)},[I,h,ce,te,t.platform,p]),fe=a.useCallback(me=>{if(me!=null&&me.workspaceId){S(me.workspaceId),d("");return}if(me!=null&&me.workspacePath){S("__custom__"),d(me.workspacePath);return}S(""),d("")},[]),G=a.useCallback(me=>{if(S(me),me==="__custom__"){ne();return}d("")},[ne]),se=a.useCallback(me=>{S("__custom__"),d(me)},[]),ee=a.useCallback((me,_e)=>{B.current=_e,R.current=me.selectedWorkspaceKey||"__home__",K(me.selectedWorkspaceKey||"__home__"),_(me.initialArgs||""),O(me.initialModel||""),X(""),ge([]),q(me),me.providerType&&i&&(V(!0),i(me.providerType).then(F=>ge(F||[])).catch(F=>console.warn("Failed to load saved sessions",F)).finally(()=>V(!1)))},[i]),ye=a.useCallback(()=>{B.current&&(ve(!0),B.current().finally(()=>{B.current=null,ve(!1),q(null)}))},[]),we=a.useCallback(()=>{B.current=null,q(null)},[]),P=a.useCallback(me=>{R.current=me,K(me)},[]);return a.useEffect(()=>{var me;ie.current!==t.id&&(ie.current=t.id,S(h||((me=p[0])==null?void 0:me.id)||"__custom__"),d(""),y(""),C([]),w(""),k(!1),L(Pr(x,s.length,r.length)))},[r.length,s.length,h,x,t.id,p]),a.useEffect(()=>{var me;g!=="__custom__"&&(g&&p.some(_e=>_e.id===g)||S(h||((me=p[0])==null?void 0:me.id)||"__custom__"))},[h,g,p]),a.useEffect(()=>{$==="ide"&&x||$==="cli"&&s.length>0||$==="acp"&&r.length>0||L(Pr(x,s.length,r.length))},[$,r.length,s.length,x]),{showAllRecent:u,setShowAllRecent:m,hasIdeOptions:x,workspaceRows:p,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:l,browseBusy:M,browseError:f,browseDialogOpen:v,activeLauncherKind:$,launchConfirm:A,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:j,launchConfirmArgs:Y,launchConfirmModel:E,launchConfirmResumeId:U,launchConfirmSavedSessions:re,launchConfirmSessionsLoading:W,launchConfirmBusy:D,resolvedWorkspacePath:J,canCreateMissingWorkspace:pe,openBrowseDialog:ne,loadBrowsePath:ce,handleWorkspaceChoiceChange:G,chooseCustomWorkspacePath:se,setCustomWorkspacePath:d,setBrowseDialogOpen:k,setActiveLauncherKind:L,openLaunchConfirm:ee,handleConfirmLaunch:ye,closeLaunchConfirm:we,setWorkspaceSelectionFromOption:fe,setLaunchConfirmWorkspaceKeyAndSync:P,setLaunchConfirmArgs:_,setLaunchConfirmModel:O,setLaunchConfirmResumeId:X}}function su({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:u,isStandalone:m,section:x,showBottomNav:p,onBack:h,onSectionChange:g,onOpenConversation:S,onOpenRecent:I,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:l,onBrowseDirectory:C,onLaunchWorkspaceProvider:M,onListSavedSessions:N}){const f=j=>j==="ide"?"IDE":j==="cli"?"CLI":"ACP",w=r.slice(0,4),v=s.slice(0,3),k=tu({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:u,onBrowseDirectory:C,onListSavedSessions:N}),$=a.useMemo(()=>w.map(j=>({key:`recent-launch:${j.id}`,primary:j.label,secondary:`${f(j.kind)}${j.subtitle?` · ${j.subtitle}`:""}`,onClick:()=>{const{options:K,selectedKey:Y}=Gt({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:j.workspace});k.openLaunchConfirm({title:`Launch ${j.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:K,selectedWorkspaceKey:Y,details:[{label:"Mode",value:f(j.kind)},...j.providerType?[{label:"Provider",value:j.providerType}]:[]]},async()=>{const _=K.find(E=>E.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(_),await I({...j,workspace:(_==null?void 0:_.workspacePath)??null})})}})),[k,I,w]),L=a.useMemo(()=>v.map(j=>({key:`recent-chat:${j.conversation.tabKey}`,primary:Ve(j.conversation),secondary:rl(j.conversation,{timestampLabel:j.timestamp?Ha(j.timestamp):null}),unread:j.unread,onClick:()=>S(j.conversation)})),[S,v]),B=k.showAllRecent?$:$.slice(0,4),A=$.length>0,q=L.length>0,R=m?"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 ${R} 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(Qr,{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:ft(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:[q&&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:L.map(j=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${j.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:j.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:j.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:j.secondary})]},j.key))})]}),A&&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:B.map(j=>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:j.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:j.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:j.secondary})]},j.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:()=>k.setShowAllRecent(j=>!j),children:k.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(k.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:k.workspaceChoice,onChange:j=>k.handleWorkspaceChoiceChange(j.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:k.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[k.workspaceRows.map(j=>e.jsxs("option",{value:j.id,children:[j.id===k.defaultWorkspaceId?"⭐ ":"",pr(j.path,j.label)||j.path]},j.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.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(cs,{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:k.resolvedWorkspacePath||k.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:k.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:()=>{k.resolvedWorkspacePath&&l(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.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:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(j=>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:K,selectedKey:Y}=Gt({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${j.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:K,selectedWorkspaceKey:Y,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:j.name}]},async()=>{const _=K.find(E=>E.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(_),y(j.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:j.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},j.type)):(k.activeLauncherKind==="cli"?n:o).map(j=>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 K=k.activeLauncherKind==="cli"?"cli":"acp",{options:Y,selectedKey:_}=Gt({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${j.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${K.toUpperCase()}`,workspaceOptions:Y,selectedWorkspaceKey:_,details:[{label:"Mode",value:K.toUpperCase()},{label:"Provider",value:j.displayName}],showArgsInput:!0,showModelInput:K==="acp",initialArgs:"",initialModel:"",providerType:j.type},async()=>{const E=Y.find(O=>O.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(E),M(K,j.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[j.icon?`${j.icon} `:"",j.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},j.type))})]}),u.message&&e.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${u.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[u.message,k.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:()=>l(k.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:d,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"})]})]})]})]}),k.browseDialogOpen&&e.jsx(gr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:j=>{k.loadBrowsePath(j)},onConfirm:j=>{k.chooseCustomWorkspacePath(j),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&e.jsx(bn,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.confirmLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.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"}),k.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:k.launchConfirmResumeId,onChange:j=>k.setLaunchConfirmResumeId(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),k.launchConfirmSavedSessions.map(j=>e.jsxs("option",{value:j.providerSessionId,disabled:!j.canResume,children:[j.title||j.providerSessionId," ",j.canResume?"":"(workspace missing)"]},j.providerSessionId))]})]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),p&&e.jsx(Po,{section:x,onSectionChange:g})]})}function Ro(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 ru(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,u,m,x;const o=Ts(n)?"cli":as(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Ts(n)?n.cliName||n.type:as(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:as(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((x=(m=(u=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:x.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function nu(t,s){const r=new Map;for(const n of s){const o=Kt(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,g)=>g.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,u=zr(n),m=o.filter(h=>h.unread||h.requiresAction).length,x=Ro(n),p=[n.platform||"machine",x].filter(Boolean);return{id:n.id,label:ft(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:u,preview:c?nl(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 Gs(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 au({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:u,requestedActiveTabKey:m,onRequestedActiveTabConsumed:x,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:S,setSelectedTabKey:I,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:l,resetMachineAction:C}){const M=a.useRef(null),N=a.useCallback(f=>{if(!(f!=null&&f.sessionId))return;const w=As(f,c),v=Math.max(Date.now(),qt(f),w.lastUpdated||0);Gs("mark_read:start",{tabKey:f.tabKey,sessionId:f.sessionId,displayPrimary:Ve(f),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:qt(f),readAt:v}),u(Kt(f)||f.routeId,"mark_session_seen",{sessionId:f.sessionId,seenAt:v}).then(k=>{Gs("mark_read:result",{tabKey:f.tabKey,sessionId:f.sessionId,result:k})}).catch(k=>{Gs("mark_read:error",{tabKey:f.tabKey,sessionId:f.sessionId,error:k instanceof Error?k.message:String(k)})})},[c,u]);return a.useEffect(()=>{var w;if(!n){d("inbox"),I(((w=t[0])==null?void 0:w.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,N(n))},[t,N,i,n,d,I]),a.useEffect(()=>{if(!m)return;const f=t.find(w=>w.tabKey===m);f&&(I(f.tabKey),d("chat"),x==null||x())},[t,x,m,d,I]),a.useEffect(()=>{if(!p)return;const f=s.find(w=>w.id===p);f&&(b(f.id),C(),y("machines"),l("inbox"),d("machine"),h==null||h())},[s,h,p,C,l,d,y,b]),a.useEffect(()=>{g&&(y(g),d("inbox"),S==null||S())},[S,g,d,y]),a.useEffect(()=>{const f=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);f.length!==0&&Gs("inbox_state",{screen:i,selectedTabKey:o,items:f.map(w=>{const v=As(w.conversation,c);return{liveState:v,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:Ve(w.conversation),serverBucket:v.inboxBucket,computedBucket:w.inboxBucket,serverUnread:v.unread,computedUnread:w.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:qt(w.conversation)}})})},[r,c,i,o]),{markConversationRead:N}}function ou(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function pa(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function iu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function cu({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,u]=a.useState(""),[m,x]=a.useState(null),p=a.useCallback(()=>{i("idle"),u(""),x(null)},[]),h=a.useCallback(async(l,C,M)=>{var N;try{i("loading"),u(`Launching ${C}…`);const f={ideType:C,enableCdp:!0};(N=M==null?void 0:M.workspacePath)!=null&&N.trim()&&(f.workspace=M.workspacePath.trim()),await t(l,"launch_ide",f),i("done"),u(`${C} launch requested`)}catch(f){i("error"),u(f instanceof Error?f.message:"Launch IDE failed"),console.error("Launch IDE failed",f)}},[t]),g=a.useCallback(async(l,C,M)=>{if(C.trim())try{i("loading"),u(M!=null&&M.createIfMissing?"Creating folder…":"Saving workspace…");const N=await t(l,"workspace_add",{path:C.trim(),createIfMissing:(M==null?void 0:M.createIfMissing)===!0});if(N!=null&&N.success){i("done"),u(M!=null&&M.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((N==null?void 0:N.error)||"Could not save workspace")}catch(N){i("error"),u(N instanceof Error?N.message:"Could not save workspace")}},[t]),S=a.useCallback(async l=>{var C,M,N,f,w,v;try{i("loading"),u("Starting daemon upgrade…");const k=await t(l,"daemon_upgrade",{});if((C=k==null?void 0:k.result)!=null&&C.alreadyLatest){i("done"),u(`Already on v${((M=k==null?void 0:k.result)==null?void 0:M.version)||"latest"}.`);return}if((N=k==null?void 0:k.result)!=null&&N.upgraded||(f=k==null?void 0:k.result)!=null&&f.success){i("done"),u(`Upgrade to v${((w=k==null?void 0:k.result)==null?void 0:w.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((v=k==null?void 0:k.result)==null?void 0:v.error)||"Upgrade failed")}catch(k){i("error"),u(k instanceof Error?k.message:"Upgrade failed")}},[t]),I=a.useCallback(async(l,C,M,N)=>{var v,k,$;const f=Date.now(),w={machineId:l,kind:C,providerType:M,workspaceId:(N==null?void 0:N.workspaceId)||null,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:f};try{i("loading"),u(`Launching ${M}…`),x(w);const L={cliType:M};(v=N==null?void 0:N.workspacePath)!=null&&v.trim()?L.dir=N.workspacePath.trim():N!=null&&N.workspaceId&&(L.workspaceId=N.workspaceId),N!=null&&N.resumeSessionId&&(L.resumeSessionId=N.resumeSessionId),(k=N==null?void 0:N.args)!=null&&k.trim()&&(L.cliArgs=N.args.trim().split(/\s+/).filter(Boolean)),($=N==null?void 0:N.model)!=null&&$.trim()&&(L.initialModel=N.model.trim());const B=await t(l,"launch_cli",L),A=(B==null?void 0:B.result)||B,q=(A==null?void 0:A.sessionId)||(A==null?void 0:A.id);if(B!=null&&B.success&&q){x(null),i("done"),u(`${M} launched`),s(`/dashboard?activeTab=${encodeURIComponent(q)}`);return}if(B!=null&&B.success){i("loading"),u(`${M} launch requested — waiting for session…`);return}x(null),i("error"),u((B==null?void 0:B.error)||(A==null?void 0:A.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(L){if(iu(L)){i("loading"),u(`${M} launch requested — waiting for session…`);return}x(null),i("error"),u(L instanceof Error?L.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,t]),d=a.useCallback(async(l,C)=>{try{const M=await t(l,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),N=(M==null?void 0:M.result)??M;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(M){return console.error("Failed to list saved sessions on mobile:",M),[]}},[t]),b=a.useCallback(async(l,C)=>br(t,l,C),[t]);a.useEffect(()=>{var N;if(!m)return;const l=pa(m.workspacePath),C=r.find(f=>{var B,A,q,R;if(!f||f.type==="adhdev-daemon"||ou(f.daemonId||f.id)!==m.machineId||(f.transport==="acp"?"acp":f.transport==="pty"?"cli":null)!==m.kind||String(f.agentType||f.type||"")!==m.providerType)return!1;const $=String(f.providerSessionId||"");if(m.resumeSessionId&&$)return $===m.resumeSessionId;if(l){const j=pa(f.workspace||f.runtimeWorkspaceLabel);return j?j===l:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((R=(q=(A=(B=f.activeChat)==null?void 0:B.messages)==null?void 0:A.at)==null?void 0:q.call(A,-1))==null?void 0:R.timestamp)||0)>=m.startedAt-5e3});if(!C)return;const M=typeof C.sessionId=="string"&&C.sessionId?C.sessionId:typeof C.instanceId=="string"&&C.instanceId?C.instanceId:(N=n.find(f=>f.routeId===C.id))==null?void 0:N.sessionId;M&&(x(null),i("done"),u(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(M)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const l=window.setTimeout(()=>{x(C=>!C||C.startedAt!==m.startedAt?C:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[m]);const y=a.useCallback(async(l,C)=>{if(C.kind==="ide"&&C.providerType){await h(l,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await I(l,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:I,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function lu({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:u,setSection:m,setMachineBackTarget:x}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=a.useCallback(y=>{const l=t.find(C=>C.routeId===y.routeId&&C.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[t,n,c,i]),g=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((y,l="inbox")=>{u(y),o(),m("machines"),x(l),c("machine")},[o,x,c,m,u]),I=a.useCallback(y=>{const l=Kt(y);l&&S(l,"chat")},[S]),d=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:h,backFromConversation:g,openMachine:S,openConversationMachine:I,backFromMachine:d,changeMachineSection:b}}function du(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function uu(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 mu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,userName:m,requestedActiveTabKey:x,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:l,isConnected:C,onShowHiddenConversation:M,onShowAllHiddenConversations:N,onHideConversation:f,onOpenNewSession:w}){const[v,k]=a.useState(()=>{var H;return((H=t[0])==null?void 0:H.tabKey)||null}),[$,L]=a.useState(()=>t[0]?"chat":"inbox"),[B,A]=a.useState("chats"),[q,R]=a.useState(null),[j,K]=a.useState("inbox"),Y=ds(),_="0.8.41",E=a.useMemo(()=>t.find(H=>H.tabKey===v)||t[0]||null,[t,v]),O=a.useMemo(()=>E?r.find(H=>H.id===E.routeId):void 0,[r,E]),U=a.useMemo(()=>!E||Oe(E)||!ze(E)?null:ls(E),[E]),X=a.useMemo(()=>r.filter(H=>H.type==="adhdev-daemon").sort(nn),[r]),re=a.useMemo(()=>X.find(H=>H.id===q)||null,[X,q]),ge=a.useMemo(()=>Es(r),[r]),W=xr({sendDaemonCommand:o,activeConv:E||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:u}),V=cu({sendDaemonCommand:o,navigate:Y,ides:r,conversations:t}),D=a.useMemo(()=>t.map(H=>{const le=$==="chat"&&(E==null?void 0:E.tabKey)===H.tabKey,Ce=_s(H,ge,{hideOpenTaskCompleteUnread:!0,isOpenConversation:le}),me=qt(H),_e=so(H);return{conversation:H,timestamp:me,preview:_e,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[t,ge,$,E]),{markConversationRead:ve}=au({conversations:t,machineEntries:X,items:D,selectedConversation:E,selectedTabKey:v,screen:$,liveSessionInboxState:ge,sendDaemonCommand:o,requestedActiveTabKey:x,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,setSelectedTabKey:k,setScreen:L,setSelectedMachineId:R,setSection:A,setMachineBackTarget:K,resetMachineAction:V.resetMachineAction}),ie=lu({conversations:t,selectedConversation:E,machineBackTarget:j,markConversationRead:ve,resetMachineAction:V.resetMachineAction,setSelectedTabKey:k,setScreen:L,setSelectedMachineId:R,setSection:A,setMachineBackTarget:K}),J=a.useMemo(()=>D.filter(H=>H.requiresAction),[D]),pe=a.useMemo(()=>D.filter(H=>H.unread&&!H.requiresAction),[D]),te=a.useMemo(()=>D.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking),[D]),ce=a.useMemo(()=>D.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking),[D]),ne=a.useMemo(()=>re?D.filter(H=>Kt(H.conversation)===re.id):[],[D,re]),fe=a.useMemo(()=>ru(re,r),[r,re]),G=(re==null?void 0:re.version)||null,se=!!re&&!!G&&!0&&G!==_,ee=a.useMemo(()=>(re==null?void 0:re.availableProviders)||[],[re]),ye=a.useMemo(()=>ee.filter(H=>H.category==="cli"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ee]),we=a.useMemo(()=>ee.filter(H=>H.category==="acp"&&H.installed!==!1).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[ee]),P=a.useMemo(()=>nu(X,D),[D,X]),ue=a.useCallback(async H=>{re&&await V.handleOpenRecent(re.id,H)},[V,re]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&E?e.jsx(Xd,{selectedConversation:E,isAcp:Oe(E),isStandalone:u,selectedIdeEntry:O,actionLogs:n,userName:m,isSendingChat:W.isSendingChat,isFocusingAgent:W.isFocusingAgent,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onHideConversation:f,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:U,onSetCliViewMode:async H=>{if(E&&U!==H)try{await o(Kt(E)||E.routeId,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:pt(E),mode:H})}catch(le){uu(le)?console.warn("Skipped CLI view mode switch:",le instanceof Error?le.message:String(le)):console.error("Failed to switch CLI view mode:",le)}},handleSendChat:W.handleSendChat,handleFocusAgent:W.handleFocusAgent}):$==="machine"&&re?e.jsx(su,{selectedMachineEntry:re,selectedMachineConversations:ne,selectedMachineRecentLaunches:fe,cliProviders:ye,acpProviders:we,selectedMachineNeedsUpgrade:se,appVersion:_,machineAction:V.machineAction,isStandalone:u,section:B,showBottomNav:j==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>Y(`/machines/${re.id}`),onMachineUpgrade:()=>V.handleMachineUpgrade(re.id),onLaunchDetectedIde:(H,le)=>V.handleLaunchDetectedIde(re.id,H,le),onAddWorkspace:(H,le)=>V.handleAddWorkspace(re.id,H,le),onBrowseDirectory:H=>V.handleBrowseDirectory(re.id,H),onLaunchWorkspaceProvider:(H,le,Ce)=>V.handleLaunchWorkspaceProvider(re.id,H,le,Ce),onListSavedSessions:H=>V.handleListSavedSessions(re.id,H)}):e.jsx(Zd,{section:B,attentionItems:J,unreadItems:pe,workingItems:te,completedItems:ce,hiddenConversations:s,machineCards:P,getAvatarText:du,onOpenConversation:ie.openConversation,onShowConversation:M,onShowAllHidden:N,onOpenNewSession:w,onOpenMachine:ie.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:A,wsStatus:l,isConnected:C,isStandalone:u})})}function Rr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function pu({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[u,m]=a.useState(!1),[x,p]=a.useState(null),h=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),S=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Rr(s,r)){p("merge");return}const y=b.currentTarget.getBoundingClientRect(),l=b.clientX-y.left,C=y.width/3;l<C?p("split-left"):l>C*2?p("split-right"):p("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),d=a.useCallback(b=>{c.current=0,m(!1);const y=b.dataTransfer.getData("text/tab-key"),l=y?t.some(M=>M.tabKey===y):!1,C=x;if(p(null),i(),!!y){if(b.preventDefault(),C==="split-left"&&Rr(s,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&Rr(s,r)){r==null||r(y,"split-right");return}if(l){o(y);return}n==null||n(y)}},[t,x,s,r,n,o,i]);return{dragOver:u,dropAction:x,resetDragState:h,handleDragEnter:g,handleDragOver:S,handleDragLeave:I,handleDrop:d}}function fu(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 xu({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[u,m]=a.useState(r??[]),[x,p]=a.useState(null),h=a.useRef(null),g=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(()=>{m(w=>{const v=fu(w,t);return v.length===w.length&&v.every((k,$)=>k===w[$])?w:v})},[t]);const d=a.useMemo(()=>{const w=x??u;if(w.length===0)return t;const v=new Map(w.map((k,$)=>[k,$]));return[...t].sort((k,$)=>{const L=v.get(k.tabKey)??999,B=v.get($.tabKey)??999;return L-B})},[t,x,u]);a.useEffect(()=>{var v,k;if(d.length===0){i!==null&&(c(null),(v=S.current)==null||v.call(S,null));return}if(i&&d.some($=>$.tabKey===i))return;const w=d[0].tabKey;w!==i&&(c(w),(k=S.current)==null||k.call(S,w))},[d,i]);const b=a.useMemo(()=>d.find(w=>w.tabKey===i),[d,i]),y=a.useCallback(w=>{var v;c(w),(v=S.current)==null||v.call(S,w)},[]),l=a.useCallback((w,v,k)=>{m($=>{var q;const L=$.filter(R=>R!==w),B=L.indexOf(v);if(B<0)return $;const A=k==="left"?B:B+1;return L.splice(A,0,w),(q=I.current)==null||q.call(I,L),L}),p(null)},[]),C=a.useCallback((w,v,k)=>{const L=(u.length>0?u:t.map(q=>q.tabKey)).filter(q=>q!==w),B=L.indexOf(v);if(B<0)return;const A=k==="left"?B:B+1;L.splice(A,0,w),h.current=L,p(L)},[u,t]),M=a.useCallback(()=>{var v;const w=h.current;w&&(m(w),(v=I.current)==null||v.call(I,w))},[]),N=a.useCallback(()=>{h.current=null,p(null)},[]),f=a.useCallback(w=>{m(v=>{var $;const k=v.filter(L=>L!==w);return k.push(w),($=I.current)==null||$.call(I,k),k})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:l,updatePreviewOrder:C,commitPreviewOrder:M,clearPreviewOrder:N,moveTabToEnd:f,setDraggingTabKey:w=>{g.current=w}}}function hu({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 gn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,u=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",m=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:u}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&e.jsx(To,{}),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(Ka,{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 Lo="adhdev-tab-shortcuts";function bu(){try{return JSON.parse(localStorage.getItem(Lo)||"{}")}catch{return{}}}function Eo({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>bu()),[u,m]=a.useState(null),x=a.useCallback(h=>{const g=[];return h.metaKey&&g.push(o?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(o?"⌥":"Alt"),h.shiftKey&&g.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[o]),p=a.useCallback(h=>{c(h);try{localStorage.setItem(Lo,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!u)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){m(null);return}const S=x(g);if(!S)return;const I={...i};for(const[d,b]of Object.entries(I))b===S&&delete I[d];I[u]=S,p(I),m(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,u,i,p,x]),a.useEffect(()=>{if(!t)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[S,I]of Object.entries(i))if(s.includes(S)&&x(g)===I){g.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:u,setShortcutListening:m,saveShortcuts:p}}const gu=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:u,onFocus:m,onSelectTab:x,onConversationActivated:p,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:S,onClearPreviewOrder:I,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:l,longPressTimer:C,isGroupActive:M}){const N=ms(s),f=N.isGenerating?"agent-tab-generating":N.isWaiting?"agent-tab-waiting":"",w=N.isReconnecting,v=a.useCallback(K=>{u.current=s.tabKey,b(s.tabKey),K.dataTransfer.setData("text/tab-key",s.tabKey),K.dataTransfer.effectAllowed="move"},[s.tabKey,u,b]),k=a.useCallback(()=>{u.current=null,b(null),S(),I(),d()},[u,b,S,I,d]),$=a.useCallback(K=>{const Y=u.current;if(!(!Y||Y===s.tabKey)&&K.dataTransfer.types.includes("text/tab-key")){K.preventDefault(),K.stopPropagation();const _=K.currentTarget.getBoundingClientRect(),E=K.clientX<_.left+_.width/2?"left":"right";h(Y,s.tabKey,E)}},[s.tabKey,u,h]),L=a.useCallback(K=>{K.preventDefault(),K.stopPropagation();const Y=K.dataTransfer.getData("text/tab-key");if(Y&&Y!==s.tabKey){const _=K.currentTarget.getBoundingClientRect(),E=K.clientX<_.left+_.width/2?"left":"right";c.includes(Y)?g(Y,s.tabKey,E):y&&y(Y)}I()},[s.tabKey,c,g,y,I]),B=a.useCallback(K=>{K.stopPropagation(),m(),x(s.tabKey),p(s)},[s,p,m,x]),A=a.useCallback(K=>{K.preventDefault(),l(K.clientX,K.clientY,s.tabKey)},[s.tabKey,l]),q=a.useCallback(K=>{const Y=K.touches[0];C.current=setTimeout(()=>{l(Y.clientX,Y.clientY,s.tabKey)},600)},[s.tabKey,C,l]),R=a.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),j=["adhdev-dockview-tab",f,r&&"is-active",M&&"is-group-active",w&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:j,draggable:!0,onDragStart:v,onDragEnd:k,onDragOver:$,onDrop:L,onClick:B,onContextMenu:A,onTouchStart:q,onTouchEnd:R,onTouchMove:R,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:N.isGenerating?e.jsx("div",{className:"tab-spinner"}):N.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):N.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:Ve(s),children:Ve(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(s)}):N.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[os(s),e.jsx("span",{className:"connecting-dots"})]}):os(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 yu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:u,onPreviewReorder:m,onReorderTab:x,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:S,onReceiveTab:I,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[l,C]=a.useState(null),M=a.useRef(null),N=a.useRef(null),f=a.useMemo(()=>t.map(A=>A.tabKey),[t]);Ls("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:w,tabShortcuts:v,shortcutListening:k,setShortcutListening:$,saveShortcuts:L}=Eo({enabled:y,sortedTabKeys:t.map(A=>A.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const A=q=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(q.target)||C(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[l]),a.useEffect(()=>{const A=N.current;if(!A)return;const q=R=>{Math.abs(R.deltaY)>Math.abs(R.deltaX)&&(R.preventDefault(),A.scrollLeft+=R.deltaY)};return A.addEventListener("wheel",q,{passive:!1}),()=>A.removeEventListener("wheel",q)},[]);const B=a.useCallback((A,q,R)=>{C({x:A,y:q,tabKey:R})},[]);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:N,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(A=>e.jsx(gu,{conv:A,isActive:s===A.tabKey,isDraggedTab:o.current===A.tabKey,isTaskCompleteUnread:n.has(A.tabKey),shortcut:y?v[A.tabKey]:void 0,conversationKeys:f,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:u,onPreviewReorder:m,onReorderTab:x,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:S,onReceiveTab:I,onOpenContextMenu:B,longPressTimer:M,isGroupActive:b},A.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&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:l.x,top:l.y},children:[y&&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:A=>{A.stopPropagation(),$(l.tabKey),C(null)},children:["⌨ ",v[l.tabKey]?`Change shortcut (${v[l.tabKey]})`:"Set shortcut"]}),v[l.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 A={...v};delete A[l.tabKey],L(A),C(null)},children:"✕ Remove shortcut"})]}),d&&e.jsxs(e.Fragment,{children:[y&&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:()=>{d(l.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&k&&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:A=>A.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. ",w?"⌘+1":"Ctrl+1",", ",w?"⌥+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 vu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,hasRegisteredMachines:m,userName:x,groupIndex:p,onFocus:h,isSplitMode:g,numGroups:S,onMoveTab:I,onReceiveTab:d,style:b,detectedIdes:y,handleLaunchIde:l,onActiveTabChange:C,initialActiveTabId:M,initialTabOrder:N,onTabOrderChange:f,onHideTab:w,isFocused:v,allowTabShortcuts:k=!0}){const{sendCommand:$}=bt(),L=a.useRef(null),{activeTabId:B,activeConv:A,sortedConversations:q,draggingTabRef:R,selectTab:j,handleTabReorder:K,updatePreviewOrder:Y,commitPreviewOrder:_,clearPreviewOrder:E,moveTabToEnd:O,setDraggingTabKey:U}=xu({conversations:t,initialActiveTabId:M,initialTabOrder:N,onActiveTabChange:C,onTabOrderChange:f}),X=xr({sendDaemonCommand:o,activeConv:A,setLocalUserMessages:i,setActionLogs:c,isStandalone:u}),{dragOver:re,dropAction:ge,resetDragState:W,handleDragEnter:V,handleDragOver:D,handleDragLeave:ve,handleDrop:ie}=pu({conversations:t,numGroups:S,onMoveTab:I,onReceiveTab:d,onOwnTabDrop:O,onClearPreviewOrder:E}),J=A&&!Oe(A)&&ls(A)==="terminal",pe=a.useMemo(()=>A?s.find(G=>G.id===A.routeId):void 0,[s,A]),te=a.useMemo(()=>A?n.filter(G=>G.routeId===A.tabKey):[],[n,A]),ce=a.useMemo(()=>Es(s),[s]),ne=a.useMemo(()=>new Set(q.filter(G=>gc(G,ce,{isOpenConversation:G.tabKey===B})).map(G=>G.tabKey)),[B,ce,q]);Ls("PaneGroup",{groupIndex:p,conversationCount:t.length,activeTabId:B,dragOver:re});const fe=a.useCallback(G=>{G.streamSource==="agent-stream"&&G.agentType&&$(G.routeId,"focus_session",{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.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:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(yu,{conversations:q,activeTabId:B,groupIndex:p,numGroups:S,unreadTabKeys:ne,draggingTabRef:R,onFocus:h,onSelectTab:j,onConversationActivated:fe,onPreviewReorder:Y,onReorderTab:K,onCommitPreviewOrder:_,onClearPreviewOrder:E,onDragStateReset:W,onDragTabKeyChange:U,onMoveTab:I,onReceiveTab:d,onHideTab:w,isGroupActive:v??!1,allowTabShortcuts:k}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:V,onDragOver:D,onDragLeave:ve,onDrop:ie,children:[re&&e.jsx(hu,{dropAction:ge,canSplit:!!(S<4&&I)}),A?e.jsx(hn,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!J,ideEntry:pe,terminalRef:L,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,handleSendChat:X.handleSendChat,isSendingChat:X.isSendingChat,handleFocusAgent:X.handleFocusAgent,isFocusingAgent:X.isFocusingAgent,actionLogs:te,userName:x,isInputActive:!g||!!v}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(gn,{conversationsCount:t.length,isSplitMode:g,isStandalone:u,hasRegisteredMachines:m,detectedIdes:y,handleLaunchIde:l})})]})]})}function wu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:u,sendDaemonCommand:m,setLocalUserMessages:x,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:S,focusedGroup:I,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:l,handleResizeStart:C,detectedIdes:M,handleLaunchIde:N,groupActiveTabIds:f,setGroupActiveTabIds:w,groupTabOrders:v,setGroupTabOrders:k,toggleHiddenTab:$,allowTabShortcuts:L=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((B,A)=>{const q=s&&n.length===r?`${n[A]}%`:void 0;return e.jsxs(Ye.Fragment,{children:[s&&A>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:R=>C(A-1,R),onDoubleClick:()=>l(A),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(vu,{style:s?{flexBasis:q??`${100/r}%`,flexGrow:q?0:1,flexShrink:q?0:1}:void 0,conversations:B,clearedTabs:i,ides:c,actionLogs:u,sendDaemonCommand:m,setLocalUserMessages:x,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:S,groupIndex:A,isFocused:s&&I===A,onFocus:()=>d(A),isSplitMode:s,numGroups:r,onMoveTab:(R,j)=>{j==="left"&&A>0?b(R,A-1):j==="right"&&A<r-1?b(R,A+1):j==="split-left"&&r<4?y(R,A,"left"):j==="split-right"&&r<4&&y(R,A,"right")},onReceiveTab:R=>b(R,A),detectedIdes:A===0?M:void 0,handleLaunchIde:A===0?N:void 0,onActiveTabChange:R=>w(j=>(j[A]??null)===(R??null)?j:{...j,[A]:R}),initialActiveTabId:f[A],initialTabOrder:v[A],onTabOrderChange:R=>k(j=>{const K=j[A]||[];return K.length===R.length&&K.every((Y,_)=>Y===R[_])?j:{...j,[A]:R}}),onHideTab:$,allowTabShortcuts:L})]},A)})})}function Do({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,u]=a.useState(null);a.useEffect(()=>t?Ge.onScreenshot("ide-page",(p,h)=>{if(p!==t)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return t?((p=Ge.onStatus)==null?void 0:p.call(Ge,(h,g)=>{h===t&&g!=null&&g.screenshotUsage&&u(g.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const x=t?Ge.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 m=a.useCallback(async(x,p)=>{const h=t?Ge.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(x,p,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const $o=a.createContext(null);function yr(){const t=a.useContext($o);if(!t)throw new Error("DashboardDockviewContext missing");return t}function tr(t){return Ve(t)||t.tabKey}function ju(t){return`remote:${t}`}function Rs(t){return t.startsWith("remote:")}function ku(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 Nu(t,s,r){var u;const n=[s];let o;for(const m of n){let x;for(const p of m){const h=t.addPanel({id:p.tabKey,component:"conversation",title:tr(p),params:{kind:"conversation",tabKey:p.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??((u=s[0])==null?void 0:u.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function fa(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Rs(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!==tr(n)&&o.api.setTitle(tr(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:tr(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 xa(t,s,r){var m,x;const n=r?ju(r):null;for(const p of[...t.panels])Rs(p.id)&&(!n||p.id!==n)&&t.removePanel(p);if(!r||!n)return;const o=Et(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=il(o);if(i){i.title!==c&&i.api.setTitle(c);return}const u=(o==null?void 0:o.tabKey)??((m=t.activePanel)==null?void 0:m.id)??((x=t.panels.find(p=>!Rs(p.id)))==null?void 0:x.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...u?{position:{referencePanel:u,direction:"right"},inactive:!0}:{}})}function Su({params:t,api:s}){var h;const r=yr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),u=xr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const g=[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 g)S.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),x=a.useMemo(()=>c?r.actionLogs.filter(g=>g.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(gn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const p=!Oe(c)&&ls(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(hn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,terminalRef:n,handleModalButton:u.handleModalButton,handleRelaunch:u.handleRelaunch,handleSendChat:u.handleSendChat,isSendingChat:u.isSendingChat,handleFocusAgent:u.handleFocusAgent,isFocusingAgent:u.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 Cu({params:t}){var m;const s=yr(),r=a.useMemo(()=>Et([...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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:u}=Do({doId:o,targetSessionId:r?cn(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(Ua,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:u})}):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 Iu(){const t=yr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(gn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function Mu(t){var S,I;ku(t);const s=yr(),r=a.useCallback(d=>{"button"in d&&d.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const d=Et([...s.conversationsByTabKey.values()],t.params.routeId),b=((S=t.api.group.activePanel)==null?void 0:S.id)===t.api.id,y=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(d==null?void 0:d.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:d!=null&&d.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:d.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=_s(n,s.liveSessionInboxState,{isOpenConversation:o}),u=c.isReconnecting,m=c.isConnecting,x=c.isGenerating,p=c.isWaiting,h=c.unread,g=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${u?" is-reconnecting":""}`,title:Ve(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey})},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"}):p?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):u?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?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:Ve(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(n)}):m?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:os(n)}):e.jsx("span",{children:os(n)})})]}),g&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function Au({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:x,userName:p,detectedIdes:h,handleLaunchIde:g,toggleHiddenTab:S,registerActionHandlers:I,onActiveTabChange:d,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:l,scrollToBottomRequest:C}){const{theme:M}=pn(),{sendCommand:N}=bt(),f=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),k=a.useRef(!1),$=a.useRef(!1),L=a.useRef(null),[B,A]=a.useState(null),[q,R]=a.useState(!1),[j,K]=a.useState(!1),Y=a.useRef(null),_=a.useMemo(()=>Mo(typeof window<"u"?window.innerWidth:1280),[]),E=a.useMemo(()=>new Map(t.map(F=>[F.tabKey,F])),[t]),O=a.useMemo(()=>Es(r),[r]),U=a.useCallback(()=>{var F;(F=f.current)==null||F.focus()},[]),X=a.useCallback(F=>{const Q=document,ae=F.document;for(const Le of Q.querySelectorAll('link[rel="stylesheet"]')){const Ee=ae.createElement("link");Ee.rel="stylesheet",Ee.href=Le.href,Le.crossOrigin&&(Ee.crossOrigin=Le.crossOrigin),ae.head.appendChild(Ee)}for(const Le of Q.querySelectorAll("style")){const Ee=ae.createElement("style");Ee.textContent=Le.textContent,ae.head.appendChild(Ee)}const de=[];for(const Le of Q.styleSheets)try{for(const Ee of Le.cssRules)Ee instanceof CSSStyleRule&&(Ee.selectorText===":root"||Ee.selectorText==="html")&&de.push(Ee.cssText)}catch{}if(de.length>0){const Le=ae.createElement("style");Le.textContent=de.join(`
41
- `),ae.head.appendChild(Le)}const Se=Q.documentElement.getAttribute("data-theme");Se&&ae.documentElement.setAttribute("data-theme",Se),ae.documentElement.style.colorScheme=Se==="light"?"light":"dark",ae.body.className=Q.body.className;const Me=Q.documentElement.getAttribute("style");Me&&ae.documentElement.setAttribute("style",Me)},[]),re=a.useCallback(()=>{var Q;const F=f.current;if(F)for(const ae of F.groups)try{const de=(Q=ae.element)==null?void 0:Q.ownerDocument;if(!de||de===document)continue;const Se=document.documentElement.getAttribute("data-theme");Se&&de.documentElement.setAttribute("data-theme",Se),de.documentElement.style.colorScheme=Se==="light"?"light":"dark",de.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me?de.documentElement.setAttribute("style",Me):de.documentElement.removeAttribute("style")}catch{}},[]),ge=a.useCallback(F=>{const Q=f.current;if(!Q)return;const ae=Q.getPanel(F);ae&&Q.addPopoutGroup(ae,{popoutUrl:"/popout.html",onDidOpen:({window:de})=>{X(de);const Se=E.get(F);Se?de.document.title=`${Ve(Se)} — ADHDev`:de.document.title="ADHDev — Popout"}})},[E,X]),W=a.useCallback(F=>{const Q=f.current;if(!Q)return;const ae=Q.getPanel(F);if(!ae)return;const de=Q.groups.filter(Se=>{var Me;try{return((Me=Se.element)==null?void 0:Me.ownerDocument)===document}catch{return!0}});de.length>0?ae.api.moveTo({group:de[0],position:"center"}):ae.api.moveTo({position:"center"}),ae.api.setActive()},[]),V=a.useCallback(F=>{const Q=f.current;if(!Q)return!1;const ae=Q.getPanel(F);if(!ae)return!1;try{const de=ae.group.element;return(de==null?void 0:de.ownerDocument)!==document}catch{return!1}},[]),D=a.useCallback(F=>{const Q=f.current;if(!Q)return;const ae=Q.getPanel(F);ae&&(ae.group.model.openPanel(ae),ae.api.setActive())},[]),ve=a.useCallback(F=>{const Q=f.current,ae=Q==null?void 0:Q.activePanel,de=(Q==null?void 0:Q.activeGroup)||(ae==null?void 0:ae.group);if(!Q||!ae||!de)return;const Se=de.panels||[];if(Se.length<=1)return;const Me=Se.findIndex(Fe=>Fe.id===ae.id);if(Me<0)return;const Le=(Me+F+Se.length)%Se.length,Ee=Se[Le];Ee&&(Ee.group.model.openPanel(Ee),Ee.api.setActive())},[]),ie=a.useCallback(F=>{var it;const Q=f.current,ae=(Q==null?void 0:Q.activeGroup)||((it=Q==null?void 0:Q.activePanel)==null?void 0:it.group);if(!Q||!ae)return;const de=Q.groups||[],Se=de.find(z=>z.id===ae.id);if(!Se)return;const Me=Se.element.getBoundingClientRect(),Le=Me.left+Me.width/2,Ee=Me.top+Me.height/2,Fe=(z,he,Ae,Re)=>Math.max(0,Math.min(he,Re)-Math.max(z,Ae)),We=z=>{const he=z.element.getBoundingClientRect(),Ae=he.left+he.width/2,Re=he.top+he.height/2;let tt=0,Ze=0,dt=0,st=!1;if(F==="left"?(st=Ae<Le,tt=Math.max(0,Me.left-he.right),Ze=Math.abs(Re-Ee),dt=Fe(Me.top,Me.bottom,he.top,he.bottom)):F==="right"?(st=Ae>Le,tt=Math.max(0,he.left-Me.right),Ze=Math.abs(Re-Ee),dt=Fe(Me.top,Me.bottom,he.top,he.bottom)):F==="above"?(st=Re<Ee,tt=Math.max(0,Me.top-he.bottom),Ze=Math.abs(Ae-Le),dt=Fe(Me.left,Me.right,he.left,he.right)):(st=Re>Ee,tt=Math.max(0,he.top-Me.bottom),Ze=Math.abs(Ae-Le),dt=Fe(Me.left,Me.right,he.left,he.right)),!st)return Number.POSITIVE_INFINITY;const wt=dt>0?0:120;return tt*3+Ze+wt};let Je=null,lt=Number.POSITIVE_INFINITY;for(const z of de){if(z.id===Se.id)continue;const he=We(z);Number.isFinite(he)&&(he>=lt||(lt=he,Je=z))}return Je||void 0},[]),J=a.useCallback(F=>{const Q=ie(F);if(!Q)return;const ae=Q.activePanel||Q.panels[0];ae&&(Q.model.openPanel(ae),ae.api.setActive())},[ie]),pe=a.useCallback((F,Q)=>{const ae=f.current,de=ae==null?void 0:ae.activePanel,Se=(ae==null?void 0:ae.activeGroup)||(de==null?void 0:de.group);if(!ae||!de||!Se)return;let Me=ie(F);!Me&&(Q!=null&&Q.createGroupIfMissing)&&(Me=ae.addGroup({referenceGroup:Se,direction:F})),Me&&(de.api.moveTo({group:Me,position:"center"}),de.group.model.openPanel(de),de.api.setActive())},[ie]),{isMac:te,tabShortcuts:ce,shortcutListening:ne,setShortcutListening:fe,saveShortcuts:G}=Eo({sortedTabKeys:t.map(F=>F.tabKey),onFocus:U,onSelectTab:D}),se=a.useCallback(()=>{var ae;const F=f.current;if(!F)return;const Q=F.activePanel;if(Q){if(Rs(Q.id)){const de=((ae=Q.params)==null?void 0:ae.routeId)||Q.id.slice(7),Se=Et(t,de);Se!=null&&Se.tabKey&&fe(Se.tabKey);return}E.has(Q.id)&&fe(Q.id)}},[E,fe,t]);a.useEffect(()=>(I==null||I({setShortcutForActiveTab:se,activatePreviousTabInGroup:()=>ve(-1),activateNextTabInGroup:()=>ve(1),splitActiveTabRight:()=>pe("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>pe("below",{createGroupIfMissing:!0}),focusLeftPane:()=>J("left"),focusRightPane:()=>J("right"),focusUpPane:()=>J("above"),focusDownPane:()=>J("below"),moveActiveTabToLeftPane:()=>pe("left"),moveActiveTabToRightPane:()=>pe("right"),moveActiveTabToUpPane:()=>pe("above"),moveActiveTabToDownPane:()=>pe("below")}),()=>I==null?void 0:I(null)),[ve,J,pe,I,se]),a.useEffect(()=>{if(!B)return;const F=Q=>{const ae=document.querySelector("[data-dockview-tab-context-menu]");ae&&ae.contains(Q.target)||A(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[B]);const ee=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:E,detectedIdes:h,handleLaunchIde:g,ides:r,isStandalone:u,hasRegisteredMachines:m,liveSessionInboxState:O,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:S,userName:p,scrollToBottomRequest:C,tabShortcuts:ce,openTabContextMenu:({x:F,y:Q,tabKey:ae})=>A({x:F,y:Q,tabKey:ae}),popoutTab:ge,moveTabBackToMain:W,isTabInPopout:V}),[n,s,E,h,g,r,u,m,O,o,c,i,S,p,C,ce,ge,W,V]),ye=a.useCallback(F=>{if(!F)return!1;const Q=f.current;if(!Q)return!1;const ae=Q.getPanel(F);return ae?(ae.group.model.openPanel(ae),ae.api.setActive(),l==null||l(),!0):!1},[l]),we=a.useCallback(()=>{if($.current)return!1;const F=ye(L.current);return F&&($.current=!0),F},[ye]),P=a.useCallback(()=>{var Q;const F=f.current;F&&Bd(_,{activeTabId:((Q=F.activePanel)==null?void 0:Q.id)??null,layout:F.toJSON()})},[_]),ue=a.useCallback(()=>{const F=w.current;if(!F)return;const Q=F.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const ae of Q)ae.setAttribute("data-adhdev-force-hidden","true")},[]),H=a.useCallback(()=>{const F=w.current;if(!F)return;const Q=F.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const ae of Q)ae.removeAttribute("data-adhdev-force-hidden")},[]),le=a.useCallback(()=>{const F=w.current;if(!F)return;const Q=F.querySelectorAll(".dv-drop-target-container");for(const Se of Q)Se.remove();const ae=F.querySelectorAll(".dv-drop-target-dropzone");for(const Se of ae)Se.remove();const de=F.querySelectorAll(".dv-drop-target");for(const Se of de)Se.classList.remove("dv-drop-target")},[]),Ce=a.useCallback(()=>{R(!1),K(!1),H(),ue(),le(),!(typeof window>"u")&&(Y.current!=null&&window.clearTimeout(Y.current),window.requestAnimationFrame(()=>{ue(),le()}),Y.current=window.setTimeout(()=>{ue(),le(),Y.current=null},80))},[H,ue,le]),me=a.useCallback(F=>{var ae;f.current=F.api;const Q=$d(_);L.current=(Q==null?void 0:Q.activeTabId)??null,Q!=null&&Q.layout&&F.api.fromJSON(Q.layout,{reuseExistingPanels:!1}),k.current=!!(Q!=null&&Q.layout)&&!x&&t.length===0,k.current||(fa(F.api,t),xa(F.api,t,y)),F.api.totalPanels===0&&t.length>0?Nu(F.api,t,b):!k.current&&!ye(b)&&we(),v.current=!0,F.api.onDidActivePanelChange(de=>{var Me;if(L.current=(de==null?void 0:de.id)??null,$.current=!0,de&&Rs(de.id)){const Le=((Me=de.params)==null?void 0:Me.routeId)||de.id.slice(7),Ee=Et(t,Le);d((Ee==null?void 0:Ee.tabKey)??null),P();return}if(d((de==null?void 0:de.id)??null),P(),!de)return;const Se=E.get(de.id);(Se==null?void 0:Se.streamSource)==="agent-stream"&&Se.agentType&&N(Se.routeId,"focus_session",{agentType:Se.agentType,...Se.sessionId&&{targetSessionId:Se.sessionId}}).catch(()=>{})}),F.api.onDidLayoutChange(()=>{P()}),F.api.onWillDragPanel(()=>{R(!0),K(!1),ue()}),F.api.onWillDragGroup(()=>{R(!0),K(!1),ue()}),F.api.onWillShowOverlay(()=>{H(),K(!0)}),F.api.onDidMovePanel(Ce),F.api.onDidDrop(Ce),F.api.onDidAddGroup(de=>{requestAnimationFrame(()=>{var Se;try{const Me=(Se=de.element)==null?void 0:Se.ownerDocument;if(!Me||Me===document)return;const Le=document.documentElement.getAttribute("data-theme");Le&&Me.documentElement.setAttribute("data-theme",Le),Me.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&Me.documentElement.setAttribute("style",Ee)}catch{}})}),d(((ae=F.api.activePanel)==null?void 0:ae.id)??null)},[ye,Ce,H,E,x,_,ue,le,d,P,b,y,N,t]);a.useEffect(()=>{const F=f.current;if(!F||!v.current||k.current&&!x||(k.current&&(k.current=!1),fa(F,t),xa(F,t,y),b&&ye(b)))return;!F.activePanel&&F.panels[0]&&(F.panels[0].group.model.openPanel(F.panels[0]),F.panels[0].api.setActive()),!!(F.activePanel&&F.getPanel(F.activePanel.id))||we()},[ye,we,x,b,y,t]),a.useEffect(()=>{v.current&&ye(b)},[ye,b]),a.useEffect(()=>{if(!q||typeof window>"u")return;const F=()=>Ce();return window.addEventListener("pointerup",F),window.addEventListener("mouseup",F),window.addEventListener("dragend",F),()=>{window.removeEventListener("pointerup",F),window.removeEventListener("mouseup",F),window.removeEventListener("dragend",F)}},[Ce,q]),a.useEffect(()=>()=>{typeof window>"u"||Y.current!=null&&window.clearTimeout(Y.current)},[]),a.useEffect(()=>{const F=Q=>{const ae=Q.target;if(!ae)return;const de=ae.querySelector("[data-tab-key]")||ae.closest("[data-tab-key]");if(de){const Se=de.getAttribute("data-tab-key");Se&&Q.dataTransfer&&Q.dataTransfer.setData("text/tab-key",Se)}};return window.addEventListener("dragstart",F),()=>window.removeEventListener("dragstart",F)},[]),a.useEffect(()=>{re()},[re,M]);const _e=M==="light"?vi:wi;return e.jsxs($o.Provider,{value:ee,children:[e.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(yi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${q?" is-dragging-dockview":""}${j?" is-showing-dockview-overlay":""}`,components:{conversation:Su,remote:Cu},defaultTabComponent:Mu,watermarkComponent:Iu,onReady:me,singleTabMode:"default",tabAnimation:"smooth",theme:_e,popoutUrl:"/popout.html"})}),B&&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:B.x,top:B.y},children:[V(B.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:()=>{W(B.tabKey),A(null)},children:[e.jsx(tc,{size:13,className:"shrink-0 opacity-70"})," Move back to main window"]}):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:()=>{ge(B.tabKey),A(null)},children:[e.jsx(ec,{size:13,className:"shrink-0 opacity-70"})," Open in new window"]}),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:F=>{F.stopPropagation(),fe(B.tabKey),A(null)},children:[e.jsx(sc,{size:13,className:"shrink-0 opacity-70"})," ",ce[B.tabKey]?`Change shortcut (${ce[B.tabKey]})`:"Set shortcut"]}),ce[B.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 F={...ce};delete F[B.tabKey],G(F),A(null)},children:[e.jsx(ht,{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:()=>{S(B.tabKey),A(null)},children:[e.jsx($a,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),ne&&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:()=>fe(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:F=>F.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. ",te?"⌘+1":"Ctrl+1",", ",te?"⌥+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"})]})})]})}const Bo="adhdev-recent-launch-args-v1",_u=8;function Tu(t){return String(t||"").trim().replace(/\s+/g," ")}function Ko(t,s){return`${t.trim()}::${s.trim()}`}function Wo(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(Bo)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Pu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Bo,JSON.stringify(t))}catch{}}function Oo(t,s){var i;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Wo().byKey[Ko(r,n)])==null?void 0:i.items)||[]}function Uo(t,s,r){var p;const n=String(t||"").trim(),o=String(s||"").trim(),i=Tu(r);if(!n||!o||!i)return;const c=Wo(),u=Ko(n,o),m=((p=c.byKey[u])==null?void 0:p.items)||[],x=[i,...m.filter(h=>h!==i)].slice(0,_u);c.byKey[u]={items:x},Pu(c)}function Lr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Ru(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function ha(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"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 Lu(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Eu(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 Du(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 $u(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 Bu({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var q;const[u,m]=a.useState(n||((q=t[0])==null?void 0:q.id)||null),[x,p]=a.useState(""),[h,g]=a.useState(null),[S,I]=a.useState(!1);a.useEffect(()=>{var R;m(n||((R=t[0])==null?void 0:R.id)||null)},[n,t]);const d=a.useMemo(()=>t.find(R=>R.id===u)||t[0]||null,[u,t]),b=a.useMemo(()=>r.filter(R=>{if(R.type==="adhdev-daemon"||R.transport!=="pty")return!1;const j=Ru(R.daemonId||R.id);return!!(d!=null&&d.id)&&j===d.id}),[d==null?void 0:d.id,r]),y=jo(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),l=y.diagnostics,C=y.loading,M=y.applyDiagnostics,N=a.useMemo(()=>{const R=new Map;for(const j of b){const K=s.find(Y=>Y.sessionId===j.sessionId||Y.routeId===j.id);j.sessionId&&K&&R.set(j.sessionId,K)}return R},[b,s]),f=a.useCallback(async()=>{if(d!=null&&d.id){I(!0);try{const R=await o(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),j=Lr(R);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Could not load session host diagnostics");M(j.diagnostics||j.result||null),p("")}catch(R){const j=R instanceof Error?R.message:"Could not load session host diagnostics";p(j)}finally{I(!1)}}},[d==null?void 0:d.id,M,o]),w=a.useCallback(async(R,j)=>{if(!(d!=null&&d.id)||R==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
42
- This will terminate the hosted runtime.`))return;const K=`${R}:${j.sessionId}`;g(K);try{const Y=await o(d.id,R,{sessionId:j.sessionId}),_=Lr(Y);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Session host action failed");const E=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${E}: ${j.displayName}`,"success"),await f()}catch(Y){const _=Y instanceof Error?Y.message:"Session host action failed";p(_),ot.showToast(_,"warning")}finally{g(Y=>Y===K?null:Y)}},[d==null?void 0:d.id,f,o]),v=a.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
43
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){g("session_host_prune_duplicate_sessions");try{const j=await o(d.id,"session_host_prune_duplicate_sessions",{}),K=Lr(j);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Duplicate prune failed");const Y=K.result||{},_=Array.isArray(Y.prunedSessionIds)?Y.prunedSessionIds.length:0,E=typeof Y.duplicateGroupCount=="number"?Y.duplicateGroupCount:0;ot.showToast(`Pruned ${_} duplicate runtime(s) across ${E} group(s)`,"success"),await f()}catch(j){const K=j instanceof Error?j.message:"Duplicate prune failed";p(K),ot.showToast(K,"warning")}finally{g(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[d==null?void 0:d.id,f,o]),k=a.useMemo(()=>[...(l==null?void 0:l.sessions)||[]].sort((R,j)=>(j.lastActivityAt||0)-(R.lastActivityAt||0)),[l==null?void 0:l.sessions]),$=a.useMemo(()=>$u(k),[k]),L=a.useMemo(()=>k.reduce((R,j)=>{var K;return R+(((K=j.attachedClients)==null?void 0:K.length)||0)},0),[k]),B=a.useMemo(()=>[...(l==null?void 0:l.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[l==null?void 0:l.recentLogs]),A=a.useMemo(()=>[...(l==null?void 0:l.recentTransitions)||[]].slice(-3).reverse(),[l==null?void 0:l.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:R=>R.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(Bt,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.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:C||S,"aria-label":"Refresh session host",children:e.jsx(us,{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(ht,{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(R=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${R.id===(d==null?void 0:d.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>m(R.id),children:R.label},R.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&&!l&&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(Xt,{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})]})]})}),l&&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:l.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:L})]}),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:ba(l.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:ha(l.hostStartedAt)})]})]}),B&&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(Xt,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:B.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(ur,{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:()=>{v()},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"]})]})]}),k.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:k.map(R=>{var X,re;const j=N.get(R.sessionId),K=b.find(ge=>ge.sessionId===R.sessionId),Y=h===`session_host_resume_session:${R.sessionId}`,_=h===`session_host_restart_session:${R.sessionId}`,E=h===`session_host_stop_session:${R.sessionId}`,O=Eu(R.meta),U=typeof((X=R.meta)==null?void 0:X.runtimeRecoveryError)=="string"?String(R.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:R.displayName||(K==null?void 0:K.runtimeDisplayName)||(K==null?void 0:K.cliName)||R.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Du(R.lifecycle)}`,children:R.lifecycle}),O&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:O})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:R.workspaceLabel||(K==null?void 0:K.runtimeWorkspaceLabel)||R.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:R.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((re=R.writeOwner)==null?void 0:re.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Lu(R.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(en,{size:11})," ",R.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",ba(R.lastActivityAt),R.osPid?` · pid ${R.osPid}`:""]}),U&&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:U})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[j&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(j),c()},children:"Open chat"}),(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{w("session_host_resume_session",R)},children:Y?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{w("session_host_restart_session",R)},children:_?"Restarting…":"Restart"}),(R.lifecycle==="running"||R.lifecycle==="starting"||R.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:()=>{w("session_host_stop_session",R)},children:E?"Stopping…":"Stop"})]})]},R.sessionId)})}),A.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:A.map(R=>{const j=k.find(K=>K.sessionId===R.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:(j==null?void 0:j.displayName)||R.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:ha(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]})]})]})]})})}function Er(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 Ys(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ku({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:u,onListSavedSessions:m,sendDaemonCommand:x,onOpenConversation:p}){var lt,it;const h=$s(),g=a.useMemo(()=>[...t].sort(nn),[t]),[S,I]=a.useState(((lt=g[0])==null?void 0:lt.id)||""),d=a.useMemo(()=>g.find(z=>z.id===S)||g[0],[S,g]),b=a.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[l,C]=a.useState(""),[M,N]=a.useState(""),[f,w]=a.useState(Er(g[0])),[v,k]=a.useState(""),[$,L]=a.useState(""),[B,A]=a.useState([]),[q,R]=a.useState(""),[j,K]=a.useState([]),[Y,_]=a.useState(!1),[E,O]=a.useState(""),[U,X]=a.useState(!1),[re,ge]=a.useState(!1),[W,V]=a.useState(null),[D,ve]=a.useState(!1),[ie,J]=a.useState(""),[pe,te]=a.useState(!1),[ce,ne]=a.useState(""),[fe,G]=a.useState([]),[se,ee]=a.useState(!1),[ye,we]=a.useState(""),[P,ue]=a.useState(!1),H=a.useRef(null),le=a.useRef(0);a.useEffect(()=>{var z;!S&&((z=g[0])!=null&&z.id)&&I(g[0].id)},[S,g]),a.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||h(d.id,{minFreshMs:3e4}).catch(()=>{})},[h,d]);const Ce=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(z=>z.category==="cli"&&z.installed!==!1),[d]),me=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(z=>z.category==="acp"&&z.installed!==!1),[d]),_e=a.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[d]),F=a.useMemo(()=>f==="cli"?Ce.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):f==="acp"?me.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):_e,[me,f,Ce,_e]);a.useEffect(()=>{var he;if(!d)return;if(H.current!==d.id){H.current=d.id,C(y||((he=b[0])==null?void 0:he.id)||"__home__"),N(""),w(Er(d)),k(""),L(""),R(""),K([]),O(""),J("");return}C(Ae=>{var Re;return Ae==="__custom__"||Ae==="__home__"||b.some(tt=>tt.id===Ae)?Ae:y||((Re=b[0])==null?void 0:Re.id)||"__home__"}),w(Ae=>Ae==="ide"&&_e.length>0||Ae==="cli"&&Ce.length>0||Ae==="acp"&&me.length>0?Ae:Er(d))},[me.length,Ce.length,y,_e.length,d,b]),a.useEffect(()=>{var z;f&&(F.some(he=>he.id===v)||k(((z=F[0])==null?void 0:z.id)||""))},[f,F,v]);const Q=a.useCallback(async(z,he)=>{const Ae=le.current+1;return le.current=Ae,_(!0),O(""),m(z,he).then(Re=>{le.current===Ae&&K(Re)}).catch(Re=>{le.current===Ae&&(K([]),O(Re instanceof Error?Re.message:"Could not load saved sessions"))}).finally(()=>{le.current===Ae&&_(!1)})},[m]),ae=a.useCallback((z,he)=>{A(Oo(z,he))},[]);a.useEffect(()=>{if(R(""),!d||!v||f==="ide"?A([]):ae(d.id,v),f!=="cli"){K([]),O(""),_(!1);return}if(!d||!v){K([]),O(""),_(!1);return}Q(d.id,v)},[f,ae,Q,d,v]),a.useEffect(()=>{if(!q)return;const z=j.find(he=>he.providerSessionId===q);z!=null&&z.canResume||R("")},[j,q]);const de=l==="__custom__"?M.trim():l==="__home__"?"":((it=b.find(z=>z.id===l))==null?void 0:it.path)||"",Se=a.useCallback(z=>{const he=String(z.workspace||"").trim();if(!he)return;const Ae=b.find(Re=>Ys(Re.path)===Ys(he));if(Ae){C(Ae.id),N("");return}C("__custom__"),N(he)},[b]),Me=a.useCallback(z=>{const he=String(z.workspace||"").trim();if(!he)return{workspaceId:null,workspacePath:null};const Ae=b.find(Re=>Ys(Re.path)===Ys(he));return Ae?{workspaceId:Ae.id,workspacePath:null}:{workspaceId:null,workspacePath:he}},[b]),Le=a.useMemo(()=>{var he;if(f!=="cli"||!d||!v)return null;const z=((he=Ce.find(Ae=>Ae.type===v))==null?void 0:he.displayName)||v;return{routeId:d.id,daemonId:d.id,providerSessionId:q||void 0,transport:"pty",mode:"chat",agentName:z,agentType:v,status:"idle",title:z,messages:[],ideType:v,workspaceName:de,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${v}`,machineName:ft(d,{fallbackId:d.id})}},[f,Ce,de,d,q,v]),Ee=a.useCallback(()=>{var he,Ae;if(!d)return;C("__custom__"),te(!0),we("");const z=hr(d.platform,[M.trim(),de,(he=b.find(Re=>Re.id===y))==null?void 0:he.path,(Ae=b[0])==null?void 0:Ae.path]);ee(!0),o(d.id,z).then(Re=>{ne(Re.path),N(Re.path),G(Re.directories)}).catch(Re=>{we(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>ee(!1))},[M,y,o,de,d,b]),Fe=a.useCallback(z=>{d&&(ee(!0),we(""),o(d.id,z).then(he=>{ne(he.path),N(he.path),G(he.directories)}).catch(he=>{we(he instanceof Error?he.message:"Could not load folder")}).finally(()=>ee(!1)))},[o,d]),We=a.useCallback(async()=>{if(!d||!de)return;ue(!0),J("");const z=await i(d.id,de);if(ue(!1),!z.ok){J(z.error||"Could not save workspace");return}J("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,de,d]),Je=a.useCallback(async()=>{if(!d||!f||!v)return;ve(!0),J("");const z=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],he=f==="ide"?await c(d.id,v,{workspacePath:de||null}):await u(d.id,f,v,{workspaceId:l!=="__home__"&&l!=="__custom__"?l:null,workspacePath:l==="__custom__"&&de||null,resumeSessionId:f==="cli"&&q?q:null,cliArgs:z});if(ve(!1),!he.ok){J(he.error||"Could not start session");return}f!=="ide"&&$.trim()&&(Uo(d.id,v,$),ae(d.id,v)),n()},[f,$,ae,n,c,u,de,d,q,v,l]);return d?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(ht,{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:d.id,onChange:z=>I(z.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:D,children:g.map(z=>e.jsx("option",{value:z.id,children:ft(z,{fallbackId:z.id})},z.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:D||!d,onClick:()=>ge(!0),children:[e.jsx(Bt,{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:Ee,disabled:D,children:"Browse…"})]}),e.jsxs("select",{value:l,onChange:z=>{const he=z.target.value;C(he),he==="__custom__"?Ee():J("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D,children:[e.jsx("option",{value:"__home__",children:"Home directory"}),b.map(z=>e.jsxs("option",{value:z.id,children:[z.id===y?"⭐ ":"",pr(z.path,z.label)||z.path]},z.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l==="__home__"?"Launch without a workspace.":de||"Select a workspace folder."}),l==="__custom__"&&de&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ee,disabled:D,children:[e.jsx(cs,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:We,disabled:D||P,children:P?"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:_e.length>0},{id:"acp",label:"ACP",enabled:me.length>0}].map(z=>e.jsx("button",{type:"button",className:`btn btn-sm ${f===z.id?"btn-primary":"btn-secondary"}`,onClick:()=>w(z.id),disabled:!z.enabled||D,children:z.label},z.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:[F.map(z=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>k(z.id),disabled:D,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.meta})]},z.id)),F.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:z=>L(z.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:D}),B.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:B.map(z=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(z),disabled:D,title:z,children:z},z))})]}),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:D||!d||!v||Y,onClick:()=>{!d||!v||Q(d.id,v)},children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:D||!d||!v,onClick:()=>{!d||!v||(X(!0),Q(d.id,v))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:q,onChange:z=>{const he=z.target.value;if(R(he),!he)return;const Ae=j.find(Re=>Re.providerSessionId===he);!Ae||!Ae.canResume||Se(Ae)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D||Y,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),j.map(z=>e.jsxs("option",{value:z.providerSessionId,disabled:!z.canResume,children:[z.title||z.providerSessionId,z.canResume?"":" (workspace missing)"]},z.providerSessionId))]})}),q&&(()=>{const z=j.find(he=>he.providerSessionId===q);return z?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:z.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[z.workspace||"Workspace unknown",z.currentModel?` · ${z.currentModel}`:""]})]}):null})(),E&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:E}),!Y&&!E&&j.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),ie&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ie.includes("saved")||ie.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ie})]}),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:D,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:Je,disabled:D||!f||!v||l==="__custom__"&&!de,children:[e.jsx(sn,{size:14}),D?"Starting…":"Start session"]})]})]})}),pe&&e.jsx(gr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:fe,busy:se,error:ye,onClose:()=>te(!1),onNavigate:Fe,onConfirm:z=>{N(z),ne(z),C("__custom__"),te(!1)}}),U&&Le&&e.jsx(dn,{activeConv:Le,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:j,isSavedSessionsLoading:Y,isResumingSavedSessionId:W,onClose:()=>X(!1),onNewChat:()=>{R(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!v||Q(d.id,v)},onResumeSavedSession:z=>{if(!d||!v||W||!z.canResume)return;const he=Me(z);R(z.providerSessionId),Se(z),V(z.providerSessionId),X(!1),ve(!0),J(""),u(d.id,"cli",v,{workspaceId:he.workspaceId,workspacePath:he.workspacePath,resumeSessionId:z.providerSessionId}).then(Ae=>{if(!Ae.ok){J(Ae.error||"Could not resume session");return}n()}).finally(()=>{ve(!1),V(Ae=>Ae===z.providerSessionId?null:Ae)})}}),re&&d&&e.jsx(Bu,{machineCards:[{id:d.id,label:ft(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Ro(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:x,onOpenConversation:z=>{ge(!1),n(),p(z)},onClose:()=>ge(!1)})]}):null}const zo="adhdev-dashboard-action-shortcuts",Wu=1200,Ou={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Uu(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function qe(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"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 Ho(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:qe("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:qe("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:qe("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:qe("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:qe("openRemoteForActiveTab",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:qe("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:qe("splitActiveTabDown",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:qe("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:qe("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:qe("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:qe("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:qe("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:qe("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:qe("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:qe("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:qe("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:qe("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:qe("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:qe("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:qe("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:qe("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:qe("toggleCliView",t)}]}function zu(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function ga(t){const s=Object.fromEntries(Ho(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(zo)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Ou))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Hu(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Fu({enabled:t=!0,onTrigger:s}){const r=Uu(),[n,o]=a.useState(()=>ga(r)),[i,c]=a.useState(null),[u,m]=a.useState([]),x=a.useRef({parts:[],timer:null}),p=a.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(Hu(d.key)),b.join("+"))},[r]),h=a.useCallback(d=>{o(d);try{localStorage.setItem(zo,JSON.stringify(d))}catch{}},[]);a.useEffect(()=>{const d=ga(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([l,C])=>d[l]===C)||h(d)},[n,r,h]);const g=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}},Wu))},[]);a.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const y=p(b);if(!y)return;const C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(u.length===0&&C){m([y]);return}const N=[...u,y].slice(0,2).join(" "),f={...n};for(const[w,v]of Object.entries(f))v===N&&delete f[w];f[i]=N,h(f),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,p,h,i,u]),a.useEffect(()=>{if(!t||i)return;const d=b=>{if(b.defaultPrevented)return;const y=p(b);if(!y)return;const l=b.metaKey||b.ctrlKey||b.altKey;if(zu(b.target)&&!l)return;const C=x.current.parts,M=l?[y]:[...C.slice(-1),y].slice(-2),N=M.join(" "),f=M[M.length-1],w=Object.entries(n).filter(([,B])=>!!B),v=w.find(([,B])=>B===N);if(v){b.preventDefault(),g(),s(v[0]);return}if(w.some(([,B])=>B.startsWith(`${N} `))){b.preventDefault(),x.current.parts=M,S();return}const $=w.find(([,B])=>B===f);if($){b.preventDefault(),g(),s($[0]);return}if(w.some(([,B])=>B.startsWith(`${f} `))){b.preventDefault(),x.current.parts=[f],S();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,S,t,p,s,g,i]),a.useEffect(()=>()=>g(),[g]);const I=a.useMemo(()=>Ho(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:u,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:h}}function Vu(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 qu(t){return t instanceof Error?t.message:String(t||"")}function Gu(t){const s=qu(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Yu({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:u,onStopCli:m,activeCliViewMode:x,onSetActiveCliViewMode:p,mobileChatConversations:h,hiddenConversations:g,ides:S,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,initialDataLoaded:C,userName:M,requestedMobileTabKey:N,onRequestedMobileTabConsumed:f,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:k,onRequestedMobileSectionConsumed:$,containerRef:L,isSplitMode:B,numGroups:A,groupSizes:q,groupedConvs:R,clearedTabs:j,focusedGroup:K,setFocusedGroup:Y,moveTabToGroup:_,splitTabRelative:E,closeGroup:O,handleResizeStart:U,detectedIdes:X,handleLaunchIde:re,groupActiveTabIds:ge,setGroupActiveTabIds:W,groupTabOrders:V,setGroupTabOrders:D,toggleHiddenTab:ve,visibleConversations:ie,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:pe,onDesktopActiveTabChange:te,onHideConversation:ce,onShowHiddenConversation:ne,onShowAllHiddenConversations:fe,scrollToBottomRequest:G,machineEntries:se,onBrowseMachineDirectory:ee,onSaveMachineWorkspace:ye,onLaunchMachineIde:we,onLaunchMachineProvider:P,onListMachineSavedSessions:ue}){const H=Ye.useRef(null),[le,Ce]=Ye.useState(!1),[me,_e]=Ye.useState(!1),[F,Q]=Ye.useState(!1),[ae,de]=Ye.useState(!1),[Se,Me]=Ye.useState(!1),[Le,Ee]=Ye.useState("quickstart"),[Fe,We]=Ye.useState("workspace"),Je=!t&&!s,lt=Ye.useCallback(xe=>{Ce(xe),xe&&_e(!1)},[]),it=Ye.useCallback(xe=>{_e(xe),xe&&Ce(!1)},[]),z=Ye.useCallback(()=>{Ee(ie.length===0?"quickstart":"shortcuts"),We("workspace"),Q(!0),Ce(!1),_e(!1)},[ie.length]),he=Ye.useCallback(async xe=>{var kt;if(!r)return;const Ke=(kt=r.modalButtons)==null?void 0:kt[xe];if(!Ke)return;const jt=Ps(r);if(!jt)return;const _t=Ke.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Dt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_t);try{await d(jt,"resolve_action",{button:Ke,action:Dt?"approve":"reject",buttonIndex:xe,...is(r)})}catch(T){Gu(T)||console.error("[Shortcut approval] Failed:",T)}},[r,d]),{isMac:Ae,actionDefinitions:Re,actionShortcuts:tt,shortcutListening:Ze,shortcutListeningDraft:dt,setShortcutListening:st,setShortcutListeningDraft:wt,saveShortcuts:It}=Fu({enabled:Je&&!F,onTrigger:xe=>{var Ke,jt,_t,Dt,kt,T,Z,oe,je,Pe,Te,Ue,ut;if(xe==="openShortcutHelp"){z();return}if(xe==="hideCurrentTab"){r&&ce(r);return}if(xe==="toggleHiddenTabs"){it(!me);return}if(xe==="openHistoryForActiveTab"){r&&!Oe(r)&&c(r);return}if(xe==="openRemoteForActiveTab"){r&&!ze(r)&&!Oe(r)&&u(r);return}if(xe==="splitActiveTabRight"){(Ke=H.current)==null||Ke.splitActiveTabRight();return}if(xe==="splitActiveTabDown"){(jt=H.current)==null||jt.splitActiveTabDown();return}if(xe==="focusLeftPane"){(_t=H.current)==null||_t.focusLeftPane();return}if(xe==="focusRightPane"){(Dt=H.current)==null||Dt.focusRightPane();return}if(xe==="focusUpPane"){(kt=H.current)==null||kt.focusUpPane();return}if(xe==="focusDownPane"){(T=H.current)==null||T.focusDownPane();return}if(xe==="moveActiveTabToLeftPane"){(Z=H.current)==null||Z.moveActiveTabToLeftPane();return}if(xe==="moveActiveTabToRightPane"){(oe=H.current)==null||oe.moveActiveTabToRightPane();return}if(xe==="moveActiveTabToUpPane"){(je=H.current)==null||je.moveActiveTabToUpPane();return}if(xe==="moveActiveTabToDownPane"){(Pe=H.current)==null||Pe.moveActiveTabToDownPane();return}if(xe==="triggerPrimaryApprovalAction"){he(0);return}if(xe==="triggerSecondaryApprovalAction"){he(1);return}if(xe==="triggerTertiaryApprovalAction"){he(2);return}if(xe==="setActiveTabShortcut"){(Te=H.current)==null||Te.setShortcutForActiveTab();return}if(xe==="selectPreviousGroupTab"){(Ue=H.current)==null||Ue.activatePreviousTabInGroup();return}if(xe==="selectNextGroupTab"){(ut=H.current)==null||ut.activateNextTabInGroup();return}!r||!ze(r)||Oe(r)||xe==="toggleCliView"&&p(x==="chat"?"terminal":"chat")}}),At=Ye.useCallback(()=>{Q(!1),st(null),wt([])},[st,wt]),ps=Ye.useMemo(()=>Fe==="all"?Re:Re.filter(xe=>Vu(xe)===Fe),[Re,Fe]),$e=Ye.useCallback(()=>{const xe=Object.fromEntries(Re.map(Ke=>[Ke.id,""]));It(xe)},[Re,It]),Wt=Ye.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const xe=Object.fromEntries(Re.map(Ke=>[Ke.id,Ke.defaultShortcut]));It(xe)},[Re,It]);return Ye.useEffect(()=>{const xe=Ke=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ke.metaKey&&Ke.key.toLowerCase()==="w":Ke.ctrlKey&&Ke.key.toLowerCase()==="w")&&(Ke.preventDefault(),r&&ce&&ce(r))};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[r,ce]),Ye.useEffect(()=>{if(!F||Ze)return;const xe=Ke=>{Ke.key==="Escape"&&(Ke.preventDefault(),At())};return window.addEventListener("keydown",xe,!0),()=>window.removeEventListener("keydown",xe,!0)},[At,F,Ze]),Ye.useEffect(()=>{if(!Je){Me(!1);return}Me(!0);const xe=window.setTimeout(()=>{Me(!1)},1e4);return()=>window.clearTimeout(xe)},[Je]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(ul,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:ie,hiddenConversations:g,onOpenHistory:c,onOpenConversation:ne,onHideConversation:ce,onShowConversation:ne,onShowAllHidden:fe,inboxOpen:le,onInboxOpenChange:lt,hiddenOpen:me,onHiddenOpenChange:it,onOpenNewSession:s?void 0:()=>de(!0),onOpenRemote:()=>{!r||ze(r)||Oe(r)||u(r)},onStopCli:m,activeCliViewMode:x,onSetCliViewMode:p}),t?e.jsx(mu,{conversations:h,hiddenConversations:g,ides:S,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,userName:M,requestedActiveTabKey:N,onRequestedActiveTabConsumed:f,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:k,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:u,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:ne,onShowAllHiddenConversations:fe,onOpenNewSession:()=>de(!0)}):s?e.jsx(wu,{containerRef:L,isSplitMode:B,numGroups:A,groupSizes:q,groupedConvs:R,clearedTabs:j,ides:S,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,hasRegisteredMachines:se.length>0,userName:M,focusedGroup:K,setFocusedGroup:Y,moveTabToGroup:_,splitTabRelative:E,closeGroup:O,handleResizeStart:U,detectedIdes:X,handleLaunchIde:re,groupActiveTabIds:ge,setGroupActiveTabIds:W,groupTabOrders:V,setGroupTabOrders:D,toggleHiddenTab:ve,allowTabShortcuts:!1}):e.jsx(Au,{visibleConversations:ie,clearedTabs:j,ides:S,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,hasRegisteredMachines:se.length>0,initialDataLoaded:C,userName:M,detectedIdes:X,handleLaunchIde:re,toggleHiddenTab:ve,registerActionHandlers:xe=>{H.current=xe},onActiveTabChange:te,requestedActiveTabKey:J,onRequestedActiveTabConsumed:pe,scrollToBottomRequest:G}),ae&&e.jsx(Ku,{machines:se,conversations:h,ides:S,onClose:()=>de(!1),onBrowseDirectory:ee,onSaveWorkspace:ye,onLaunchIde:we,onLaunchProvider:P,onListSavedSessions:ue,sendDaemonCommand:d,onOpenConversation:xe=>{de(!1),ne(xe),te(xe.tabKey)}}),F&&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:At,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:xe=>xe.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, plus grouped shortcuts you can tune."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:At,children:"Close"})]}),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(xe=>e.jsx("button",{type:"button",className:`btn btn-sm ${Le===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ee(xe.id),children:xe.label},xe.id))}),Le==="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:"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 ",Ae?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Le==="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; one active pane is usually the cleanest default."]})]})]}),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."]})]})]})]}),Le==="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(xe=>e.jsx("button",{type:"button",className:`btn btn-sm ${Fe===xe.id?"btn-primary":"btn-secondary"}`,onClick:()=>We(xe.id),children:xe.label},xe.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:$e,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:Wt,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:ps.map(xe=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ze===xe.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:xe.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:xe.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:xe.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:Ze===xe.id?dt.length>0?`${dt.join(" ")} ...`:"Listening...":tt[xe.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{st(xe.id),wt([])},children:Ze===xe.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ke={...tt};Ke[xe.id]="",It(Ke)},children:"Disable"})]})]})},xe.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ae?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:z,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 ${Se?"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:"?"}),Se&&e.jsx("span",{children:"Guide"})]})]})}const Dr=[{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 Xu({onClose:t}){const[s,r]=a.useState(0),n=Dr[s],o=s===Dr.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(ht,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Dr.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:`
44
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
45
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
46
- `})]})}function Ju({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,u=i.status==="waiting_approval",m=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:u?"var(--status-warning)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"0 0 6px var(--accent-primary)":"none"}}),i.title,u&&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 Zu({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,u]=a.useState(()=>i||"native"),m=a.useMemo(()=>oo(s),[s]),x=a.useMemo(()=>t?un(t,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,m,r]),p=a.useMemo(()=>x.find(b=>b.streamSource==="native"),[x]),h=a.useMemo(()=>x.filter(b=>b.streamSource==="agent-stream"),[x]),g=a.useMemo(()=>t?Et(x,t.id):null,[x,t]);a.useEffect(()=>{i&&u(i)},[i]),a.useEffect(()=>{if(i||!g)return;const b=g.streamSource==="native"?"native":g.tabKey;!b||c===b||c==="native"&&u(b)},[c,g,i]),a.useEffect(()=>{var b;c!=="native"&&(h.some(y=>y.tabKey===c)||u(((b=h[0])==null?void 0:b.tabKey)||"native"))},[c,h]),a.useEffect(()=>{c==="native"&&(p||h[0]&&u(h[0].tabKey))},[c,p,h]);const S=a.useMemo(()=>c==="native"&&p?p:h.find(b=>b.tabKey===c)||g||p||h[0],[c,p,g,h]),I=a.useMemo(()=>h.map(b=>({tabKey:b.tabKey,title:no(b)||o,status:b.status})),[h,o]),d=a.useCallback(b=>{if(b)return x.find(y=>y.sessionId===b||y.routeId===b||y.tabKey===b)},[x]);return{activeChatTab:c,setActiveChatTab:u,activeConv:S,conversations:x,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:d}}function Qu({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:u,setActionLogs:m,isStandalone:x,userName:p,onOpenHistory:h,onConversationChange:g,onClose:S}){const[I,d]=a.useState("split"),[b,y]=a.useState(()=>Rt(t)?"native":t.tabKey),l=a.useRef(null),C=a.useMemo(()=>s||r.find(_=>_.id===t.routeId),[t.routeId,s,r]),M=a.useMemo(()=>He((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:N,extensionTabs:f,hasExtensions:w}=Zu({ideData:C,allIdes:r,connectionStates:n,localUserMessages:i,ideName:M||"IDE",preferredTabKey:Rt(t)?void 0:t.tabKey}),v=a.useMemo(()=>C?Et(N,C.id):null,[C,N]);a.useEffect(()=>{const _=l.current,E={routeId:t.routeId,tabKey:t.tabKey,streamSource:t.streamSource};if(l.current=E,!(_&&_.routeId===E.routeId&&_.tabKey===E.tabKey&&_.streamSource===E.streamSource)){if(Rt(t)){y("native");return}y(t.tabKey)}},[t.routeId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(b==="native"){if(N.some(_=>_.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!N.some(_=>_.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[N,b,v]);const k=a.useMemo(()=>b==="native"?N.find(_=>_.streamSource==="native")||t:N.find(_=>_.tabKey===b)||t,[t,N,b]),$=ko(k),L=a.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...k,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:k,[k,$]),B=ar(L),A=xr({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:u,setActionLogs:m,isStandalone:x}),{connScreenshot:q,screenshotUsage:R,handleRemoteAction:j}=Do({doId:B,targetSessionId:cn(L),connState:L.connectionState||"new",viewMode:I}),K=a.useMemo(()=>o.filter(_=>_.routeId===L.tabKey),[o,L.tabKey]);a.useEffect(()=>{g==null||g(L)},[L,g]),a.useEffect(()=>{const _=E=>{E.key==="Escape"&&S()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[S]);const Y=a.useCallback(_=>{_.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:Y,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(xt,{size:16})}),e.jsx("span",{className:"truncate",children:fr(k)||"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(_=>{const E=I===_;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:()=>d(_),title:_==="split"?"Split view":"Remote only",children:_==="split"?e.jsx(Ui,{size:15}):e.jsx(xt,{size:15})},_)})}),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(k),title:"Chat History",children:[e.jsx(tn,{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(Ju,{hasExtensions:w,ideName:M||"IDE",activeChatTab:b,extensionTabs:f,onSelectTab:y}),e.jsx(Fa,{activeConv:L,onModalButton:A.handleModalButton}),e.jsx(Hr,{activeConv:L,ideEntry:C,showMetaChips:!1,handleSendChat:A.handleSendChat,isSendingChat:A.isSendingChat,handleFocusAgent:A.handleFocusAgent,isFocusingAgent:A.isFocusingAgent,actionLogs:K,userName:p})]}),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(Ua,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:q,screenshotUsage:R,transportType:L.transport,onAction:j})})]})]})})}function em({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=ol(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 tm({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:u,onCloseHistory:m,onNewHistoryChat:x,onSwitchHistorySession:p,onRefreshHistory:h,onResumeSavedHistorySession:g,remoteDialogConv:S,remoteDialogIdeEntry:I,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:C,setActionLogs:M,isStandalone:N,userName:f,onOpenRemoteHistory:w,onRemoteConversationChange:v,onCloseRemoteDialog:k,cliStopDialogOpen:$,cliStopTargetConv:L,onCancelCliStop:B,onStopCliNow:A,onSaveCliAndStop:q,toasts:R,onDismissToast:j,onClickToast:K,showOnboarding:Y,onCloseOnboarding:_}){var E;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(dn,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:u,onClose:m,onNewChat:x,onSwitchSession:p,onRefreshHistory:h,onResumeSavedSession:g}),S&&e.jsx(Qu,{activeConv:S,ideEntry:I,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:C,setActionLogs:M,isStandalone:N,userName:f,onOpenHistory:w,onConversationChange:v,onClose:k}),$&&L&&(ze(L)||Oe(L))&&e.jsx(em,{activeConv:L,canSaveAndStop:ze(L)&&!Oe(L)&&!!((E=L.resume)!=null&&E.supported),onCancel:B,onStopNow:A,onSaveAndStop:q}),e.jsx(ao,{toasts:R,onDismiss:j,onClickToast:K}),Y&&e.jsx(Xu,{onClose:_})]})}function sm({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(us,{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 u=ft(c,{fallbackId:c.id}),m=n[c.id],x=c.version||c.daemonVersion||"unknown",p=c.versionUpdateRequired===!0;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[e.jsx("span",{className:"font-medium text-text-primary",children:u}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",x]}),p&&e.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),m==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:p?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):m==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):m==="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:p?"var(--status-danger)":"var(--status-warning)",background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:p?"Update now":"Upgrade"})]},c.id)})]}),!r&&e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:e.jsx(ht,{size:16})})]})}function rm(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function ya(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function nm(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function am(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 om(){var kn,Nn,Sn,Cn,In;const{sendCommand:t}=bt(),s=$s(),r=Zr(),n=ds(),[o,i]=ji(),c=o.get("activeTab"),u=((kn=r.state)==null?void 0:kn.openRemoteForTabKey)||null,m=((Nn=r.state)==null?void 0:Nn.openMachineId)||null,x=((Sn=r.state)==null?void 0:Sn.mobileSection)||null,p=eo(),h=p.ides||[],g=p.initialLoaded??!0,{updateRouteChats:S,setToasts:I}=p,[d,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=p.toasts||[],l=p.wsStatus||"connected",C=p.isConnected??!0,M=p.connectionStates||{},N=p.showReconnected||!1,{groupAssignments:f,setGroupAssignments:w,focusedGroup:v,setFocusedGroup:k,groupActiveTabIds:$,setGroupActiveTabIds:L,groupTabOrders:B,setGroupTabOrders:A,groupSizes:q,setGroupSizes:R,isMobile:j,hasHydratedStoredLayout:K,hydrateStoredLayout:Y}=Wd(),[_,E]=a.useState(!1),[O,U]=a.useState(!1),[X,re]=a.useState(null),[ge,W]=a.useState([]),[V,D]=a.useState(!1),[ve,ie]=a.useState(null),[J]=a.useState(()=>wo()),[pe,te]=a.useState([]),[ce,ne]=a.useState({}),[fe,G]=a.useState({}),[se,ee]=a.useState(null),[ye,we]=a.useState(null),[P,ue]=a.useState(null),H=a.useRef(null);Ls("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(f).length,localMessageTabs:Object.keys(ce).length,actionLogCount:pe.length});const le=h.find(be=>be.type==="adhdev-daemon"),Ce=(le==null?void 0:le.detectedIdes)||[],me=a.useMemo(()=>h.filter(be=>be.type==="adhdev-daemon").sort(nn),[h]),_e=!!le;a.useEffect(()=>{!le||!(!le.detectedIdes||!le.availableProviders||!le.recentLaunches||!le.workspaces)||s(le.id,{minFreshMs:3e4}).catch(()=>{})},[le,s]);const F=(le==null?void 0:le.terminalBackend)||null,Q=le?ft(le,{fallbackId:le.id}):null,ae=(le==null?void 0:le.id)||null,{hiddenTabs:de,hideTab:Se,toggleTab:Me,showTab:Le,showAllTabs:Ee}=yd(),{chatIdes:Fe,conversations:We,visibleConversations:Je,visibleTabKeys:lt,resolveConversationBySessionId:it,resolveConversationByTarget:z}=_d({ides:h,connectionStates:M,localUserMessages:ce,clearedTabs:fe,hiddenTabs:de}),he=a.useMemo(()=>Es(h),[h]),Ae=a.useRef(null),{containerRef:Re,normalizedGroupAssignments:tt,numGroups:Ze,isSplitMode:dt,groupedConvs:st,moveTabToGroup:wt,closeGroup:It,handleResizeStart:At,splitTabRelative:ps}=Gd({groupAssignments:f,setGroupAssignments:w,setFocusedGroup:k,setGroupActiveTabIds:L,setGroupTabOrders:A,groupSizes:q,setGroupSizes:R,isMobile:j,visibleConversations:Je,visibleTabKeys:lt}),$e=a.useMemo(()=>{var Ie,Ne;if(!j){if(se){const ke=We.find(Be=>Be.tabKey===se);if(ke)return ke}return Je[0]}const be=$[v];if(be){const ke=We.find(Be=>Be.tabKey===be);if(ke)return ke}return((Ie=st[v])==null?void 0:Ie[0])||((Ne=st[0])==null?void 0:Ne[0])},[se,j,$,v,We,st,Je]);a.useEffect(()=>{if(j){Ae.current=null;return}if(!($e!=null&&$e.sessionId)){Ae.current=null;return}const be=`${$e.tabKey}:${$e.sessionId}`;if(Ae.current===be)return;const Ie=()=>{if(document.visibilityState!=="visible"||Ae.current===be)return;Ae.current=be;const Ne=As($e,he),ke=Math.max(Date.now(),qt($e),Ne.lastUpdated||0);t($e.daemonId||$e.routeId,"mark_session_seen",{sessionId:$e.sessionId,seenAt:ke}).catch(()=>{})};if(document.visibilityState==="visible"){const Ne=setTimeout(Ie,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(Ie,800),document.removeEventListener("visibilitychange",Ne))};return document.addEventListener("visibilitychange",Ne),()=>{document.removeEventListener("visibilitychange",Ne)}}},[$e,j,he,t]);const{requestedDesktopTabKey:Wt,requestedMobileTabKey:xe,consumeRequestedActiveTab:Ke}=Td({isMobile:j,urlActiveTab:c,resolveConversationBySessionId:it,setSearchParams:i}),{remoteDialogConv:jt,remoteDialogIdeEntry:_t,remoteDialogActiveConv:Dt,setRemoteDialogActiveConv:kt,openRemoteDialog:T,closeRemoteDialog:Z}=zd({isMobile:j,location:r,navigate:n,requestedRemoteTabTarget:u,requestedDesktopTabKey:Wt,conversations:We,ides:h,resolveConversationByTarget:z}),oe=Dt||jt||$e,je=!!oe&&ze(oe)&&!Oe(oe),Pe=a.useMemo(()=>{if(!oe||!je)return null;const be=oe.daemonId||oe.routeId||"",Ie=pt(oe);return`${be}:${Ie}`},[oe,je]),Te=a.useMemo(()=>Je,[Je]),Ue=j&&J==="chat",ut=a.useMemo(()=>We.filter(be=>de.has(be.tabKey)),[We,de]),ct=a.useCallback(be=>{const Ie=new URLSearchParams(o);Ie.set("activeTab",be),i(Ie,{replace:!0})},[o,i]),Qe=a.useCallback(async(be,Ie)=>br(t,be,Ie),[t]),fs=a.useCallback(async(be,Ie)=>{if(!Ie.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ne=await t(be,"workspace_add",{path:Ie.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]),Fo=a.useCallback(async(be,Ie,Ne)=>{var ke;try{const Be={ideType:Ie,enableCdp:!0};(ke=Ne==null?void 0:Ne.workspacePath)!=null&&ke.trim()&&(Be.workspace=Ne.workspacePath.trim());const et=await t(be,"launch_ide",Be);return!(et!=null&&et.success)&&(et==null?void 0:et.success)!==void 0?{ok:!1,error:(et==null?void 0:et.error)||"Could not launch IDE"}:(ue({machineId:be,kind:"ide",providerType:Ie,workspacePath:(Ne==null?void 0:Ne.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Be){return{ok:!1,error:Be instanceof Error?Be.message:"Could not launch IDE"}}},[t]),Vo=a.useCallback(async(be,Ie,Ne,ke)=>{var et,xs,ts;const Be=Date.now();try{const Nt={cliType:Ne};(et=ke==null?void 0:ke.workspacePath)!=null&&et.trim()?Nt.dir=ke.workspacePath.trim():ke!=null&&ke.workspaceId&&(Nt.workspaceId=ke.workspaceId),(xs=ke==null?void 0:ke.resumeSessionId)!=null&&xs.trim()&&(Nt.resumeSessionId=ke.resumeSessionId.trim()),Array.isArray(ke==null?void 0:ke.cliArgs)&&ke.cliArgs.length>0&&(Nt.cliArgs=ke.cliArgs),(ts=ke==null?void 0:ke.initialModel)!=null&&ts.trim()&&(Nt.initialModel=ke.initialModel.trim());const rt=await t(be,"launch_cli",Nt),mt=(rt==null?void 0:rt.result)||rt,hs=(mt==null?void 0:mt.sessionId)||(mt==null?void 0:mt.id);return rt!=null&&rt.success&&hs?(ct(hs),{ok:!0}):rt!=null&&rt.success?(ue({machineId:be,kind:Ie,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:Be}),{ok:!0}):{ok:!1,error:(rt==null?void 0:rt.error)||(mt==null?void 0:mt.error)||`Could not launch ${Ie.toUpperCase()} session`}}catch(Nt){return nm(Nt)?(ue({machineId:be,kind:Ie,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:Be}),{ok:!0}):{ok:!1,error:Nt instanceof Error?Nt.message:`Could not launch ${Ie.toUpperCase()} session`}}},[ct,t]),qo=a.useCallback(async(be,Ie)=>{if(!be||!Ie)return[];try{const Ne=await t(be,"list_saved_sessions",{providerType:Ie,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(!P)return;const be=ya(P.workspacePath),Ie=h.find(Be=>{var rt,mt,hs,Mn;if(!Be||Be.type==="adhdev-daemon"||rm(Be.daemonId||Be.id)!==P.machineId||(Ts(Be)?"cli":as(Be)?"acp":"ide")!==P.kind||String(Be.agentType||Be.type||"")!==P.providerType)return!1;if(P.resumeSessionId)return String(Be.providerSessionId||"")===P.resumeSessionId;if(be){const wr=ya(Be.workspace||Be.runtimeWorkspaceLabel);return wr?wr===be:!1}return Number(Be.lastUpdated||Be._lastUpdate||Be.timestamp||((Mn=(hs=(mt=(rt=Be.activeChat)==null?void 0:rt.messages)==null?void 0:mt.at)==null?void 0:hs.call(mt,-1))==null?void 0:Mn.timestamp)||0)>=P.startedAt-5e3});if(!Ie)return;const Ne=typeof Ie.sessionId=="string"&&Ie.sessionId?Ie.sessionId:typeof Ie.instanceId=="string"&&Ie.instanceId?Ie.instanceId:(ke=We.find(Be=>Be.routeId===Ie.id))==null?void 0:ke.sessionId;Ne&&(ue(null),ct(Ne))},[We,ct,h,P]),a.useEffect(()=>{if(!P)return;const be=window.setTimeout(()=>{ue(Ie=>!Ie||Ie.startedAt!==P.startedAt?Ie:null)},45e3);return()=>window.clearTimeout(be)},[P]),vd({visibleConversations:Je,clearedTabs:fe,setClearedTabs:G,setActionLogs:te}),Pd({ides:h,sendDaemonCommand:t,setToasts:I,setLocalUserMessages:ne,resolveConversationByTarget:z});const{isRefreshingHistory:Go,handleLaunchIde:Yo,handleRefreshHistory:Xo}=ra({sendDaemonCommand:t,activeConv:$e,chats:(Cn=h.find(be=>be.id===($e==null?void 0:$e.routeId)))==null?void 0:Cn.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:ne,setClearedTabs:G}),{isCreatingChat:Jo,isRefreshingHistory:Zo,handleSwitchSession:Qo,handleNewChat:ei,handleRefreshHistory:ti}=ra({sendDaemonCommand:t,activeConv:oe,chats:(In=h.find(be=>be.id===(oe==null?void 0:oe.routeId)))==null?void 0:In.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:ne,setClearedTabs:G}),vr=a.useCallback(async()=>{if(!(!oe||!je||V)){D(!0);try{const be=oe.daemonId||oe.routeId,Ie=pt(oe),Ne=await t(be,"list_saved_sessions",{agentType:Ie,providerType:Ie,kind:"cli",limit:50}),ke=(Ne==null?void 0:Ne.result)??Ne;W(Array.isArray(ke==null?void 0:ke.sessions)?ke.sessions:[])}catch(be){console.error("Refresh saved sessions failed",be),W([])}finally{D(!1)}}},[oe,V,je,t]);a.useEffect(()=>{if(!_){H.current=null;return}if(!je){H.current=null,W([]),D(!1);return}!Pe||V||H.current!==Pe&&(H.current=Pe,vr())},[vr,_,V,je,Pe]);const si=a.useCallback(async be=>{if(!oe||!je||!be.providerSessionId||!be.workspace)return;const Ie=oe.daemonId||oe.routeId,Ne=pt(oe);try{ie(be.providerSessionId);const ke=await t(Ie,"launch_cli",{cliType:Ne,dir:be.workspace,resumeSessionId:be.providerSessionId,initialModel:be.currentModel}),Be=(ke==null?void 0:ke.result)??ke,et=typeof(Be==null?void 0:Be.sessionId)=="string"?Be.sessionId:typeof(Be==null?void 0:Be.id)=="string"?Be.id:"";et&&i(xs=>{const ts=new URLSearchParams(xs);return ts.set("activeTab",et),ts},{replace:!0}),E(!1)}catch(ke){console.error("Resume saved session failed",ke)}finally{ie(null)}},[oe,je,t,i]);Ud({urlActiveTab:j&&!Ue?c:null,conversations:We,resolveConversationBySessionId:it,normalizedGroupAssignments:tt,hasHydratedStoredLayout:j&&!Ue?K:!0,hydrateStoredLayout:j&&!Ue?Y:()=>{},setGroupActiveTabIds:L,setFocusedGroup:k,setSearchParams:i,historyModalOpen:_,activeConv:$e,isRefreshingHistory:Go,ides:h,handleRefreshHistory:Xo});const yn=a.useCallback(async(be,Ie)=>{const Ne=Ie||X||$e;if(!Ne||!ze(Ne)&&!Oe(Ne))return;const ke=pt(Ne),Be=Ne.routeId||Ne.daemonId||"";try{await t(Be,"stop_cli",{cliType:ke,targetSessionId:Ne.sessionId,mode:be})}catch(et){console.error("Stop CLI failed:",et)}},[$e,X,t]),ri=a.useCallback(async be=>{const Ie=be||$e;!Ie||!ze(Ie)&&!Oe(Ie)||(re(Ie),U(!0))},[$e]),ni=a.useMemo(()=>!$e||!ze($e)||Oe($e)?null:ls($e),[$e]),ai=a.useCallback(async be=>{if(!(!$e||!ze($e)||Oe($e)||ls($e)===be))try{await t(Kt($e)||$e.routeId,"set_cli_view_mode",{targetSessionId:$e.sessionId,cliType:pt($e),mode:be})}catch(Ne){am(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},[$e,t]),{versionMismatchDaemons:oi,hasRequiredVersionDaemons:vn,appVersion:ii,versionBannerDismissed:ci,setVersionBannerDismissed:li,upgradingDaemons:di,handleBannerUpgrade:ui}=Yd({ides:h,sendDaemonCommand:t}),wn=a.useCallback(be=>{ee(be.tabKey),i(Ie=>{const Ne=new URLSearchParams(Ie),ke=$c(be);return ke?Ne.set("activeTab",ke):Ne.delete("activeTab"),Ne},{replace:!0})},[i]),jn=a.useCallback(be=>{Le(be.tabKey),wn(be)},[wn,Le]),mi=a.useCallback(be=>{Se(be.tabKey)},[Se]);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(ll,{wsStatus:l,showReconnected:N}),e.jsx(dl,{terminalBackend:F,isStandalone:_e,machineLabel:Q,machineKey:ae}),(!ci||vn)&&e.jsx(sm,{daemons:oi,targetVersion:ii,required:vn,upgradingDaemons:di,onUpgrade:ui,onDismiss:()=>li(!0)}),e.jsx(Yu,{showMobileChatMode:Ue,isMobile:j,activeConv:$e,chatIdes:Fe,wsStatus:l,isConnected:C,onOpenHistory:be=>{be&&kt(be),E(!0)},onOpenRemote:T,onStopCli:ri,activeCliViewMode:ni,onSetActiveCliViewMode:ai,mobileChatConversations:Te,ides:h,actionLogs:pe,sendDaemonCommand:t,setLocalUserMessages:ne,setActionLogs:te,isStandalone:_e,initialDataLoaded:g,userName:p.userName,requestedMobileTabKey:xe,onRequestedMobileTabConsumed:Ke,requestedMachineId:m,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:x,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:Re,isSplitMode:dt,numGroups:Ze,groupSizes:q,groupedConvs:st,clearedTabs:fe,focusedGroup:v,setFocusedGroup:k,moveTabToGroup:wt,splitTabRelative:ps,closeGroup:It,handleResizeStart:At,detectedIdes:Ce,handleLaunchIde:Yo,groupActiveTabIds:$,setGroupActiveTabIds:L,groupTabOrders:B,setGroupTabOrders:A,toggleHiddenTab:Me,visibleConversations:Je,hiddenConversations:ut,requestedDesktopTabKey:Wt,onRequestedDesktopTabConsumed:Ke,onDesktopActiveTabChange:ee,onHideConversation:mi,onShowHiddenConversation:jn,onShowAllHiddenConversations:Ee,scrollToBottomRequest:ye,machineEntries:me,onBrowseMachineDirectory:Qe,onSaveMachineWorkspace:fs,onLaunchMachineIde:Fo,onLaunchMachineProvider:Vo,onListMachineSavedSessions:qo}),e.jsx("style",{children:`
47
- body { overflow: hidden; overscroll-behavior: none; }
48
- `}),e.jsx(tm,{historyModalOpen:_,historyTargetConv:oe,ides:h,isHistoryCreatingChat:Jo,isHistoryRefreshingHistory:je?!1:Zo,savedHistorySessions:ge,isSavedHistoryLoading:V,isResumingSavedHistorySessionId:ve,onCloseHistory:()=>E(!1),onNewHistoryChat:ei,onSwitchHistorySession:Qo,onRefreshHistory:je?vr:ti,onResumeSavedHistorySession:si,remoteDialogConv:jt,remoteDialogIdeEntry:_t,connectionStates:M,actionLogs:pe,localUserMessages:ce,sendDaemonCommand:t,setLocalUserMessages:ne,setActionLogs:te,isStandalone:_e,userName:p.userName,onOpenRemoteHistory:be=>{be&&kt(be),E(!0)},onRemoteConversationChange:kt,onCloseRemoteDialog:Z,cliStopDialogOpen:O,cliStopTargetConv:X,onCancelCliStop:()=>{U(!1),re(null)},onStopCliNow:async()=>{U(!1),await yn("hard",X),re(null)},onSaveCliAndStop:async()=>{U(!1),await yn("save",X),re(null)},toasts:y,onDismissToast:be=>I(Ie=>Ie.filter(Ne=>Ne.id!==be)),onClickToast:be=>{if(be.targetKey){const Ie=z(be.targetKey);Ie&&(k(tt.get(Ie.tabKey)??0),jn(Ie),we({tabKey:Ie.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function im({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[u,m]=a.useState(null),[x,p]=a.useState(null),[h,g]=a.useState(!1),[S,I]=a.useState(null),[d,b]=a.useState(!1),[y,l]=a.useState(""),C=a.useRef(null),M=a.useCallback(_=>{C.current=_},[]),N=a.useCallback((_,E,O=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:_,message:E}]),setTimeout(()=>{var U;return(U=o.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),O&&ot.showToast(E,_==="error"||_==="warn"?"warning":"success")},[o]),f=a.useCallback(_=>{const E=_ instanceof Error?_.message:String(_||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),w=a.useCallback(async(_,E)=>{var O;if(!t||u)return!1;m(_),N("info",`Launching ${He(_)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const U={ideType:_,enableCdp:!0};(O=E==null?void 0:E.workspace)!=null&&O.trim()?U.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const X=await r(t,"launch_ide",U);return N(X!=null&&X.success?"info":"error",X!=null&&X.success?`${He(_)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(U){return N("error",`Launch error: ${U.message}`,!0),!1}finally{m(null)}},[t,u,N,r]),v=a.useCallback(async _=>{if(!t)return{success:!1};const{cliType:E,dir:O,workspaceId:U,useDefaultWorkspace:X,useHome:re,argsStr:ge,model:W,resumeSessionId:V}=_;if(!E)return N("warn","Select a CLI or ACP provider first",!0),{success:!1};const D=ge?ge.split(/\s+/).filter(Boolean):void 0,ve=(O==null?void 0:O.trim())||(U?"(saved id)":X?"(default workspace)":re?"(home)":"");N("info",`Launching ${E}${ve?` in ${ve}`:""}${W?` (model: ${W})`:""}...`),p(E);try{const ie={cliType:E,cliArgs:D,initialModel:W||void 0};O!=null&&O.trim()?ie.dir=O.trim():U?ie.workspaceId=U:X?ie.useDefaultWorkspace=!0:re&&(ie.useHome=!0),V&&(ie.resumeSessionId=V);const J=await r(t,"launch_cli",ie),pe=(J==null?void 0:J.result)||J;return J!=null&&J.success?(N("info",`${E} launched`,!0),(pe==null?void 0:pe.launchSource)==="home"?N("info","📂 Running in home directory (explicit choice)"):(pe==null?void 0:pe.launchSource)==="defaultWorkspace"&&N("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:pe==null?void 0:pe.sessionId}):(N("error",`Failed: ${(J==null?void 0:J.error)||(pe==null?void 0:pe.error)}`,!0),(J==null?void 0:J.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&I({cliType:E,argsStr:ge,model:W}),{success:!1,sessionId:pe==null?void 0:pe.sessionId})}catch(ie){return f(ie)?(N("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(N("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{p(null)}},[t,N,f,r]),k=a.useCallback(async(_,E,O,U)=>t?_?E.trim()?v({cliType:_,dir:E,argsStr:O,model:U}):(I({cliType:_,argsStr:O,model:U}),{success:!1}):(N("warn","Select a provider",!0),{success:!1}):{success:!1},[t,N,v]),$=a.useCallback(async(_,E,O)=>{if(t&&window.confirm(`Stop ${_}?
49
- This will terminate the process.`))try{const U=await r(t,"stop_cli",{cliType:_,dir:E,targetSessionId:O});U!=null&&U.success?N("info",`${_} stopped`,!0):N("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){N("error",`Stop failed: ${U.message}`,!0)}},[t,N,r]),L=a.useCallback(async _=>{try{await r(_.daemonId,"restart_ide",{ideType:_.type}),N("info",`${He(_.type)} restart initiated`,!0)}catch(E){N("error",`Restart failed: ${E.message}`,!0)}},[N,r]),B=a.useCallback(async _=>{if(window.confirm(`Stop ${He(_.type)}?
50
- This will disconnect CDP and optionally kill the process.`))try{const E=await r(_.daemonId,"stop_ide",{ideType:_.type,killProcess:!0});E!=null&&E.success?N("info",`${He(_.type)} stopped`,!0):N("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){N("error",`Stop failed: ${E.message}`,!0)}},[N,r]),A=a.useCallback(async()=>{if(t)try{const _=await r(t,"detect_ides",{});N("info",`Found ${((_==null?void 0:_.result)||[]).length} IDE(s)`,!0)}catch(_){N("error",`Detection failed: ${_.message}`,!0)}},[t,N,r]),q=a.useCallback(async _=>{if(!t||!_.trim())return!1;g(!0);try{const E=await r(t,"workspace_add",{path:_.trim()});return E!=null&&E.success?(N("info",`Workspace added: ${_.trim()}`),!0):(N("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return N("error",E.message),!1}finally{g(!1)}},[t,N,r]),R=a.useCallback(async _=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const E=await r(t,"workspace_remove",{id:_});E!=null&&E.success?N("info","Workspace removed",!0):N("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){N("error",E.message,!0)}finally{g(!1)}}},[t,N,r]),j=a.useCallback(async _=>{var E;if(t){g(!0);try{const O=await r(t,"workspace_set_default",_===null?{clear:!0}:{id:_});if(O!=null&&O.success){N("info",_?"Default workspace updated":"Default workspace cleared",!0);const U=typeof O.defaultWorkspacePath=="string"?O.defaultWorkspacePath:"";U&&((E=C.current)==null||E.call(C,U))}else N("error",(O==null?void 0:O.error)||"workspace_set_default failed",!0)}catch(O){N("error",O.message,!0)}finally{g(!1)}}},[t,N,r]),K=a.useCallback(async _=>{var O;if(!t||!_.trim())return;const E=_.trim();g(!0);try{const U=await r(t,"workspace_set_default",{path:E});U!=null&&U.success?(N("info","Default workspace set from history"),(O=C.current)==null||O.call(C,E)):N("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){N("error",U.message)}finally{g(!1)}},[t,N,r]),Y=a.useCallback(async()=>{if(t)try{if(await r(t,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:t,registeredMachineId:s,nickname:y})}catch(_){N("warn",`Live nickname updated, but account sync failed: ${_.message}`)}N("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(_){N("error",`Failed: ${_.message}`)}},[t,y,s,N,n,r]);return{logs:i,launchingIde:u,launchingAgentType:x,workspaceBusy:h,launchPick:S,setLaunchPick:I,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:l,addLog:N,handleLaunchIde:w,runLaunchCliCore:v,handleLaunchCli:k,handleStopCli:$,handleRestartIde:L,handleStopIde:B,handleDetectIdes:A,handleWorkspaceAdd:q,handleWorkspaceRemove:R,handleWorkspaceSetDefault:j,handleWorkspaceResumePath:K,handleSaveNickname:Y,setOnDefaultWorkspaceChanged:M}}function cm({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:u,handleWorkspaceAdd:m,handleWorkspaceRemove:x,handleWorkspaceSetDefault:p}=i,[h,g]=a.useState(!1),[S,I]=a.useState(""),[d,b]=a.useState([]),[y,l]=a.useState(!1),[C,M]=a.useState(""),N=a.useCallback(async B=>{l(!0),M("");try{const A=await br(c,t,B);I(A.path),b(A.directories)}catch(A){M(A instanceof Error?A.message:"Could not load folder")}finally{l(!1)}},[t,c]),f=a.useCallback(()=>{var A;g(!0);const B=hr(s.platform,[s.defaultWorkspacePath,(A=s.workspaces[0])==null?void 0:A.path]);N(B)},[N,s.defaultWorkspacePath,s.platform,s.workspaces]),w=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,k=w&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,$=((L=s.loadavg)==null?void 0:L[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(Ks,{icon:e.jsx(Ba,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Sc(s.uptime):"Waiting…"}),e.jsx(Ks,{icon:e.jsx(xt,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Ks,{icon:e.jsx(ur,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Ks,{icon:e.jsx(Hi,{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(Ln,{value:w?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:w?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),e.jsx(Ln,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:w?`${kr(s.totalMem-v)} / ${kr(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${kr(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(cs,{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:u,value:s.defaultWorkspaceId||"",onChange:B=>void p(B.target.value===""?null:B.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(B=>e.jsx("option",{value:B.id,children:B.label||B.path},B.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:u,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(B=>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:[B.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:pr(B.path,B.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:B.path,children:B.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:u,onClick:()=>void x(B.id),children:"Remove"})]},B.id))})]}),h&&e.jsx(gr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:d,busy:y,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:B=>{N(B)},onConfirm:B=>{(async()=>{if(!B)return;await m(B)&&g(!1)})()}})]})}function lm(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 dm(t,s,r){const n=[];for(const[o,i]of Object.entries(t.settings)){const c=i;if(c.length===0)continue;const u=s.find(m=>m.type===o);n.push({type:o,displayName:(u==null?void 0:u.displayName)||o,icon:(u==null?void 0:u.icon)||"",category:(u==null?void 0:u.category)||"unknown",schema:c,values:t.values[o]||{}})}return n}const va=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],um=[{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 mm({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,u]=a.useState("codex-cli"),[m,x]=a.useState([]),[p,h]=a.useState(""),[g,S]=a.useState([]),[I,d]=a.useState(""),b=a.useRef(null),y=a.useRef(null),l=v=>{x(k=>k.includes(v)?k.filter($=>$!==v):[...k,v])},C=()=>x([...va]),M=()=>x([]);a.useEffect(()=>{var v;(v=b.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),a.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const N=a.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(t,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&o==="running"&&(i("done"),S(k=>[...k,`
51
- ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[t,s.type,r,o]),f=async()=>{if(m.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,p?`💬 Comment: ${p}`:"",""]),d("");try{const v=await r(t,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...p?{comment:p}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(S(k=>[...k,"✅ Agent started. Monitoring progress..."]),N()):(i("error"),d((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),d((v==null?void 0:v.message)||"Connection failed")}}},w=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),S(v=>[...v,`
52
- ⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.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:v=>v.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:um.map(v=>e.jsxs("button",{onClick:()=>u(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.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:C,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:va.map(v=>e.jsxs("button",{onClick:()=>l(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(v)?"☑ ":"☐ ",v]},v))})]}),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:p,onChange:v=>h(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(o==="running"||o==="done"||o==="error")&&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:[g.map((v,k)=>e.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},k)),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"&&m.length>0&&`${m.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:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:w,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([]),d("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function pm({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var N;const i=s.filter(f=>f.category==="ide"),[c,u]=a.useState(((N=i[0])==null?void 0:N.type)||""),[m,x]=a.useState(""),[p,h]=a.useState(""),[g,S]=a.useState(!1),[I,d]=a.useState(""),[b,y]=a.useState(!1),l=f=>{const w=f.toLowerCase().replace(/[^a-z0-9-]/g,"");x(w),(!p||p===C(m))&&h(C(w))},C=f=>f.split("-").map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join(" "),M=async()=>{if(!(!m||!p||!c)){S(!0),d("");try{const f=await r(t,"provider_clone",{type:m,name:p,category:"ide",location:"user",cloneFrom:c});f!=null&&f.success||f!=null&&f.created?(y(!0),o==null||o(m)):d((f==null?void 0:f.error)||"Failed to create provider")}catch(f){d((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:m})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," 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:()=>u(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:m,onChange:f=>l(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/",m||"...","/"]})]})]}),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:p,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:!m||!p||g,className:"machine-btn",style:{background:m&&p?"rgba(34,197,94,0.12)":void 0,borderColor:m&&p?"rgba(34,197,94,0.3)":void 0,color:m&&p?"#86efac":void 0,opacity:!m||!p||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function fm({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[u,m]=a.useState(null),[x,p]=a.useState("all"),[h,g]=a.useState(null),[S,I]=a.useState(!1),d=a.useCallback(async()=>{if(t){c(!0);try{const y=await r(t,"get_provider_settings",{}),l=lm(y);if(l){const C=dm(l,s);C.sort((M,N)=>M.category.localeCompare(N.category)||M.displayName.localeCompare(N.displayName)),o(C)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&d()},[]);const b=async(y,l,C)=>{m(`${y}.${l}`),o(M=>M.map(N=>N.type===y?{...N,values:{...N.values,[l]:C}}:N));try{const M=await r(t,"set_provider_setting",{providerType:y,key:l,value:C});M!=null&&M.success||d()}catch{d()}m(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(y=>e.jsx("button",{onClick:()=>p(y),className:`machine-btn text-[10px] px-2 py-0.5 ${x===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),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:d,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),x!=="all"&&n.filter(y=>y.category===x).length>1&&(()=>{const y=n.filter(N=>N.category===x),l=new Map;for(const N of y)for(const f of N.schema){if(f.type!=="boolean")continue;const w=l.get(f.key),v=!!(N.values[f.key]??f.default);w?(w.onCount+=v?1:0,w.total+=1):l.set(f.key,{label:f.label||f.key,onCount:v?1:0,total:1})}const C=[...l.entries()].filter(([,N])=>N.total===y.length);if(C.length===0)return null;const M=async(N,f)=>{for(const w of y)await b(w.type,N,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 (",y.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(([N,f])=>{const w=f.onCount===f.total,v=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(N,!0),disabled:w,className:`machine-btn text-[9px] px-1.5 py-px ${w?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void M(N,!1),disabled:v,className:`machine-btn text-[9px] px-1.5 py-px ${v?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),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(y=>x==="all"||y.category===x).map(y=>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:y.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:y.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:y.category==="acp"?"rgba(139,92,246,0.08)":y.category==="cli"?"rgba(59,130,246,0.08)":y.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:y.category==="acp"?"#a78bfa":y.category==="cli"?"#60a5fa":y.category==="ide"?"#86efac":"var(--status-warning)"},children:y.category}),y.category==="ide"&&e.jsx("button",{onClick:()=>g(s.find(l=>l.type===y.type)||{type:y.type,name:y.displayName,displayName:y.displayName,icon:y.icon,category:y.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),e.jsx("div",{className:"flex flex-col gap-2",children:y.schema.map(l=>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:[l.label||l.key,u===`${y.type}.${l.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),l.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:l.description})]}),e.jsx("div",{className:"shrink-0",children:l.type==="boolean"?e.jsx("button",{onClick:()=>b(y.type,l.key,!(y.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:y.values[l.key]??l.default?"#8b5cf6":"var(--border-subtle)"},children: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:y.values[l.key]??l.default?21:3}})}):l.type==="number"?e.jsx("input",{type:"number",value:Number(y.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:C=>{const M=parseInt(C.target.value)||0;l.min!==void 0&&M<l.min||l.max!==void 0&&M>l.max||b(y.type,l.key,M)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?e.jsx("select",{value:String(y.values[l.key]??l.default??""),onChange:C=>b(y.type,l.key,C.target.value),className:"machine-input text-[11px]",children:l.options.map(C=>e.jsx("option",{value:C,children:C},C))}):e.jsx("input",{type:"text",value:String(y.values[l.key]??l.default??""),onBlur:C=>b(y.type,l.key,C.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},y.type))}),h&&e.jsx(mm,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),S&&e.jsx(pm,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),d()}})]})}function xm({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState(0),[c,u]=a.useState(!0),[m,x]=a.useState("debug"),p=a.useRef(null),h=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const g=async()=>{try{const I=await s(t,"get_logs",{count:200,minLevel:m,since:o}),d=(I==null?void 0:I.result)||I;if(I!=null&&I.success&&Array.isArray(d==null?void 0:d.logs)&&d.logs.length>0){n(y=>[...y,...d.logs.map(C=>({timestamp:C.ts,level:C.level,message:`[${C.category}] ${C.message}`}))].slice(-300));const b=Math.max(...d.logs.map(y=>y.ts));i(b)}}catch{}};g();const S=setInterval(g,3e3);return()=>clearInterval(S)},[t,c,o,m,s]),a.useEffect(()=>{if(c&&r.length>0){const g=h.current?"smooth":"instant";setTimeout(()=>{var S;(S=p.current)==null||S.scrollIntoView({behavior:g}),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(g=>e.jsx("button",{onClick:()=>{x(g),n([]),i(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${m===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),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:()=>u(!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((g,S)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#475569":"#8b5cf6"},children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:g.message})]},S)),e.jsx("div",{ref:p})]})]})}function $r(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Br(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function wa(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 hm(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function bm(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 gm(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 ym(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 vm({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[u,m]=a.useState(!1),x=jo(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),p=x.diagnostics,h=x.loading,g=x.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(f=>[f.sessionId||f.id,f])),[s]),I=a.useCallback(async()=>{if(t){m(!0);try{const f=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),w=$r(f);if(!(w!=null&&w.success))throw new Error((w==null?void 0:w.error)||"Could not load session host diagnostics");g(w.diagnostics||w.result||null),o("")}catch(f){const w=f instanceof Error?f.message:"Could not load session host diagnostics";o(w)}finally{m(!1)}}},[g,t,r]),d=a.useCallback(async(f,w)=>{const v=`${f}:${w.sessionId}`;if(!(f==="session_host_stop_session"&&!window.confirm(`Stop ${w.displayName}?
53
- This will terminate the hosted runtime.`))){c(v);try{const k=await r(t,f,{sessionId:w.sessionId}),$=$r(k);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const L=f==="session_host_resume_session"?"resumed":f==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${L}: ${w.displayName}`,"success"),await I()}catch(k){const $=k instanceof Error?k.message:"Session host action failed";ot.showToast($,"warning"),o($)}finally{c(k=>k===v?null:k)}}},[t,I,r]),b=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
54
- 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 w=await r(t,"session_host_prune_duplicate_sessions",{}),v=$r(w);if(!(v!=null&&v.success))throw new Error((v==null?void 0:v.error)||"Duplicate prune failed");const k=v.result||{},$=Array.isArray(k.prunedSessionIds)?k.prunedSessionIds.length:0,L=typeof k.duplicateGroupCount=="number"?k.duplicateGroupCount:0;ot.showToast(`Pruned ${$} duplicate runtime(s) across ${L} group(s)`,"success"),await I()}catch(w){const v=w instanceof Error?w.message:"Duplicate prune failed";ot.showToast(v,"warning"),o(v)}finally{c(w=>w==="session_host_prune_duplicate_sessions"?null:w)}}},[t,I,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((f,w)=>(w.lastActivityAt||0)-(f.lastActivityAt||0)),[p==null?void 0:p.sessions]),l=a.useMemo(()=>ym(y),[y]),C=a.useMemo(()=>y.reduce((f,w)=>{var v;return f+(((v=w.attachedClients)==null?void 0:v.length)||0)},0),[y]),M=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),N=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(f=>f.level==="warn"||f.level==="error")||null,[p==null?void 0:p.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(Bt,{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:[l>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 (${l})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||u,children:[e.jsx(us,{size:13}),h||u?"Refreshing…":"Refresh"]})]})]}),n&&!p&&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(Xt,{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})]})]})}),p&&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:p.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:C})]}),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:p.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:wa(p.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Br(p.hostStartedAt)})]})]}),N&&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(Xt,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:N.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Br(N.timestamp),N.sessionId?` · ${N.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(ur,{size:14})," Hosted Runtimes"]}),y.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:y.map(f=>{var A;const w=i===`session_host_resume_session:${f.sessionId}`,v=i===`session_host_restart_session:${f.sessionId}`,k=i===`session_host_stop_session:${f.sessionId}`,$=bm(f.meta),L=S.get(f.sessionId),B=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||(L==null?void 0:L.cliName)||f.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${gm(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||(L==null?void 0:L.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:((A=f.writeOwner)==null?void 0:A.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:hm(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(en,{size:11})," ",B]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",wa(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:()=>{d("session_host_resume_session",f)},children:w?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{d("session_host_restart_session",f)},children:v?"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:()=>{d("session_host_stop_session",f)},children:k?"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 v;const w=y.find(k=>k.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:(w==null?void 0:w.displayName)||((v=S.get(f.sessionId))==null?void 0:v.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:Br(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:p.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function wm({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 Kr({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 Wr({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 jm({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const u=n.slice(0,6),m=r.slice(0,4),p=Ss(t,"0.8.41"),h=g=>g==="ide"?"IDE":g==="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:[u.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Kr,{icon:e.jsx(Lt,{size:13}),children:"Current Chats"}),e.jsx(Wr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(g=>{const S=Yr(g);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(g),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:Ve(g)}),S>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:za(S)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Qt(g)})]},g.tabKey)})})})]}),m.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Kr,{icon:e.jsx(Ba,{size:13}),children:"Recent Launches"}),e.jsx(Wr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(g=>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(g),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:g.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[h(g.kind),g.subtitle?` · ${g.subtitle}`:""]})]},g.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Kr,{icon:e.jsx(Xt,{size:13}),children:"Daemon Update"}),e.jsx(Wr,{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:p?"Daemon update required":"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:p?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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(us,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function km(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Nm={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 Xs(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Sm(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 Or({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:u,initialWorkspaceId:m,initialWorkspacePath:x}){const p=ds(),{handleLaunchIde:h,handleStopCli:g,handleRestartIde:S,handleStopIde:I,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:l}=c,[C,M]=a.useState(null),N=a.useCallback(T=>{T&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(T)}`})},[p]),f=Nm[t],w=t==="ide",v=t==="acp",k=a.useMemo(()=>n.filter(T=>T.category===t&&(t==="ide"||T.installed!==!1)),[t,n]),$=a.useMemo(()=>new Map(k.map(T=>[T.type,T.displayName||T.type])),[k]),[L,B]=a.useState(""),[A,q]=a.useState(""),[R,j]=a.useState([]),[K,Y]=a.useState(""),[_,E]=a.useState(""),[O,U]=a.useState([]),[X,re]=a.useState(!1),[ge,W]=a.useState(""),[V,D]=a.useState(!1),[ve,ie]=a.useState(null),[J,pe]=a.useState(x?"__custom__":m||s.defaultWorkspaceId||""),[te,ce]=a.useState(x||""),[ne,fe]=a.useState([]),[G,se]=a.useState(!1),[ee,ye]=a.useState(""),[we,P]=a.useState([]),[ue,H]=a.useState(!1),[le,Ce]=a.useState(""),me=a.useRef(null),[_e,F]=a.useState(null),Q=a.useRef("__home__"),[ae,de]=a.useState("__home__"),[Se,Me]=a.useState(!1),Le=a.useRef(0),Ee=ne.filter(T=>!o.some(Z=>Z.type===T&&at(Z.status)!=="stopped")),Fe=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!J&&pe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(x){pe("__custom__"),ce(x);return}m&&(pe(m),ce(""))},[m,x]),a.useEffect(()=>{w||L&&(k.some(T=>T.type===L)||(B(""),E("")))},[k,w,L]);const We=(()=>{if(J==="__custom__")return te.trim();if(!J)return"";const T=(s.workspaces||[]).find(Z=>Z.id===J);return(T==null?void 0:T.path)||""})(),Je=a.useCallback(T=>{const Z=Fe.current[T];Z&&(clearTimeout(Z),delete Fe.current[T]),fe(oe=>oe.includes(T)?oe.filter(je=>je!==T):oe)},[]),lt=a.useRef(new Set),it=a.useCallback(async T=>{if(u){H(!0),Ce("");try{const Z=await br(u,r,T);ye(Z.path),ce(Z.path),P(Z.directories)}catch(Z){Ce(Z instanceof Error?Z.message:"Could not load folder")}finally{H(!1)}}},[r,u]),z=a.useCallback(()=>{var Z;if(!u)return;pe("__custom__"),se(!0);const T=hr(s.platform,[te.trim(),We,s.defaultWorkspacePath,(Z=s.workspaces[0])==null?void 0:Z.path]);it(T)},[te,it,s.defaultWorkspacePath,s.platform,s.workspaces,We,u]),he=a.useCallback(T=>{const Z=String(T.workspace||"").trim();if(!Z)return;const oe=(s.workspaces||[]).find(je=>Xs(je.path)===Xs(Z));if(oe){pe(oe.id),ce("");return}pe("__custom__"),ce(Z)},[s.workspaces]),Ae=a.useCallback(T=>{const Z=String(T.workspace||"").trim();if(!Z)return{workspaceId:null,workspacePath:"",useHome:!0};const oe=(s.workspaces||[]).find(je=>Xs(je.path)===Xs(Z));return oe?{workspaceId:oe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Z,useHome:!1}},[s.workspaces]),Re=a.useCallback(async T=>{if(!u||!T||t!=="cli"){U([]),re(!1),W("");return}const Z=Le.current+1;Le.current=Z,re(!0),W("");try{const oe=await u(r,"list_saved_sessions",{providerType:T,kind:"cli",limit:30});if(Le.current!==Z)return;const je=(oe==null?void 0:oe.result)??oe;U(Array.isArray(je==null?void 0:je.sessions)?je.sessions:[])}catch(oe){if(Le.current!==Z)return;U([]),W(oe instanceof Error?oe.message:"Could not load saved sessions")}finally{Le.current===Z&&re(!1)}},[t,r,u]),tt=a.useMemo(()=>{if(t!=="cli"||!L)return null;const T=$.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:_||void 0,transport:"pty",mode:"chat",agentName:T,agentType:L,status:"idle",title:T,messages:[],ideType:L,workspaceName:We,displayPrimary:T,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[t,r,$,We,_,L]),Ze=a.useCallback(T=>{if(t==="ide"||!T){j([]);return}j(Oo(r,T))},[t,r]);a.useEffect(()=>{if(E(""),Ze(L),t!=="cli"||!L){U([]),W(""),re(!1);return}Re(L)},[t,Ze,Re,L]),a.useEffect(()=>{if(!_)return;const T=O.find(Z=>Z.providerSessionId===_);T!=null&&T.canResume||E("")},[O,_]);const dt=a.useCallback((T,Z)=>{me.current=Z,Q.current=T.selectedWorkspaceKey||"__home__",de(T.selectedWorkspaceKey||"__home__"),F(T)},[]),st=a.useCallback(()=>{me.current&&(Me(!0),me.current().finally(()=>{me.current=null,Me(!1),F(null)}))},[]),wt=a.useCallback(T=>{if(!T)return;fe(oe=>oe.includes(T)?oe:[...oe,T]);const Z=Fe.current[T];Z&&clearTimeout(Z),Fe.current[T]=setTimeout(()=>{fe(oe=>oe.includes(T)?oe.filter(je=>je!==T):oe),delete Fe.current[T]},2e4)},[]);a.useEffect(()=>{for(const Z of o)at(Z.status)!=="stopped"&&(ne.includes(Z.type)&&!lt.current.has(Z.type)&&(lt.current.add(Z.type),l("info",`${$.get(Z.type)||Z.type} launched`,!0)),Je(Z.type));const T=new Set(o.filter(Z=>at(Z.status)!=="stopped").map(Z=>Z.type));lt.current.forEach(Z=>{!ne.includes(Z)&&!T.has(Z)&&lt.current.delete(Z)})},[l,Je,o,ne,$]),a.useEffect(()=>()=>{Object.values(Fe.current).forEach(clearTimeout),Fe.current={}},[]);const[It,At]=a.useState({}),[ps,$e]=a.useState(null);a.useEffect(()=>{if(!w||!r||!u)return;(async()=>{try{const Z=await u(r,"get_ide_extensions",{}),oe=(Z==null?void 0:Z.result)||Z;oe!=null&&oe.success&&(oe!=null&&oe.ideExtensions)&&At(oe.ideExtensions)}catch{}})()},[w,r,u]);const Wt=T=>w?He(T.type):t==="cli"?T.cliName:T.acpName,xe=w?s.detectedIdes||[]:[],Ke=a.useCallback(async T=>{const Z=(T==null?void 0:T.type)||L,oe=(T==null?void 0:T.workspacePath)??We;if(w){await h(Z,oe?{workspace:oe}:void 0)&&wt(Z);return}const je=await c.runLaunchCliCore({cliType:Z,dir:T!=null&&T.workspaceId?void 0:oe||void 0,workspaceId:(T==null?void 0:T.workspaceId)||void 0,useHome:(T==null?void 0:T.useHome)||!(T!=null&&T.workspaceId)&&!oe,argsStr:(T==null?void 0:T.argsStr)??(A||void 0),model:(T==null?void 0:T.model)??(v&&K||void 0),resumeSessionId:(T==null?void 0:T.resumeSessionId)||!v&&t==="cli"&&Z===L&&_||void 0});if(je.success||je.pending){const Pe=(T==null?void 0:T.argsStr)??A;!w&&(Pe!=null&&Pe.trim())&&(Uo(r,Z,Pe),Ze(Z)),wt(Z),je.success&&je.sessionId&&N(je.sessionId)}},[c,h,v,w,A,K,Ze,wt,r,N,We,_,L]),jt=()=>{var je;const T=w?He(L):$.get(L)||L,{options:Z,selectedKey:oe}=Gt({machine:s,currentWorkspaceId:J&&J!=="__custom__"?J:null,currentWorkspacePath:We});dt({title:`Launch ${T}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:Z,selectedWorkspaceKey:oe,details:[{label:"Mode",value:f.label},{label:"Provider",value:T},...!w&&t==="cli"&&_?[{label:"Resume",value:((je=O.find(Pe=>Pe.providerSessionId===_))==null?void 0:je.title)||_}]:[],...!w&&A.trim()?[{label:"Arguments",value:A.trim()}]:[],...v&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Pe=Z.find(Te=>Te.key===Q.current);Pe!=null&&Pe.workspaceId?(pe(Pe.workspaceId),ce("")):Pe!=null&&Pe.workspacePath?(pe("__custom__"),ce(Pe.workspacePath)):(pe(""),ce("")),await Ke({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},_t=T=>{w?I(T):g(T.type,T.workspace,T.id)},Dt=a.useCallback(async(T,Z,oe=!1)=>{if(T.mode===Z){oe&&T.sessionId&&N(T.sessionId);return}if(!u||!T.sessionId){oe&&T.sessionId&&N(T.sessionId);return}try{await u(r,"set_cli_view_mode",{targetSessionId:T.sessionId,cliType:T.type,mode:Z}),oe&&N(T.sessionId)}catch(je){Sm(je)?console.warn("Skipped CLI view mode switch:",je instanceof Error?je.message:String(je)):console.error("Failed to switch CLI view mode:",je)}},[r,N,u]),kt=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:T=>{const Z=T.target.value;if(pe(Z),Z==="__custom__"&&u){z();return}Z!=="__custom__"&&ce("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(T=>e.jsxs("option",{value:T.id,children:[T.id===s.defaultWorkspaceId?"⭐ ":"",pr(T.path,T.label)]},T.id)),e.jsx("option",{value:"__custom__",children:u?"📁 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:u?"📁 Select workspace…":"✏️ Custom path…"})]})}),J==="__custom__"&&(u?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:z,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:te,onChange:T=>ce(T.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__"?We?e.jsx("span",{className:"font-mono truncate block",title:We,children:We}):u?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":We?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:We,children:We})]}):"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:w?xe.length>0?xe.map(T=>{const Z=o.find(Ue=>(Ue.type||"").toLowerCase()===(T.type||"").toLowerCase()&&at(Ue.status)!=="stopped"),oe=T.running||!!Z,je=!!Z&&Z.cdpConnected,Pe=ne.includes(T.type||T.id||""),Te=L===(T.type||"");return e.jsxs("button",{onClick:()=>{if(je&&Z){const Ue=Z.sessionId;Ue?p(`/dashboard?activeTab=${encodeURIComponent(Ue)}`,{state:{openRemoteForTabKey:Ue}}):p("/dashboard",{state:{openRemoteForTabKey:Z.id}});return}Pe||B(Ue=>Ue===(T.type||"")?"":T.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 ${je?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Te?"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!==T.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(T.type)}),oe&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${je?"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:T.name||He(T.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${je?"text-green-400":Pe?"text-orange-400":Te?"text-accent-primary":"text-text-muted"}`,children:je?"Open Session":Pe?"Starting...":Te?"Configure":"Select"})]})]},T.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:d,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[e.jsx(Wi,{size:14})," Scan System"]})]}):k.length>0?k.map(T=>{const Z=L===T.type,oe=ne.includes(T.type),Pe=!!o.find(Te=>Te.type===T.type&&at(Te.status)!=="stopped");return e.jsxs("button",{onClick:()=>B(Te=>Te===T.type?"":T.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Z?"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:T.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:T.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${oe?"text-orange-400":Z?"text-accent-primary":"text-text-muted"}`,children:oe?"Starting...":Z?"Configure":"Select"})]})]},T.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."})]})}),L&&(w?xe.find(T=>T.type===L):k.find(T=>T.type===L))&&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:w?He(L):$.get(L)||L})]}),kt,!w&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&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 Re(L),disabled:!L||X,children:X?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{L&&(D(!0),Re(L))},disabled:!L,children:"Open History"})]})]}),_?(()=>{const T=O.find(Z=>Z.providerSessionId===_);return T?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:T.title||T.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:T.providerSessionId}),e.jsx("div",{children:T.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."}),ge&&e.jsx("div",{className:"text-[10px] text-red-400",children:ge})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:K,onChange:T=>Y(T.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:A,onChange:T=>q(T.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"}),R.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(T=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>q(T),title:T,children:T},T))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:jt,disabled:!!y||!!b||ne.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===L||b===L?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ne.filter(T=>!o.some(Z=>Z.type===T&&at(Z.status)!=="stopped")).length,")"]}),o.length===0&&Ee.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:[Ee.map(T=>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(T)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?He(T):$.get(T)||T}),e.jsx("div",{className:"text-[11px] text-text-muted",children:y===T?"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:${T}`)),o.map(T=>{const Z=w?T:null,oe=v?T:null,je=!w&&!v?T:null,Pe=at(T.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(T.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Wt(T),(Z==null?void 0:Z.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Z.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:T.workspace||"—"}),(oe==null?void 0:oe.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",oe.currentModel]}),(oe==null?void 0:oe.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",oe.currentPlan]}),(je==null?void 0:je.mode)&&e.jsx("span",{className:je.mode==="chat"?"text-violet-400":"text-text-secondary",children:je.mode==="chat"?"Chat view":"Terminal view"})]}),je&&(je.runtimeKey||je.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[je.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 ",je.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 Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${je.runtimeKey}`),M(je.runtimeKey||null),window.setTimeout(()=>{M(Ue=>Ue===je.runtimeKey?null:Ue)},1200)},children:C===je.runtimeKey?"Copied":"Copy"})]}),je.runtimeWriteOwner&&e.jsx("span",{style:{color:je.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:je.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:km(je.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}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Te=T.sessionId;if(Te){p(`/dashboard?activeTab=${encodeURIComponent(Te)}`,{state:{openRemoteForTabKey:Te}});return}p("/dashboard",{state:{openRemoteForTabKey:T.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(xt,{size:13})}),e.jsx("button",{onClick:()=>{const Te=T.workspace||"",{options:Ue,selectedKey:ut}=Gt({machine:s,currentWorkspacePath:Te});dt({title:`Restart ${He(T.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Ue,selectedWorkspaceKey:ut,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:He(T.type)}]},async()=>{const ct=Ue.find(fs=>fs.key===Q.current),Qe=(ct==null?void 0:ct.workspacePath)??"";if(Qe&&Qe!==Te){await Ke({type:T.type,workspacePath:Qe});return}await S(T)})},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(us,{size:14})})]}),v&&e.jsx("button",{onClick:()=>{const Te=T.sessionId;Te&&N(Te)},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:!T.sessionId,children:e.jsx(Lt,{size:14})}),je&&Pe!=="stopped"&&e.jsxs(e.Fragment,{children:[je.mode&&e.jsx(ln,{mode:je.mode,onChange:Te=>void Dt(je,Te,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Te=T.sessionId;Te&&N(Te)},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:!T.sessionId,children:je.mode==="chat"?e.jsx(Lt,{size:14}):e.jsx(xt,{size:13})})]}),Pe==="stopped"?e.jsx("button",{onClick:()=>{const Te=T.workspace||"",Ue=w?He(T.type):Wt(T),{options:ut,selectedKey:ct}=Gt({machine:s,currentWorkspacePath:Te});dt({title:`Launch ${Ue}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:ut,selectedWorkspaceKey:ct,details:[{label:"Mode",value:f.label},{label:"Provider",value:Ue}]},async()=>{const Qe=ut.find(fs=>fs.key===Q.current);await Ke({type:T.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:oe==null?void 0:oe.currentModel})})},disabled:ne.includes(T.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:ne.includes(T.type)?"⏳":e.jsx(sn,{size:14})}):e.jsx("button",{onClick:()=>_t(T),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(ht,{size:14})})]})]}),Z&&Z.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Z.aiAgents.map(Te=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Va(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",at(Te.status)]},Te.id))}),Z&&(It[Z.type]||[]).length>0&&u&&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:(It[Z.type]||[]).map(Te=>e.jsxs("button",{disabled:ps===`${Z.type}.${Te.type}`,onClick:async()=>{const Ue=`${Z.type}.${Te.type}`;$e(Ue);try{await u(r,"set_ide_extension",{ideType:Z.type,extensionType:Te.type,enabled:!Te.enabled}),At(ut=>({...ut,[Z.type]:(ut[Z.type]||[]).map(ct=>ct.type===Te.type?{...ct,enabled:!ct.enabled}:ct)}))}catch(ut){console.error("Extension toggle failed:",ut)}finally{$e(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 ${Te.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 ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,e.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},T.id)})]}),G&&u&&e.jsx(gr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ee,directories:we,busy:ue,error:le,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:T=>{it(T)},onConfirm:T=>{ce(T),pe("__custom__"),se(!1)}}),_e&&e.jsx(bn,{title:_e.title,description:_e.description,details:_e.details,workspaceOptions:_e.workspaceOptions,selectedWorkspaceKey:ae,onWorkspaceChange:T=>{Q.current=T,de(T)},confirmLabel:_e.confirmLabel,busy:Se,onConfirm:st,onCancel:()=>{me.current=null,F(null)}}),V&&tt&&e.jsx(dn,{activeConv:tt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:O,isSavedSessionsLoading:X,isResumingSavedSessionId:ve,onClose:()=>D(!1),onNewChat:()=>{E(""),D(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Re(L)},onResumeSavedSession:T=>{if(!T.canResume||ve)return;const Z=Ae(T);E(T.providerSessionId),he(T),ie(T.providerSessionId),D(!1),Ke({type:T.providerType,workspaceId:Z.workspaceId,workspacePath:Z.workspacePath,useHome:Z.useHome,resumeSessionId:T.providerSessionId}).finally(()=>{ie(oe=>oe===T.providerSessionId?null:oe)})}})]})}const ja=[{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 Cm({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:u,initialCategory:m="ide",initialWorkspaceId:x,initialWorkspacePath:p,sendDaemonCommand:h}){var d;const[g,S]=a.useState(m);a.useEffect(()=>{S(m)},[m]);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:ja.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 ${g===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] ${g===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:(d=ja.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&e.jsx(Or,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:p}),g==="cli"&&e.jsx(Or,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:p}),g==="acp"&&e.jsx(Or,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:x,initialWorkspacePath:p})]})}function Im({onNicknameSynced:t}={}){var te,ce,ne,fe,G,se,ee,ye,we;const{id:s}=ki(),r=ds(),n=Zr(),{sendCommand:o}=bt(),i=$s(),c=eo(),u=c.ides||[],m=c.initialLoaded??!0,x=u.find(P=>P.id===s&&P.type==="adhdev-daemon"),p=u.some(P=>P.type==="adhdev-daemon"),[h,g]=a.useState("workspace"),[S,I]=a.useState("ide"),d=a.useRef(null),[b,y]=a.useState(null),l=a.useRef("__home__"),[C,M]=a.useState("__home__"),[N,f]=a.useState(!1),w=a.useRef(null);a.useEffect(()=>{!s||!x||!(!x.workspaces||!x.availableProviders||!x.detectedIdes||!x.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,x,s]),hd(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},k=im({machineId:s,registeredMachineId:(x==null?void 0:x.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:w});a.useEffect(()=>ot.onToast(ue=>{c.setToasts(le=>{if(le.some(_e=>_e.message===ue.message&&ue.timestamp-_e.timestamp<3e3))return le;const me={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...le.slice(-4),me]});const H=ue.duration||5e3;setTimeout(()=>c.setToasts(le=>le.filter(Ce=>Ce.id!==ue.id)),H)}),[c]);const $=(x==null?void 0:x.availableProviders)||[],L={};for(const P of $)L[P.type]=P.icon;const B=P=>L[P]||"",A=x?{id:x.id,hostname:qa(x,{fallbackId:x.id}),platform:((te=x.machine)==null?void 0:te.platform)||"unknown",arch:((ce=x.machine)==null?void 0:ce.arch)||"",cpus:((ne=x.machine)==null?void 0:ne.cpus)||0,totalMem:((fe=x.machine)==null?void 0:fe.totalMem)||0,freeMem:(G=x.machine)==null?void 0:G.freeMem,availableMem:(se=x.machine)==null?void 0:se.availableMem,loadavg:(ee=x.machine)==null?void 0:ee.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,q=u.filter(P=>P.daemonId===s&&P.type!=="adhdev-daemon").filter(P=>!Ts(P)&&!as(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Tc(P.aiAgents||(P.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:s})),R=u.filter(P=>P.daemonId===s&&Ts(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:s})),j=u.filter(P=>P.daemonId===s&&as(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,currentModel:P.currentModel,currentPlan:P.currentPlan,daemonId:s})),K=x?ft(x,{fallbackId:s}):"",Y="workspace",_=n.state,E=_==null?void 0:_.initialMachineTab,O=_==null?void 0:_.initialWorkspaceCategory,U=_==null?void 0:_.initialWorkspaceId,X=_==null?void 0:_.initialWorkspacePath,re=E==="ides"||E==="clis"||E==="acps"?"workspace":E||Y,ge=E==="ides"?"ide":E==="clis"?"cli":E==="acps"?"acp":O,W=[...q.map(P=>{var ue,H,le,Ce,me;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((me=(Ce=(le=(H=P.activeChat)==null?void 0:H.messages)==null?void 0:le.at)==null?void 0:Ce.call(le,-1))==null?void 0:me.timestamp)||0}}),...R.map(P=>{var ue,H,le,Ce,me;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((me=(Ce=(le=(H=P.activeChat)==null?void 0:H.messages)==null?void 0:le.at)==null?void 0:Ce.call(le,-1))==null?void 0:me.timestamp)||0}}),...j.map(P=>{var ue,H,le,Ce,me;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ue=P.activeChat)==null?void 0:ue.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace||void 0,currentModel:P.currentModel,timestamp:((me=(Ce=(le=(H=P.activeChat)==null?void 0:H.messages)==null?void 0:le.at)==null?void 0:Ce.call(le,-1))==null?void 0:me.timestamp)||0}})].sort((P,ue)=>ue.timestamp-P.timestamp).map(({timestamp:P,...ue})=>ue),V=((x==null?void 0:x.recentLaunches)||[]).length>0?((x==null?void 0:x.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace,currentModel:P.currentModel})):W,D=a.useMemo(()=>{var ue;const P=((ue=c.connectionStates)==null?void 0:ue[s||""])||void 0;return u.filter(H=>H.daemonId===s&&H.type!=="adhdev-daemon").flatMap(H=>un(H,{},{connectionStates:s&&P?{[s]:P}:void 0,defaultConnectionState:P})).filter(H=>!(H.transport==="pty"&&H.mode==="terminal")).sort((H,le)=>Yr(le)-Yr(H))},[u,c.connectionStates,s]),ve=a.useCallback(P=>{const ue=P.sessionId||P.tabKey;ue&&r(`/dashboard?activeTab=${encodeURIComponent(ue)}`)},[r]),ie=a.useCallback(()=>{d.current&&(f(!0),d.current().finally(()=>{d.current=null,f(!1),y(null)}))},[]),J=a.useCallback(P=>{if(!A)return;const{options:ue,selectedKey:H}=Gt({machine:A,currentWorkspacePath:P.workspace}),le=async()=>{I(P.kind),g("workspace")};d.current=async()=>{const Ce=ue.find(F=>F.key===l.current),me=(Ce==null?void 0:Ce.workspacePath)??null,_e=(Ce==null?void 0:Ce.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await k.handleLaunchIde(P.providerType,me?{workspace:me}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await k.runLaunchCliCore({cliType:P.providerType,dir:_e?void 0:me||"",workspaceId:_e||void 0,model:P.kind==="acp"?P.currentModel:void 0,resumeSessionId:P.providerSessionId});return}await le()},l.current=H,M(H),y({title:`Launch ${P.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ue,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[k,A]);if(a.useEffect(()=>{g(re)},[Y,re,s]),a.useEffect(()=>{ge&&I(ge)},[ge,s]),!A)return m?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:v,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 pe=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xt,{size:14})," Workspace"]}),count:q.length+R.length+j.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Oi,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bi,{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:v,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[k.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:k.nicknameInput,onChange:P=>k.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&k.handleSaveNickname(),P.key==="Escape"&&k.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:k.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:()=>k.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:()=>{k.setEditingNickname(!0),k.setNicknameInput(A.machineNickname||"")},title:"Click to set nickname",children:K}),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:[A.platform," · ",A.arch]}),e.jsxs("span",{children:[A.cpus," cores"]}),(x==null?void 0:x.version)&&e.jsxs("span",{children:["v",x.version]}),A.p2p.available&&e.jsxs("span",{children:["P2P ",A.p2p.state==="connected"?"connected":A.p2p.state]}),A.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:A.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:pe.map(P=>e.jsxs("button",{onClick:()=>g(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.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(jm,{machineEntry:x,providers:$,recentLaunches:V,currentConversations:D,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:J,onOpenConversation:ve}),e.jsx(Cm,{machine:A,machineId:s,providers:$,ideSessions:q,cliSessions:R,acpSessions:j,actions:k,getIcon:B,initialCategory:S,initialWorkspaceId:U,initialWorkspacePath:X,sendDaemonCommand:o})]}),h==="providers"&&e.jsx(fm,{machineId:s,providers:$,sendDaemonCommand:o}),h==="overview"&&e.jsx(cm,{machineId:s,machine:A,ideSessions:q,cliSessions:R,acpSessions:j,actions:k,sendDaemonCommand:o}),h==="session-host"&&e.jsx(vm,{machineId:s,cliSessions:R,sendDaemonCommand:o}),h==="logs"&&e.jsx(xm,{machineId:s,sendDaemonCommand:o})]})})}),k.launchPick&&A&&e.jsx(wm,{machine:A,launchPick:k.launchPick,actions:k}),b&&e.jsx(bn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:P=>{l.current=P,M(P)},confirmLabel:b.confirmLabel,busy:N,onConfirm:ie,onCancel:()=>{d.current=null,y(null)}}),e.jsx(ao,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ue=>ue.filter(H=>H.id!==P)),onClickToast:P=>{P.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(P.targetKey)}`)}}),e.jsx("style",{children:`
55
- @keyframes toast-in {
56
- from { opacity: 0; transform: translateX(40px); }
57
- to { opacity: 1; transform: translateX(0); }
58
- }
59
- `})]})}class Mm{constructor(){Xe(this,"adapters",new Map);Xe(this,"states",new Map);Xe(this,"runtimeListeners",new Map);Xe(this,"screenshotCallbacks",new Map);Xe(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 Tt=new Mm;function Am(){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 Js=Am(),ka=3e3,_m=3e4;let Mt=null,Tm=0;const lr=new Map;let zt=null,Is=null;function Na(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function ws(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function Pm(t){return t==="connected"?"connected":t}async function sr(t,s,r){const n=gl(t,r||{}),o=Mt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++Tm}_${Date.now()}`;return new Promise((c,u)=>{const m=setTimeout(()=>{lr.delete(i),u(new Error(`WS command timeout: ${s}`))},3e4);lr.set(i,{resolve:x=>{clearTimeout(m),c(x)},reject:x=>{clearTimeout(m),u(x)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Jr(t,s){const r=Mt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Rm{constructor(s){Xe(this,"daemonId");Xe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Mt==null?void 0:Mt.readyState)===WebSocket.OPEN}get connectionState(){return(Mt==null?void 0:Mt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return sr(this.daemonId,s,r)}async sendInput(s,r){return sr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,zt&&(clearInterval(zt),zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await sr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Tt.emitScreenshot(this.daemonId,o)}}catch{}};r(),zt=setInterval(r,2e3)}stopScreenshots(s){zt&&(clearInterval(zt),zt=null)}}let vt=null;function Lm(t){return(!vt||vt.daemonId!==t)&&(vt=new Rm(t)),vt}function Em({children:t}){const s=a.useRef(nr()),r=nr();s.current=r;const{setUserName:n}=Yt(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,u]=a.useState("disconnected"),m=a.useCallback((d,b)=>{u(d),Is==null||Is(d,b)},[]),x=a.useRef(null),p=a.useRef(),h=a.useRef(ka),g=a.useRef(!0),S=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{g.current=!0,S.current=!1;function d(){var l,C;if(!g.current||((l=x.current)==null?void 0:l.readyState)===WebSocket.OPEN||((C=x.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${Js}...`),ws("connect_attempt",{url:Js,reason:I.current,delayMs:h.current});let y;try{y=new WebSocket(Js)}catch(M){console.error("[Standalone WS] Failed to create WebSocket:",M),b();return}x.current=y,y.onopen=()=>{if(!g.current){y.close();return}m("connected"),h.current=ka,ws("open",{url:Js,reason:I.current}),$t.resubscribeAll({sendData:Jr}),console.log("[Standalone WS] Connected")},Mt=y,y.onmessage=M=>{var N,f;try{const w=JSON.parse(M.data);if((w.type==="command_result"||w.type==="error")&&w.requestId){const v=lr.get(w.requestId);v&&(lr.delete(w.requestId),w.type==="error"?v.reject(new Error(((N=w.data)==null?void 0:N.message)||"Command failed")):v.resolve(w.data));return}if(w.type==="session_output"){const v=w.sessionId||w.cliId||w.cliType;v&&Tt.emitSessionOutput(v,typeof w.data=="string"?w.data:"",typeof w.seq=="number"?w.seq:void 0);return}if(w.type==="runtime_snapshot"){Tt.emitRuntimeSnapshot(w.sessionId,typeof w.text=="string"?w.text:"",typeof w.seq=="number"?w.seq:0,!!w.truncated);return}if(w.type==="topic_update"){const v=w.update;v&&$t.publish(v);return}if(w.type==="status"||w.type==="initial_state"){const v=w.data;if(!v)return;const{injectEntries:k,markLoaded:$,getIdes:L}=s.current,B=v.instanceId||"standalone",A=L().find(j=>j.id===B),q=Lm(B);Tt.register(B,q),Tt.setState(B,"connected"),m("connected",B),Tt.emitStatus(B,v);const R=or(v,{daemonId:B,existingDaemon:A,existingEntries:L()});Na("ws_status",{type:w.type,daemonId:B,sessions:(v.sessions||[]).map(j=>({id:j.id,parentId:j.parentId,providerType:j.providerType,kind:j.kind,transport:j.transport,unread:j.unread,inboxBucket:j.inboxBucket,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,title:j.title})),recentLaunches:(v.recentLaunches||[]).map(j=>({id:j.id,providerType:j.providerType,kind:j.kind,workspace:j.workspace,lastLaunchedAt:j.lastLaunchedAt}))}),Na("entries",{daemonId:B,entries:R.filter(j=>j.type!=="adhdev-daemon").map(j=>({id:j.id,type:j.type,unread:j.unread,inboxBucket:j.inboxBucket,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,sessionId:j.sessionId}))}),R.length>0&&k(R,{authoritativeDaemonIds:[B]}),$(),c.current!==B&&((f=i.current)==null||f.call(i),c.current=B,i.current=$t.subscribe({sendData:Jr},B,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${B}`,params:{includeSessions:!0}},j=>{if(j.topic!=="daemon.metadata")return;const K=s.current.getIdes(),Y=K.find(E=>E.id===B),_=or(j.status,{daemonId:B,existingDaemon:Y,existingEntries:K,timestamp:j.timestamp});_.length>0&&s.current.injectEntries(_),j.userName&&o.current&&o.current(j.userName)}))}}catch(w){console.error("[Standalone WS] Parse error:",w)}},y.onclose=M=>{g.current&&(vt==null||vt.stopScreenshots(),vt&&Tt.setState(vt.daemonId,"disconnected"),m("disconnected"),x.current=null,I.current=`close:${M.code}${M.wasClean?":clean":":unclean"}`,ws("close",{code:M.code,reason:M.reason||"",wasClean:M.wasClean}),b())},y.onerror=M=>{S.current||!g.current||(I.current="error",ws("error",{message:M instanceof Event?"event":String(M),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",M))}}function b(){if(!g.current)return;clearTimeout(p.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),ws("schedule_reconnect",{reason:I.current,delayMs:y}),p.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,_m),d()},y)}return d(),()=>{var y;g.current=!1,S.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),x.current&&(x.current.onerror=null,x.current.onclose=null,x.current.close(),x.current=null,Mt=null),vt&&(vt.stopScreenshots(),Tt.unregister(vt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function Dm({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Is=(c,u)=>{r(c),u&&o(u)},()=>{Is=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",u=Pm(s),m={};return n&&(m[n]=u),m.standalone=u,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return e.jsx(_i,{connectionOverrides:i,children:e.jsx(Em,{children:t})})}const $m=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Ra,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(dr,{}),label:"Settings"}];function Bm({children:t}){const s=ds(),r=Zr(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),u=p=>{s(p),o(!1)},m=()=>{c(p=>{const h=!p;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},x=p=>`nav-item${r.pathname.startsWith(p)?" 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:p=>p.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:$m.map(p=>e.jsxs("div",{className:x(p.path),id:`nav-${p.id}`,onClick:()=>u(p.path),title:i?p.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.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(La,{})}),!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(Ea,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.41"]}),e.jsx(Xl,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,title:i?"Expand sidebar":"Collapse sidebar",children:[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 Km=[{icon:e.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Lt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(Da,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(xt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Ms,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(La,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Wm=[{icon:e.jsx(Ka,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Ra,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(mr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx($i,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(en,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Ki,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Om=[{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 Um(){return e.jsxs(fo,{icon:e.jsx(Ea,{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.41"]}),children:[e.jsx(St,{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(St,{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:Km.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(St,{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:uo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:lo.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(St,{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:Wm.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(St,{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:Om.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(xo,{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(Qi,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function zm(){const{ides:t}=Yt(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=bt(),{userName:o}=Yt(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const u=h=>{const g=h.target.value.trim();s!=null&&s.id&&g!==o&&n(s.id,"set_user_name",{userName:g}).catch(console.error)},[m,x]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=h=>{x(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(fo,{icon:e.jsx(dr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(Hl,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(St,{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.41"]}),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(St,{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(St,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(ed,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(St,{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(nd,{})]}),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(fd,{})]})]})}),e.jsx(St,{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(Jl,{}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Zi,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),e.jsx(St,{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(Di,{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:u,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}Yl();dd();const Hm=Ta({baseUrl:""});function Sa(){const{ides:t,initialLoaded:s}=Yt();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(Ur,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Ur,{to:"/dashboard",replace:!0})}function Fm(){return e.jsx(Ni,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Ri,{client:Hm,children:e.jsx(Dm,{children:e.jsx(Ei,{value:{sendCommand:sr,sendData:Jr},children:e.jsx(Bm,{children:e.jsxs(Si,{children:[e.jsx(Ot,{path:"/dashboard",element:e.jsx(om,{})}),e.jsx(Ot,{path:"/machine",element:e.jsx(Sa,{})}),e.jsx(Ot,{path:"/machines/:id",element:e.jsx(Im,{})}),e.jsx(Ot,{path:"/machines",element:e.jsx(Sa,{})}),e.jsx(Ot,{path:"/about",element:e.jsx(Um,{})}),e.jsx(Ot,{path:"/settings",element:e.jsx(zm,{})}),e.jsx(Ot,{path:"*",element:e.jsx(Ur,{to:"/dashboard",replace:!0})})]})})})})})})}sl({connectionManager:Tt});Ci(document.getElementById("root")).render(e.jsx(Fm,{}));