@adhdev/daemon-standalone 0.8.33 → 0.8.34

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,58 +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 Ri=Object.defineProperty;var Ei=(t,s,r)=>s in t?Ri(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var Ye=(t,s,r)=>Ei(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as ra,a as na,b as $i,c as Di,u as us,R as He,d as aa,t as Bi,e as Ki,D as Wi,f as Oi,g as Fi,h as Rr,i as Ui,k as zi,B as Vi,l as Hi,m as Mt,N as Cr,n as qi}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();const ia=a.createContext({ides:[],updateIdeChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),oa=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function cn(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 ur(t,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},i=s.version??r.version??t.version,o=s.serverVersion??t.serverVersion??r.serverVersion,c=s.versionMismatch===!0||t.versionMismatch===!0;return i&&(n.version=i),o&&(n.serverVersion=o),i&&o&&i===o?(delete n.versionMismatch,delete n.serverVersion,n):((s.versionMismatch===!0||c&&i&&o&&i!==o)&&(n.versionMismatch=!0),n)}function Ys(t){return Array.isArray(t)?t.map(Ys):!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,Ys(r)]))}function Gi(t,s){try{return JSON.stringify(Ys(t))===JSON.stringify(Ys(s))}catch{return!1}}function Ms(t,s,r){return Gi(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function Yi(t,s,r){var l,p,m,f,v,x,w;const n=Date.now(),i=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(u=>({...u,_lastUpdate:n}));const o=new Map;for(const u of s)o.set(u.id,u);for(const u of t){const k=o.get(u.id);if(!k){o.set(u.id,{...u,_lastUpdate:n});continue}const g=cn(u),b=cn(k);if(g>b){const C=(l=u.chats)!=null&&l.length?u.chats:k.chats,I=ur(k,u,{...k,...u,chats:C,_lastUpdate:n});o.set(u.id,Ms(k,I,n))}else if(g<b){const C={};if(u.status&&u.status!==k.status&&(C.status=u.status),u.cdpConnected!==void 0&&(C.cdpConnected=u.cdpConnected),(p=u.chats)!=null&&p.length&&!((m=k.chats)!=null&&m.length)&&(C.chats=u.chats),u.machineNickname!==void 0&&u.machineNickname!==k.machineNickname&&(C.machineNickname=u.machineNickname),u.version!==void 0&&(C.version=u.version),u.serverVersion!==void 0&&(C.serverVersion=u.serverVersion),u.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const I=ur(k,u,{...k,...C,_lastUpdate:k._lastUpdate});o.set(u.id,Ms(k,I,n))}else Ms(k,{...k,_lastUpdate:k._lastUpdate},n)}else{const C=u.timestamp||n,I=k._lastUpdate||k.timestamp||0;if(C>=I){const N=(f=u.chats)!=null&&f.length?u.chats:k.chats,h=ur(k,u,{...k,...u,chats:N,_lastUpdate:n});o.set(u.id,Ms(k,h,n))}else(v=u.chats)!=null&&v.length&&!((x=k.chats)!=null&&x.length)&&o.set(u.id,{...k,chats:u.chats})}}const c=new Set(t.map(u=>u.id)),d=new Set;for(const u of t){const k=u.daemonId||((w=u.id)==null?void 0:w.split(":")[0]);k&&d.add(k)}for(const[u,k]of o){const g=k.daemonId||u.split(":")[0];if(!d.has(g))continue;if(i.has(g)&&!c.has(u)){o.delete(u);continue}const b=n-(k._lastUpdate||k.timestamp||0);(k.transport==="pty"&&!c.has(u)&&b>1e4||k.transport==="acp"&&!c.has(u)&&b>1e4||k.transport==="cdp-page"&&!c.has(u)&&b>3e4)&&o.delete(u)}for(const[u,k]of o)n-(k._lastUpdate||k.timestamp||0)>3e5&&k.status!=="online"&&o.delete(u);return Array.from(o.values())}function Xi(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 Ji({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[i,o]=a.useState(!1),[c,d]=a.useState([]),[l,p]=a.useState(void 0),m=a.useRef(r);a.useEffect(()=>{m.current=r},[r]);const f=a.useCallback((g,b)=>{n(C=>{let I=!1;const N=C.map(h=>h.id!==g||h.chats===b?h:(I=!0,{...h,chats:b}));return I?N:C})},[]),v=a.useCallback((g,b)=>{n(C=>{const I=C.length===0?g:Yi(g,C,b);return Xi(C,I)?C:I})},[]),x=a.useCallback(()=>o(!0),[]),w=a.useMemo(()=>({injectEntries:v,markLoaded:x,getIdes:()=>m.current}),[v,x]),u=s,k=a.useMemo(()=>({ides:r,updateIdeChats:f,initialLoaded:i,toasts:c,setToasts:d,wsStatus:(u==null?void 0:u.wsStatus)??"connected",isConnected:(u==null?void 0:u.isConnected)??!0,connectionStates:(u==null?void 0:u.connectionStates)??{},connectionTransports:(u==null?void 0:u.connectionTransports)??{},showReconnected:(u==null?void 0:u.showReconnected)??!1,retryConnection:u==null?void 0:u.retryConnection,isP2PActive:(u==null?void 0:u.isP2PActive)??!1,p2pStates:(u==null?void 0:u.p2pStates)??{},userRole:u==null?void 0:u.userRole,userName:l,setUserName:p}),[r,f,i,c,u==null?void 0:u.wsStatus,u==null?void 0:u.isConnected,u==null?void 0:u.connectionStates,u==null?void 0:u.connectionTransports,u==null?void 0:u.showReconnected,u==null?void 0:u.retryConnection,u==null?void 0:u.isP2PActive,u==null?void 0:u.p2pStates,u==null?void 0:u.userRole,l]);return e.jsx(oa.Provider,{value:w,children:e.jsx(ia.Provider,{value:k,children:t})})}function Gt(){return a.useContext(ia)}function ln(){return a.useContext(oa)}function ca(t){const{baseUrl:s,getToken:r,onUnauthorized:n}=t;function i(d){return d.startsWith("http")?d:`${s}${d.startsWith("/")?"":"/"}${d}`}function o(d){const l=r==null?void 0:r(),p=i(d),m=d.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return l&&m.searchParams.set("token",l),!d.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(d,l={}){const p={"Content-Type":"application/json",...l.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const f=i(d),v=new AbortController,x=setTimeout(()=>v.abort(),15e3);try{const w=await fetch(f,{...l,headers:p,signal:v.signal});if(w.status===401)throw n==null||n(),new Error("Unauthorized");if(!w.ok){const u=await w.json().catch(()=>({error:w.statusText}));throw new Error(u.error||`API Error: ${w.status}`)}return w.json()}finally{clearTimeout(x)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,l,p={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:l,payload:p})}),execTerminal:(d,l,p)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:l,name:p})}),sendAgentMessage:(d,l,p)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:l,message:p})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,l,p)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:l,action:p?"approve":"reject"})}),getMuxState:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/state`),getMuxSocketInfo:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/socket-info`),controlMux:(d,l,p={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:l,payload:p})}),getMuxEventsUrl:d=>o(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>o(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const Zi=ca({baseUrl:"http://localhost:3847"}),Qi=a.createContext(Zi);function eo({client:t,children:s}){return e.jsx(Qi.Provider,{value:t,children:s})}const to={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},la=a.createContext(to);function so({value:t,children:s}){return e.jsx(la.Provider,{value:t,children:s})}function $t(){return a.useContext(la)}const Pe={size:18};function da({size:t=Pe.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 Er({size:t=Pe.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 Pt({size:t=Pe.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 $r({size:t=Pe.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 ro({size:t=Pe.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 no({size:t=Pe.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 Xs({size:t=Pe.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 ao({size:t=Pe.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 er({size:t=Pe.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 ua({size:t=Pe.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 ma({size:t=Pe.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 Tt({size:t=Pe.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 ct({size:t=Pe.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 Dr({size:t=Pe.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 io({size:t=Pe.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 ls({size:t=Pe.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 ms({size:t=Pe.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 Lt({size:t=Pe.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 Yt({size:t=Pe.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 pa({size:t=Pe.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 oo({size:t=Pe.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 Br({size:t=Pe.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 co({size:t=Pe.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 Is({size:t=Pe.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 lo({size:t=Pe.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 Kr({size:t=Pe.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 uo({size:t=Pe.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 Rt({size:t=Pe.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 xa({size:t=Pe.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 mo({size:t=Pe.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 po({size:t=Pe.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 xo({size:t=Pe.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 tr({size:t=Pe.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 fo({size:t=Pe.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 ho({size:t=Pe.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 bo({size:t=Pe.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 go({size:t=Pe.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 dn(t){return!!t&&typeof t=="object"&&"text"in t}function Wr(t,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let i="";return typeof t=="string"?i=t:Array.isArray(t)?i=t.map(o=>typeof o=="string"?o:dn(o)?String(o.text||""):"").join(r):dn(t)?i=String(t.text||""):i=String(t||""),n?i.replace(/\s+/g," ").trim():i}function Xt(t){return Wr(t,{normalizeWhitespace:!0})}function fa(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function yo(t,s,r){return Number(t.receivedAt||r[as(t,s)]||0)||0}function vo(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function as(t,s){const r=t,n=Wr(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 un=5e3,wo=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(ra,{remarkPlugins:[na],children:s.text}),e.jsx("span",{className:"action-time",children:fa(s.timestamp)})]})},(t,s)=>t.log===s.log),jo=a.memo(function({message:s,receivedAt:r,agentName:n,userName:i,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:d}){var I,N,h;const l=(s.role||"").toLowerCase(),p=l==="user"||l==="human",m=s.kind||(l==="tool"?"tool":"standard"),f=Wr(s.content,{joiner:`
4
- `});if(m==="thought"){const y=typeof((I=s.meta)==null?void 0:I.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(po,{size:13}),e.jsx("span",{children:y})]}),e.jsx("div",{className:"chat-msg-body",children:f})]})}if(m==="tool")return e.jsxs("div",{className:"self-start chat-msg-tool",children:[e.jsx("span",{className:"tool-icon",children:"⏺"}),e.jsx("span",{className:"tool-text",children:f.split(`
5
- `)[0].slice(0,80)})]});if(m==="terminal"){const y=(N=s.meta)!=null&&N.isRunning?"⏳":"✅",j=typeof((h=s.meta)==null?void 0:h.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:y}),e.jsx("span",{children:j})]}),e.jsx("pre",{className:"chat-msg-body",children:f})]})}if(m==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:f.slice(0,100)});const v=s.meta,w=(typeof(v==null?void 0:v.renderMode)=="string"?v.renderMode.trim():"")==="preformatted",u=f,k=o&&!p&&!w&&u.length>un,g=k&&!c?u.slice(0,un):u,b=w,C=!b&&vo(g);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(u||p)&&e.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${u?"mb-1.5":"mb-0"}`,children:[e.jsx("span",{className:"chat-sender",children:p?i||"You":s.senderName||n}),r!=null&&e.jsx("span",{className:"chat-time",children:fa(r)})]}),u&&e.jsx("div",{className:"chat-markdown",children:b?e.jsx("pre",{className:"chat-preformatted",children:g}):C?e.jsx(ra,{remarkPlugins:[na,$i,Di],children:g}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:g})}),k&&e.jsx("button",{onClick:d,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(u.length/100)*100} chars) ↓`})]})})},(t,s)=>t.message===s.message&&t.receivedAt===s.receivedAt&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isTextExpanded===s.isTextExpanded),ko=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:i,isCliMode:o=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:l={},emptyState:p,onLoadMore:m,isLoadingMore:f,hasMoreHistory:v,hiddenLiveCount:x=0,loadError:w,scrollToBottomRequestNonce:u},k){var ke;const g=a.useRef(null),b=a.useRef(null),C=a.useRef(null),I=a.useRef(0),N=a.useRef(""),h=a.useRef(!1),y=a.useRef(null),j=a.useRef(!1),S=a.useRef(null),E=a.useRef(!1),[D,O]=a.useState(new Set),_=a.useRef(!1),P=()=>{const X=g.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<200:!0},T=a.useCallback((X="auto")=>{const Z=g.current;Z&&Z.scrollTo({top:Z.scrollHeight,behavior:X})},[]),L=a.useCallback(()=>{var re;const X=g.current,Z=(re=window.getSelection)==null?void 0:re.call(window);if(!X||!Z||Z.rangeCount===0||Z.isCollapsed){E.current=!1;return}const G=Z.anchorNode,fe=Z.focusNode;E.current=!!(G&&fe&&X.contains(G)&&X.contains(fe))},[]),B=a.useCallback((X="auto")=>{y.current!=null&&cancelAnimationFrame(y.current),y.current=requestAnimationFrame(()=>{y.current=null,T(X)})},[T]),J=s.length>0?`${s.length}:${(((ke=s[s.length-1])==null?void 0:ke.content)||"").length}`:"0:0";a.useEffect(()=>{const X=!h.current,Z=N.current!==d;if(N.current=d,X||Z){h.current=!0,_.current=!1,j.current=!0,E.current||B("auto"),I.current=s.length;return}s.length>I.current?!_.current&&!E.current&&B("auto"):P()&&!_.current&&!E.current&&B("auto"),I.current=s.length},[J,d,c,s.length,B]),a.useEffect(()=>{u&&(_.current=!1,j.current=!0,S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{j.current=!1,S.current=null},180),E.current||B("auto"))},[B,u]),a.useEffect(()=>()=>{y.current!=null&&cancelAnimationFrame(y.current),S.current!=null&&window.clearTimeout(S.current)},[]),a.useEffect(()=>{const X=b.current;if(!X)return;const Z=()=>{S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{j.current=!1,S.current=null},180)},G=new ResizeObserver(()=>{j.current&&(E.current||(B("auto"),Z()))});return G.observe(X),()=>{G.disconnect(),S.current!=null&&(window.clearTimeout(S.current),S.current=null)}},[B,d]),a.useImperativeHandle(k,()=>({scrollToBottom:(X="smooth")=>{T(X)}}),[T]),a.useEffect(()=>{const X=g.current;if(!X)return;let Z;const G=()=>{clearTimeout(Z),Z=setTimeout(()=>{_.current=!P()},50)};return X.addEventListener("scroll",G,{passive:!0}),()=>{X.removeEventListener("scroll",G),clearTimeout(Z)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",L),()=>document.removeEventListener("selectionchange",L)),[L]);const K=a.useRef(0),$=a.useRef(!1);a.useEffect(()=>{const X=g.current;if(!X||!$.current||K.current===0)return;const Z=X.scrollHeight-K.current;Z>0&&(X.scrollTop=Z),K.current=0,$.current=!1},[s.length]);const W=()=>{const X=g.current;X&&(K.current=X.scrollHeight),$.current=!0,m==null||m()},V=a.useMemo(()=>{const X=s.map((re,he)=>({type:"message",data:re,index:he,ts:yo(re,he,l)}));if(!r||r.length===0)return X;const Z=[...r].sort((re,he)=>re.timestamp-he.timestamp).map((re,he)=>({type:"action",data:re,index:he,ts:re.timestamp})),G=[];let fe=0;for(const re of X){for(;fe<Z.length&&re.ts>0&&Z[fe].ts<re.ts;)G.push(Z[fe++]);G.push(re)}for(;fe<Z.length;)G.push(Z[fe++]);return G},[s,r,l]),H=x>0||!!v,te=x>0?`↑ Show ${Math.min(x,80)} earlier messages${x>80?` (${x} hidden)`:""}`:w?`↻ ${w}`:"↑ Load older messages";return e.jsx("div",{ref:g,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:b,className:"chat-container-content",children:[f&&e.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),H&&!f&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:W,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${w&&x===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:te})}),V.length===0&&!H&&(p||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),V.map(X=>{if(X.type==="action"){const ie=X.data;return e.jsx(wo,{log:ie},`action-${X.index}`)}const Z=X.data,G=X.index,fe=as(Z,G),re=Z.receivedAt||l[fe],he=`${d}-${fe}`,ve=D.has(he);return e.jsx(jo,{message:Z,receivedAt:re,agentName:n,userName:i,isCliMode:o,isTextExpanded:ve,onToggleTextExpanded:()=>O(ie=>{const pe=new Set(ie);return ve?pe.delete(he):pe.add(he),pe})},`msg-${fe}`)}),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})]})})}),No=a.memo(ko,(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),So="modulepreload",Co=function(t){return"/"+t},mn={},Io=function(s,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(l=>{if(l=Co(l),l in mn)return;mn[l]=!0;const p=l.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${m}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":So,p||(f.as="script"),f.crossOrigin="",f.href=l,d&&f.setAttribute("nonce",d),document.head.appendChild(f),p)return new Promise((v,x)=>{f.addEventListener("load",v),f.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return i.then(c=>{for(const d of c||[])d.status==="rejected"&&o(d.reason);return s().catch(o)})};let pn=!1;const ha=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},i)=>{const o=a.useRef(null),[c,d]=a.useState(null),l=a.useRef([]),p=a.useRef(!1),m=a.useRef(!1),f=a.useRef(!1),v=()=>{const x=o.current;if(x){p.current&&(x.clear(),p.current=!1);for(const w of l.current)x.write(w);l.current=[],m.current&&(x.fit(),m.current=!1),f.current&&(x.bumpResize(),f.current=!1)}};return a.useImperativeHandle(i,()=>({write:x=>{o.current?o.current.write(x):l.current.push(x)},clear:()=>{o.current?o.current.clear():(l.current=[],p.current=!0)},reset:()=>{o.current&&typeof o.current.reset=="function"?o.current.reset():(l.current=[],p.current=!0)},resize:(x,w)=>{o.current&&typeof o.current.resize=="function"&&o.current.resize(x,w)},fit:()=>{o.current?o.current.fit():m.current=!0},bumpResize:()=>{o.current?o.current.bumpResize():f.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const x=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(x)},[c]),a.useEffect(()=>{let x=!1;return Io(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(w=>{pn||(pn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||d(()=>w.GhosttyTerminalView)}).catch(w=>{console.error("[CliTerminal] failed to load terminal renderer",w)}),()=>{x=!0}},[]),c?e.jsx(c,{ref:o,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"}})});ha.displayName="CliTerminal";function Ps({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 xn({value:t,max:s,label:r,color:n="#8b5cf6",detail:i,compact:o=!1}){const c=s>0?Math.min(Math.round(t/s*100),100):0,d=c>85?"#ef4444":c>60?"var(--status-warning)":n;return o?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:d}})})]}):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, ${d}, ${d}cc)`}})}),i&&e.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:i})]})}function _o({cursorPos:t,viewportRef:s,imgRef:r}){var b;if(!t||!r.current)return null;const n=r.current,i=n.getBoundingClientRect(),o=(b=s.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||i.width,d=n.naturalHeight||i.height,l=c/d,p=i.width/i.height;let m,f,v,x;l>p?(m=i.width,f=i.width/l,v=0,x=(i.height-f)/2):(f=i.height,m=i.height*l,v=(i.width-m)/2,x=0);const w=i.left-o.left+v+m*t.nx,u=i.top-o.top+x+f*t.ny,k=Math.max(8,Math.min(o.width-8,w)),g=Math.max(8,Math.min(o.height-8,u));return e.jsxs("div",{style:{position:"absolute",left:k-8,top:g-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 To({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:i,setIsMenuOpen:o,imeText:c,setImeText:d,handleImeSubmit:l,isConnActive:p,zoom:m,isMobile:f,mobileFillZoom:v,onZoomOut:x,onZoomReset:w,onZoomIn:u,transportType:k,screenshotUsage:g,lastActionStatus:b}){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),o(!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=>d(C.target.value),onKeyDown:C=>{l(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:()=>{o(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${i?"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:p?"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:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),e.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),k==="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"}),k==="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"}),g&&g.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:g.budgetExhausted?"#ef4444":"#c4b5fd",background:g.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:g.budgetExhausted?"TURN blocked":`TURN ${g.dailyUsedMinutes}/${g.dailyBudgetMinutes}m`}),b&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),i&&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: ",m<=(f?v:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:C=>{C.stopPropagation(),x()},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(),w()},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:f?"FILL":"FIT"}),e.jsx("button",{onClick:C=>{C.stopPropagation(),u()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Ao({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 Mo(){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 fn(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 _s(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!Mo())return;n.current+=1;const i=r.current;if(!i){console.debug(`[render-trace] ${t}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,d])=>[c,fn(d)]))}),r.current=s;return}const o=Object.keys({...i,...s}).filter(c=>!Object.is(i[c],s[c]));o.length>0&&console.debug(`[render-trace] ${t}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,fn(s[c])]))}),r.current=s})}function Po({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:i,minZoom:o,zoomRef:c,panXRef:d,panYRef:l,setPanX:p,setPanY:m,setZoom:f,lastWheelTimeRef:v,onAction:x,setLastActionStatus:w,spawnRippleFromNormalized:u,clampPan:k,isMobile:g,mobileFillZoom:b}){const[C,I]=a.useState(null),N=a.useRef(null),h=a.useRef(null),y=a.useRef(null),j=a.useRef(!1),S=a.useRef(null),E=a.useRef(0),D=a.useRef(null),O=a.useRef(1),_=a.useRef({x:0,y:0}),P=a.useRef(!1),T=a.useRef(n),L=a.useRef(x),B=30,J=550,K=18,$=60,W=400,V=12,H=()=>{if(N.current)return;const X={nx:.5,ny:.5};N.current=X,I(X)};return a.useEffect(()=>{T.current=n,n==="mouse"&&H()},[n]),a.useEffect(()=>{L.current=x},[x]),a.useEffect(()=>{const X=t.current;if(!X)return;const Z=ie=>{if(!r.current)return null;const pe=r.current.getBoundingClientRect();return!pe.width||!pe.height?null:{nx:Math.max(0,Math.min(1,(ie.clientX-pe.left)/pe.width)),ny:Math.max(0,Math.min(1,(ie.clientY-pe.top)/pe.height))}},G=(ie,pe)=>{if(!r.current)return{dnx:0,dny:0};const oe=r.current,ge=oe.getBoundingClientRect(),Y=oe.naturalWidth||ge.width,se=oe.naturalHeight||ge.height,Q=Y/se,xe=ge.width/ge.height;let M,ee;return Q>xe?(M=ge.width,ee=ge.width/Q):(ee=ge.height,M=ge.height*Q),{dnx:ie/M,dny:pe/ee}},fe=(ie,pe,oe)=>{if(oe<=1.05)return;const ge=-(ie-.5)*100,Y=-(pe-.5)*100,se=k(ge,Y,oe);(Math.abs(se.x-d.current)>.1||Math.abs(se.y-l.current)>.1)&&(p(se.x),m(se.y),d.current=se.x,l.current=se.y)},re=ie=>{const pe=s.current;if(pe&&ie.target instanceof Node&&pe.contains(ie.target))ie.preventDefault();else return;if(ie.touches.length===1){const oe=ie.touches[0];h.current={x:oe.clientX,y:oe.clientY,time:Date.now()},y.current={x:oe.clientX,y:oe.clientY},P.current||(j.current=!1),S.current=setTimeout(()=>{if(!j.current&&!P.current)if(j.current=!0,T.current==="mouse"){const ge=N.current||{nx:.5,ny:.5};w("Right Click"),u(ge.nx,ge.ny,"right"),L.current("input_click",{...ge,button:"right"}).catch(()=>{})}else{const ge=Z(oe);ge&&(w("Right Click"),u(ge.nx,ge.ny,"right"),L.current("input_click",{...ge,button:"right"}).catch(()=>{}))}},500);return}if(ie.touches.length===2){S.current&&clearTimeout(S.current),j.current=!0,P.current=!0;const oe=ie.touches[1].clientX-ie.touches[0].clientX,ge=ie.touches[1].clientY-ie.touches[0].clientY;D.current=Math.sqrt(oe*oe+ge*ge),O.current=c.current,_.current={x:(ie.touches[0].clientX+ie.touches[1].clientX)/2,y:(ie.touches[0].clientY+ie.touches[1].clientY)/2}}},he=ie=>{const pe=s.current;if(pe&&ie.target instanceof Node&&pe.contains(ie.target)&&ie.preventDefault(),ie.touches.length===1&&y.current){const oe=ie.touches[0],ge=oe.clientX-y.current.x,Y=oe.clientY-y.current.y;if(!j.current&&h.current){const se=oe.clientX-h.current.x,Q=oe.clientY-h.current.y;Math.sqrt(se*se+Q*Q)>8&&(j.current=!0,S.current&&clearTimeout(S.current))}if(j.current)if(T.current==="mouse"){const se=G(ge,Y),Q=N.current||{nx:.5,ny:.5},xe=Math.max(0,Math.min(1,Q.nx+se.dnx)),M=Math.max(0,Math.min(1,Q.ny+se.dny));N.current={nx:xe,ny:M},I({nx:xe,ny:M}),w(`Cursor: ${Math.round(xe*100)}%, ${Math.round(M*100)}%`),fe(xe,M,c.current);const ee=Date.now();ee-v.current>=30&&(v.current=ee,L.current("input_mouseMoved",{nx:xe,ny:M}).catch(()=>{}))}else if(c.current>1){const se=s.current;if(se){const Q=se.clientWidth,xe=se.clientHeight,M=d.current+ge/Q*100,ee=l.current+Y/xe*100,ye=k(M,ee,c.current);p(ye.x),m(ye.y),d.current=ye.x,l.current=ye.y}}else{const se=Z(oe);if(se){const Q=Date.now();Q-v.current>=40&&(v.current=Q,w("Scroll"),L.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-ge*2.5),deltaY:Math.round(-Y*2.5)}).catch(()=>{}))}}y.current={x:oe.clientX,y:oe.clientY};return}if(ie.touches.length===2&&D.current!==null){const oe=ie.touches[1].clientX-ie.touches[0].clientX,ge=ie.touches[1].clientY-ie.touches[0].clientY,se=Math.sqrt(oe*oe+ge*ge)/D.current,Q=(ie.touches[0].clientX+ie.touches[1].clientX)/2,xe=(ie.touches[0].clientY+ie.touches[1].clientY)/2,M=Q-_.current.x,ee=xe-_.current.y,ye=Math.abs(se-1)>.03;if(T.current==="mouse"){if(ye){const A=Math.max(o,Math.min(5,O.current*se));f(A),c.current=A}else if(Math.abs(M)>2||Math.abs(ee)>2){const A=N.current||{nx:.5,ny:.5},q=Date.now();q-v.current>=30&&(v.current=q,w("Scroll"),L.current("input_wheel",{nx:A.nx,ny:A.ny,deltaX:Math.round(-M*3),deltaY:Math.round(-ee*3)}).catch(()=>{}))}}else{const A=Math.max(o,Math.min(5,O.current*se));f(A),c.current=A;const q=s.current;if(q&&A>1){const F=q.clientWidth,ae=q.clientHeight,de=d.current+M/F*100,Ce=l.current+ee/ae*100,Ee=k(de,Ce,A);p(Ee.x),m(Ee.y),d.current=Ee.x,l.current=Ee.y}}_.current={x:Q,y:xe}}},ve=ie=>{var pe;if(S.current&&clearTimeout(S.current),D.current=null,ie.touches.length===1&&P.current){const oe=ie.touches[0];h.current={x:oe.clientX,y:oe.clientY,time:Date.now()},y.current={x:oe.clientX,y:oe.clientY},j.current=!0;return}if(ie.touches.length===0){if(P.current){P.current=!1,j.current=!1;return}if(ie.changedTouches.length===1){const oe=ie.changedTouches[0],ge=Date.now(),Y=ge-(((pe=h.current)==null?void 0:pe.time)||0),se=h.current?oe.clientX-h.current.x:0,Q=h.current?oe.clientY-h.current.y:0,xe=Math.sqrt(se*se+Q*Q);if(T.current==="mouse"){if(Y<B||Y>J||xe>K){j.current=!1;return}const M=N.current||Z(oe);M&&(w(`Click: ${Math.round(M.nx*100)}%, ${Math.round(M.ny*100)}%`),u(M.nx,M.ny,"left"),L.current("input_click",{...M}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(Y<$||Y>W||xe>V){j.current=!1;return}const M=Z(oe);if(!M)return;ge-E.current<300?(w("Double tap"),u(M.nx,M.ny,"double"),L.current("input_click",{...M,clickCount:2}).catch(()=>{}),E.current=0):(w(`Tap: ${Math.round(M.nx*100)}%, ${Math.round(M.ny*100)}%`),u(M.nx,M.ny,"left"),L.current("input_click",{...M}).catch(()=>{}),E.current=ge)}}j.current=!1}};return X.addEventListener("touchstart",re,{passive:!1}),X.addEventListener("touchmove",he,{passive:!1}),X.addEventListener("touchend",ve,{passive:!1}),()=>{X.removeEventListener("touchstart",re),X.removeEventListener("touchmove",he),X.removeEventListener("touchend",ve),S.current&&clearTimeout(S.current)}},[t,s,r,o,c,d,l,p,m,f,v,w,u,k]),{cursorPos:C,cursorPosRef:N,handleToggleInputMode:()=>{i(X=>{const Z=X==="touch"?"mouse":"touch";return Z==="mouse"&&H(),Z})},handleZoomReset:()=>{const X=g?b:1;f(X),c.current=X,p(0),m(0),d.current=0,l.current=0}}}function ba({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:i,transportType:o}){const c=a.useRef(null),d=a.useRef(null),l=a.useRef(null),[p,m]=a.useState(null),[f,v]=a.useState(""),[,x]=a.useState(!1),[w,u]=a.useState([]),k=a.useRef(0),[g,b]=a.useState(!1),[C,I]=a.useState(!1),N=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[h,y]=a.useState(N?"mouse":"touch"),[j,S]=a.useState(1),E=a.useRef(!1),[D,O]=a.useState(1),[_,P]=a.useState(0),[T,L]=a.useState(0);_s("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:h,zoom:D,panX:_,panY:T,isMenuOpen:g,isImeOpen:C});const B=a.useRef(0),J=a.useRef(D),K=a.useRef(_),$=a.useRef(T);a.useEffect(()=>{J.current=D},[D]),a.useEffect(()=>{K.current=_},[_]),a.useEffect(()=>{$.current=T},[T]),a.useEffect(()=>{var Y;(Y=c.current)==null||Y.focus()},[]);const W=r==="connected",V=n,H=W?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",te=W?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!N||E.current||!V)return;const Y=l.current,se=d.current;if(!Y||!se)return;const Q=()=>{const xe=se.clientWidth,M=se.clientHeight,ee=Y.naturalWidth,ye=Y.naturalHeight;if(!ee||!ye||!xe||!M)return;const A=Math.min(xe/ee,M/ye),F=Math.max(xe/ee,M/ye)/A;F>1.01&&(S(F),O(F),J.current=F),E.current=!0};Y.complete&&Y.naturalWidth?Q():Y.addEventListener("load",Q,{once:!0})},[V,N]);const ke=.5;a.useEffect(()=>{D<=ke&&(P(0),L(0))},[D,ke]);const X=(Y,se,Q)=>{if(Q<=ke)return{x:0,y:0};const xe=(Q-1)/(2*Q)*100,M=(Q-1)/(2*Q)*100;return{x:Math.max(-xe,Math.min(xe,Y)),y:Math.max(-M,Math.min(M,se))}},Z=(Y,se)=>{if(!l.current)return null;const Q=l.current.getBoundingClientRect();return!Q.width||!Q.height?null:{nx:Math.max(0,Math.min(1,(Y-Q.left)/Q.width)),ny:Math.max(0,Math.min(1,(se-Q.top)/Q.height))}},G=(Y,se,Q)=>{const xe=d.current;if(!xe)return;const M=xe.getBoundingClientRect(),ee=++k.current;u(ye=>[...ye,{id:ee,x:Y-M.left,y:se-M.top,type:Q}]),setTimeout(()=>u(ye=>ye.filter(A=>A.id!==ee)),600)},fe=(Y,se,Q)=>{const xe=l.current,M=d.current;if(!xe||!M)return;const ee=xe.getBoundingClientRect(),ye=M.getBoundingClientRect(),A=xe.naturalWidth||ee.width,q=xe.naturalHeight||ee.height,F=A/q,ae=ee.width/ee.height;let de,Ce,Ee,Ae;F>ae?(de=ee.width,Ce=ee.width/F,Ee=0,Ae=(ee.height-Ce)/2):(Ce=ee.height,de=ee.height*F,Ee=(ee.width-de)/2,Ae=0);const Fe=ee.left-ye.left+Ee+de*Y,xt=ee.top-ye.top+Ae+Ce*se,Xe=++k.current;u(We=>[...We,{id:Xe,x:Fe,y:xt,type:Q}]),setTimeout(()=>u(We=>We.filter(it=>it.id!==Xe)),600)},re=async Y=>{var Q;const se=Z(Y.clientX,Y.clientY);if(se){m(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),G(Y.clientX,Y.clientY,"left"),(Q=c.current)==null||Q.focus();try{const xe=await t("input_click",{nx:se.nx,ny:se.ny});xe!=null&&xe.success||s(`❌ Click failed: ${xe==null?void 0:xe.error}`)}catch(xe){s(`❌ Click error: ${xe.message||xe}`)}}},he=async(Y,se,Q,xe=0)=>{try{await t("input_key",{type:Q?"char":"keyDown",key:Y,code:se,text:Q?Y:void 0,unmodifiedText:Q?Y:void 0,modifiers:xe})}catch(M){s(`❌ Key error: ${M.message||M}`)}},ve=async Y=>{if(Y.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Y.key)&&Y.preventDefault();let Q=0;Y.altKey&&(Q|=1),Y.ctrlKey&&(Q|=2),Y.metaKey&&(Q|=4),Y.shiftKey&&(Q|=8),m(`Key: ${Y.key}`),await he(Y.key,Y.code,Y.key.length===1,Q)},ie=async Y=>{if(Y.key==="Enter"){if(Y.nativeEvent.isComposing)return;if(f){const se=f;v(""),m(`IME Sent: ${se}`);try{const Q=await t("input_type",{text:se});Q!=null&&Q.success||s(`❌ IME error: ${Q==null?void 0:Q.error}`)}catch(Q){s(`❌ IME error: ${Q.message}`)}}else m("Key: Enter"),await he("Enter","Enter",!1)}};a.useEffect(()=>{const Y=c.current;if(!Y)return;const se=Q=>{var xe;if((xe=l.current)!=null&&xe.contains(Q.target)){Q.preventDefault();const M=Date.now();if(M-B.current<40)return;B.current=M;const ee=Z(Q.clientX,Q.clientY);if(!ee)return;m(`Scroll: ${Math.round(Q.deltaY)}`),t("input_wheel",{nx:ee.nx,ny:ee.ny,deltaX:Math.round(Q.deltaX),deltaY:Math.round(Q.deltaY)}).catch(()=>{})}};return Y.addEventListener("wheel",se,{passive:!1}),()=>Y.removeEventListener("wheel",se)},[t]);const{cursorPos:pe,handleToggleInputMode:oe,handleZoomReset:ge}=Po({containerRef:c,viewportRef:d,imgRef:l,inputMode:h,setInputMode:y,minZoom:ke,zoomRef:J,panXRef:K,panYRef:$,setPanX:P,setPanY:L,setZoom:O,lastWheelTimeRef:B,onAction:t,setLastActionStatus:m,spawnRippleFromNormalized:fe,clampPan:X,isMobile:N,mobileFillZoom:j});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ve,onContextMenu:Y=>Y.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[V?e.jsx("img",{ref:l,src:V,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${D}) translate(${_}%, ${T}%)`,transformOrigin:"center center",cursor:h==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:re,onContextMenu:Y=>Y.preventDefault(),onDragStart:Y=>Y.preventDefault()}):e.jsx(Ao,{waitingLabel:H,waitingHint:te,transportType:o}),h==="mouse"&&V&&e.jsx(_o,{cursorPos:pe,viewportRef:d,imgRef:l}),w.map(Y=>{const Q={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Y.type];return e.jsxs("div",{style:{position:"absolute",left:Y.x,top:Y.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${Q}, 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(${Q}, 0.9)`,boxShadow:`0 0 12px rgba(${Q}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Y.id)})]}),e.jsx(To,{inputMode:h,onToggleInputMode:oe,isImeOpen:C,setIsImeOpen:I,isMenuOpen:g,setIsMenuOpen:b,imeText:f,setImeText:v,handleImeSubmit:ie,isConnActive:W,zoom:D,isMobile:N,mobileFillZoom:j,onZoomOut:()=>O(Y=>Math.max(.5,Y-.25)),onZoomReset:ge,onZoomIn:()=>O(Y=>Math.min(5,Y+.25)),transportType:o,screenshotUsage:i,lastActionStatus:p}),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 ga(t,s={}){if(!t)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:i=60}=s,o=Date.now()-t,c=Math.floor(o/1e3);if(c<i)return n;const d=Math.floor(c/60);if(d<60)return`${d}m${r}`;const l=Math.floor(d/60);if(l<24)return`${l}h${r}`;const p=Math.floor(l/24);return p<7?`${p}d${r}`:new Date(t).toLocaleDateString()}const ya=t=>ga(t);function Lo(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ps(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",i=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:i}}function Ts(t){const s=new Map,r=(n,i)=>{n&&s.set(n,{sessionId:n,...Lo(i)})};for(const n of t)if(!n.daemonMode){r(n.sessionId,n);for(const i of n.childSessions||[])r(i.id,i)}return s}function js(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 ks(t,s,r){const n=js(t,s),i=ps(t),o=i.isReconnecting,c=i.isConnecting,d=i.isGenerating,l=i.isWaiting,p=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||l,m=n.inboxBucket==="working"||d,f=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:f,requiresAction:p,isWorking:m,isReconnecting:o,isConnecting:c,isGenerating:d,isWaiting:l,inboxBucket:p?"needs_attention":m?"working":f?"task_complete":"idle"}}function Ro(t,s,r){return ks(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Eo(t,s,r){return js(t,r||new Map).surfaceHidden}function va({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ps(t).isWaiting||!t.modalButtons)return null;const o=d=>{r||(n(d),s(d))},c=d=>d.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return 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(Lt,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((d,l)=>{const p=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),f=/^(reject|deny|delete|remove|abort)/.test(p),v=r===d,x=r!==null;return e.jsx("button",{onClick:()=>o(d),disabled:x,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"bg-white font-extrabold":f?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${x&&!v?"opacity-40":"opacity-100"} ${x?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)"}:void 0,children:v?"⏳ ...":c(d)},l)})})]})]})}const hn=new Map,$o={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",antigravity:"#f97316",windsurf:"#34d399"};function Do({ideId:t,sessionId:s,ideType:r,providerType:n,displayLabel:i,controls:o,controlValues:c,serverModel:d,serverMode:l}){const{sendCommand:p}=$t(),m=`${t}:${s||n}`,f=$o[n]||"#94a3b8",[v,x]=a.useState({}),w=a.useRef(0),u={...d?{model:d}:{},...l?{mode:l}:{},...c||{},...Date.now()<w.current?v:{}};a.useEffect(()=>{c&&Date.now()>w.current&&x({})},[c]);const[k,g]=a.useState(hn.get(m)||{}),[b,C]=a.useState(null),[I,N]=a.useState(null),h=a.useCallback(async(P,T={})=>{const L={...T,...s&&{targetSessionId:s}};return await p(t,P,L)},[t,s,p]),y=a.useCallback(async(P,T={},L)=>{try{const B=await h("invoke_provider_script",{agentType:n,ideType:r,scriptName:P,...T});return(B==null?void 0:B.success)===!1&&L?await h(L,{agentType:n,ideType:r,...T}):B}catch(B){if(!L)throw B;return await h(L,{agentType:n,ideType:r,...T})}},[h,n,r]);if(!o||o.length===0)return null;const j=o.filter(P=>P.placement==="bar").sort((P,T)=>(P.order??50)-(T.order??50));if(j.length===0)return null;const S=async P=>{var L,B,J;if(b===P.id){C(null);return}if((((L=P.options)==null?void 0:L.map(K=>K.value))||k[P.id]||[]).length>0){C(P.id);return}if(P.dynamic&&P.listScript){N(P.id);try{const K=Ls(P.listScript),$=await y(P.listScript,{},K),V=(($==null?void 0:$.models)||($==null?void 0:$.modes)||((B=$==null?void 0:$.result)==null?void 0:B.models)||((J=$==null?void 0:$.result)==null?void 0:J.modes)||($==null?void 0:$.options)||[]).map(H=>typeof H=="string"?H:(H==null?void 0:H.name)||(H==null?void 0:H.id)||(H==null?void 0:H.value)||String(H));g(H=>{const te={...H,[P.id]:V};return hn.set(m,te),te}),C(P.id)}catch{}finally{N(null)}}},E=async(P,T)=>{C(null),x(L=>({...L,[P.id]:T})),w.current=Date.now()+5e3;try{if(!P.setScript)return;await y(P.setScript,{model:P.id==="model"?T:void 0,mode:P.id==="mode"?T:void 0,value:T},Ls(P.setScript))}catch{}},D=async P=>{var $;const T=(($=P.options)==null?void 0:$.map(W=>W.value))||k[P.id]||[];if(T.length===0)return;const L=String(u[P.id]||""),J=(T.indexOf(L)+1)%T.length,K=T[J];if(typeof K=="string"){x(W=>({...W,[P.id]:K})),w.current=Date.now()+5e3;try{if(!P.setScript)return;await y(P.setScript,{value:K},Ls(P.setScript))}catch{}}},O=async P=>{const L=!u[P.id];x(B=>({...B,[P.id]:L})),w.current=Date.now()+5e3;try{if(!P.setScript)return;await y(P.setScript,{value:L},Ls(P.setScript))}catch{}},_=async P=>{if(P.invokeScript)try{await y(P.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:f},children:i}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),j.map(P=>{var K;const T=String(u[P.id]||""),L=b===P.id,B=I===P.id,J=((K=P.options)==null?void 0:K.map($=>$.value))||k[P.id]||[];switch(P.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:L?`${f}55`:"transparent",border:"1px solid",color:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>S(P),children:[P.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),B?"...":T||P.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),L&&J.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>C(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:P.label.toUpperCase()}),J.map($=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:$===T?`${f}18`:"transparent",color:$===T?f:"var(--text-secondary)",fontWeight:$===T?600:400,borderLeft:$===T?`2px solid ${f}`:"2px solid transparent"},onMouseEnter:W=>{W.currentTarget.style.background=`${f}12`},onMouseLeave:W=>{W.currentTarget.style.background=$===T?`${f}18`:"transparent"},onClick:()=>E(P,$),children:$},$))]})]})]},P.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:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>D(P),title:`Click to cycle: ${J.join(" → ")}`,children:[P.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),T||P.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},P.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:T?`${f}44`:"transparent",background:T?`${f}14`:"var(--surface-tertiary)",color:T?f:"var(--text-muted)"},onClick:()=>O(P),children:[P.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.label]},P.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:()=>_(P),children:[P.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.resultDisplay==="inline"&&T?`${P.label}: ${T}`:P.label]},P.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:T?"var(--text-primary)":"var(--text-muted)"},children:[P.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),T?`${P.label}: ${T}`:P.label]},P.id);default:return null}})]})}function Ls(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const Bo=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:i,isActive:o=!0}){const c=a.useRef(null),[d,l]=a.useState("");a.useEffect(()=>{l("")},[s]),a.useEffect(()=>{var m;o&&((m=c.current)==null||m.focus())},[s,o]);const p=()=>{const m=d.trim();!m||n||(l(""),i(m))};return e.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:o?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:o?72:0,opacity:o?1:0,transform:o?"translateY(0)":"translateY(10px)",padding:o?"10px 12px":"0 12px",pointerEvents:o?"auto":"none"},"aria-hidden":!o,children:e.jsxs("div",{className:"flex gap-2.5 items-center",title:o?`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:d,onChange:m=>l(m.target.value),onPaste:m=>{const f=m.clipboardData.getData("text");f&&l(v=>v+f),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),p()}},onBlur:m=>{if(window.innerWidth<768){const f=m.relatedTarget;if((f==null?void 0:f.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:p,disabled:!d.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var Ko=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Wo(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function nt(t,s){if(Wo(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Ko.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 wa(t){return nt(t)==="generating"}function Oe(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Oo(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 i=Math.floor(r/24),o=r%24;return`${i}d ${o}h`}function bn(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function sr(t,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof t=="string"?t.trim():"";if(!n)return"";const i=n.replace(/[\\/]+$/,""),o=i.split(/[\\/]/).filter(Boolean);return o[o.length-1]||i}function Fo(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 Uo(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function zo(t){return Fo(t.trim().replace(/\.local$/i,""))}function Vo(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function ja(t,s={}){var i,o;const r=[t.hostname,(i=t.machine)==null?void 0:i.hostname,(o=t.system)==null?void 0:o.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Uo(c));if(r&&r!=="Unknown")return zo(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function lt(t,s={}){return Vo(t)||ja(t,s)}function Ns(t){return t.transport==="pty"}function is(t){return t.transport==="acp"}function gn(t,s){return Oe(t)}function yn(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const i=(s||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=Oe(r||"").trim().toLowerCase();return n===i||n===o||n===c}function Ho(t){return nt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function qo(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 i=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=s.get(i),c=nt(n.status);if(!o){s.set(i,{...n,status:c});continue}const d=r.indexOf(o.status||"idle"),l=r.indexOf(c||"idle");l>=0&&(d<0||l<d)&&s.set(i,{...n,status:c})}return Array.from(s.values())}function Go(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 Yo(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&&Go(s.receivedAt)||0}function Xo(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Ir(t){return Math.max(Xo(t),Yo(t.activeChat))}function Jo(t,s,r,n,i,o){const c=s-t;if(c!==0)return c;const d=r.localeCompare(n);return d!==0?d:i.localeCompare(o)}function Or(t,s){return Jo(Ir(t),Ir(s),lt(t,{fallbackId:t.id}),lt(s,{fallbackId:s.id}),t.id,s.id)}const Ke=t=>t.transport==="pty",ds=(t,s)=>Ke(t)?t.mode||"terminal":"chat",ka=(t,s)=>Ke(t)&&ds(t)==="terminal",De=t=>t.transport==="acp";function wt(t){return t.streamSource!=="agent-stream"}function Et(t){var s;return t.daemonId||((s=t.ideId)==null?void 0:s.split(":")[0])||t.ideId||""}function Na(t){return t.machineName||""}function Fr(t){return Et(t)}function Jt(t){return wt(t)?t.ideType||t.agentType||"":t.agentType||t.ideType||""}function rr(t){return t.displayPrimary||t.agentName||"Agent"}function Ur(t){return[t.displaySecondary,Na(t)].filter(Boolean)}function As(t){return t.agentName||Oe(Jt(t))}function Zo(t){var s,r;if(!wt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Oe(t.ideType||"")}function Qo(t){return wt(t)?t.sessionId:t.nativeSessionId}function vn(t){return wt(t)?"native":t.tabKey}function ec(t){return t.sessionId}function tc(t,s){if(s)return wt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function sc(t,s){const r=Jt(t),n=wt(t)?s!=null&&s.type?Oe(s.type):Oe(t.ideType||""):As(t);return{isNativeConversation:wt(t),isCli:Ke(t),isAcp:De(t),isCliTerminal:ka(t),providerType:r,displayLabel:n,targetEntry:tc(t,s)}}function Sa({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:i=!0}){const o=us(),c=Et(t),d=Na(t),l=t.transport==="cdp-page"||t.transport==="cdp-webview",p=t.streamSource==="agent-stream"&&!!t.agentName,m=!p&&(t.transport==="pty"||t.transport==="acp"),f=As(t),v=Zo(t),x=a.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),w=a.useCallback(()=>{if(r){r();return}const u=Qo(t);u&&o(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[t,o,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[l&&(i?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:v,children:[e.jsx(ct,{size:12}),e.jsx("span",{children:v})]}):e.jsxs("span",{className:"conversation-meta-chip",title:v,children:[e.jsx(ct,{size:12}),e.jsx("span",{children:v})]})),p&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[e.jsx(Yt,{size:12}),e.jsx("span",{children:f})]}),m&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[e.jsx(Yt,{size:12}),e.jsx("span",{children:f})]}),d&&(i?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:d,children:[e.jsx(Pt,{size:12}),e.jsx("span",{children:d})]}):e.jsxs("span",{className:"conversation-meta-chip",title:d,children:[e.jsx(Pt,{size:12}),e.jsx("span",{children:d})]}))]})}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 Ca(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 i=Xt(t.content),o=Xt(s.content);if(!i||i!==o)return!1;const c=Zt(t),d=Zt(s);return c&&d?Math.abs(c-d)<=15e3:!!t._localId!=!!s._localId}function wn(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 rc(t,s){const r=wn(t),n=wn(s);return n!==r?n>r?s:t:Xt(s.content).length>=Xt(t.content).length?s:t}function jn(t){const s=[];for(const r of t){const n=s.findIndex(i=>Ca(i,r));if(n>=0){s.splice(n,1,rc(s[n],r));continue}s.push(r)}return s}function kn(t){return[...t].sort((s,r)=>{const n=Zt(s),i=Zt(r);return n&&i&&n!==i?n-i:0})}function Nn(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${Xt(t==null?void 0:t.content).slice(0,100)}`}function Sn(t,s){const r=t.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const i=r.findIndex(o=>Ca(o,n));return i>=0?(r.splice(i,1),!1):!0})}function nc(t,s){const r=new Set(s.map(n=>Nn(n)));return t.filter(n=>!r.has(Nn(n)))}function ac(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}const ic=60,oc=60;function _r({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:i,isFocusingAgent:o,actionLogs:c,userName:d,showMetaChips:l=!1,scrollToBottomRequestNonce:p,isInputActive:m=!0}){const f=a.useRef(new Map),{sendCommand:v}=$t();_s("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const x=He.useMemo(()=>ps(t),[t.status,t.connectionState]),w=a.useRef(new Map),u=a.useCallback(B=>(w.current.has(B)||w.current.set(B,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:ic}),w.current.get(B)),[]),k=a.useCallback((B,J)=>{const K=u(B);w.current.set(B,{...K,...J}),g($=>$+1)},[u]),[,g]=a.useState(0),b=t.tabKey,C=u(b),I=C.messages,N=C.hasMore,h=C.error,y=Math.max(0,t.messages.length-C.visibleLiveCount),[j,S]=a.useState(!1),E=a.useCallback(async()=>{if(j)return;const B=t.tabKey,J=u(B);if(t.messages.length>J.visibleLiveCount){k(B,{visibleLiveCount:Math.min(t.messages.length,J.visibleLiveCount+oc),error:null});return}S(!0),k(B,{error:null});try{const K=Fr(t);if(!K){k(B,{hasMore:!1});return}const $=Jt(t),W=await v(K,"chat_history",{agentType:$,offset:J.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),V=ac(W),H=V.messages||[];if(H.length>0){const te=u(B);k(B,{messages:[...H,...te.messages],offset:te.offset+H.length,hasMore:!!V.hasMore})}else k(B,{hasMore:!!V.hasMore})}catch(K){const $=(K==null?void 0:K.message)||"";$.includes("P2P not available")||$.includes("channel not open")||$.includes("P2P not connected")||$.includes("timeout")?k(B,{error:"Connection not ready — tap to retry"}):k(B,{hasMore:!1,error:"Failed to load history"})}finally{S(!1)}},[j,s,t,v,u,k]),{allMessages:D,receivedAtMap:O}=a.useMemo(()=>{const B=y>0?t.messages.slice(-C.visibleLiveCount):t.messages;if(I.length===0){const W=kn(jn(B)),V={};return W.forEach((H,te)=>{const ke=`${t.tabKey}:${as(H,te)}`;let X=Zt(H)||f.current.get(ke)||0;X||(X=Date.now(),f.current.set(ke,X)),V[as(H,te)]=X}),{allMessages:W,receivedAtMap:V}}const J=nc(I,B),K=kn(jn([...J,...B])),$={};return K.forEach((W,V)=>{const H=`${t.tabKey}:${as(W,V)}`;let te=Zt(W)||f.current.get(H)||0;te||(te=Date.now(),f.current.set(H,te)),$[as(W,V)]=te}),{allMessages:K,receivedAtMap:$}},[t.messages,t.tabKey,y,I,C.visibleLiveCount]),_=a.useMemo(()=>c.filter(B=>B.ideId===t.tabKey).sort((B,J)=>B.timestamp-J.timestamp),[c,t.tabKey]),P=rr(t),T=a.useMemo(()=>sc(t,s),[t,s]),L=a.useMemo(()=>{if(t.messages.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((x.isGenerating||t.status==="streaming")&&S(!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(Yt,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),e.jsx("button",{onClick:i,disabled:o,className:"btn btn-primary",children:o?"⌛ Switching...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{size:14})," Open ",P," Panel"]})}),e.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(t.status==="panel_hidden")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(pa,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),e.jsx("button",{onClick:i,disabled:o,className:"btn btn-primary",children:o?"⌛ Opening...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ls,{size:14})," Open ",P," Panel"]})}),e.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(t.status==="idle"&&!j)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.messages.length,t.connectionState,t.status,i,o,j,P,x.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[l&&e.jsx(Sa,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(No,{messages:D,actionLogs:_,agentName:As(t)||P||"Agent",userName:d,isCliMode:T.isCli||T.isAcp,isWorking:x.isGenerating,contextKey:t.tabKey,receivedAtMap:O,onLoadMore:E,isLoadingMore:j,hasMoreHistory:N,hiddenLiveCount:y,loadError:h??void 0,emptyState:L,scrollToBottomRequestNonce:p}),m&&!T.isCliTerminal&&(()=>{var B,J,K,$,W,V;return e.jsx(Do,{ideId:t.ideId,sessionId:t.sessionId,ideType:t.ideType,providerType:T.providerType,displayLabel:T.displayLabel,controls:(B=T.targetEntry)==null?void 0:B.providerControls,controlValues:(J=T.targetEntry)==null?void 0:J.controlValues,serverModel:((K=T.targetEntry)==null?void 0:K.currentModel)||void 0,serverMode:(($=T.targetEntry)==null?void 0:$.currentPlan)||void 0,acpConfigOptions:T.isAcp?(W=T.targetEntry)==null?void 0:W.acpConfigOptions:void 0,acpModes:T.isAcp?(V=T.targetEntry)==null?void 0:V.acpModes:void 0})})(),e.jsx(Bo,{contextKey:t.tabKey,panelLabel:P,isSending:n,onSend:r,isActive:m})]})}let Ia=Gt;function _a(){return Ia()}class cc{constructor(){Ye(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(i=>i(...r))}}let Ta=new cc;class lc{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,i){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 ze=new lc;function dc(t){t.dashboardWS&&(Ta=t.dashboardWS),t.connectionManager&&(ze=t.connectionManager),t.useDaemonsHook&&(Ia=t.useDaemonsHook)}function Ve(t){return rr(t)}function Qt(t){return Ur(t).join(" · ")}function Aa(t){const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=Xt(s==null?void 0:s.content);return r||(t.title?t.title:Qt(t)||"No messages yet")}function Ma(t,s){const{isReconnecting:r,isConnecting:n}=ps(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function uc(t,s){const r=["Chat",...Ur(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function os(t){return Ma(t)||Qt(t)}function mc(t){return`${Ve(t)} · ${Aa(t)}`}function pc(t){return`${Ve(t)} — ${Oe(t.ideType)}`}function xc(t){return As(t)||"CLI"}function Pa(t){return t.title||As(t)||t.ideId}function fc(t){return t?`Remote · ${Ve(t)||t.workspaceName||"Session"}`:"Remote"}function hc({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:i=!1,isVisible:o=!0}){var $;const{ides:c}=Gt(),d=a.useRef(null),{sendCommand:l,sendData:p}=$t(),[m,f]=a.useState(""),[v,x]=a.useState(!1),[w,u]=a.useState(1),k=a.useRef(!1),g=a.useRef(0),b=a.useRef(!1),C=a.useRef(""),I=a.useRef(null),N=a.useRef(!1),h=a.useRef(null),y=t.tabKey,j=t.sessionId||"",S=t.daemonId||(($=t.ideId)==null?void 0:$.split(":")[0])||t.ideId||"",E=c.find(W=>W.id===S&&W.daemonMode),D=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",O=.6,_=1.15,P=()=>{if(typeof window>"u")return 1;const W=window.innerWidth||0;return W<=360?.68:W<=390?.74:W<=430?.82:W<=480?.9:1},T=()=>{var W,V;g.current=0,b.current=!1,C.current="",I.current=null,N.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),x(!1),(V=(W=r.current)==null?void 0:W.reset)==null||V.call(W)},L=()=>{var W,V;g.current=0,b.current=!1,C.current="",I.current=null,N.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),x(!0),(V=(W=r.current)==null?void 0:W.reset)==null||V.call(W)},B=()=>{var V;if(h.current=null,!o)return;const W=C.current;W&&(C.current="",(V=r.current)==null||V.write(W))},J=W=>{W&&(C.current+=W,o&&h.current===null&&(h.current=requestAnimationFrame(B)))},K=(W,V=0,H,te)=>{var ke,X,Z,G,fe;V>0&&g.current>=V||V===0&&b.current||(g.current=V,x(!0),typeof H=="number"&&typeof te=="number"&&H>0&&te>0&&((X=(ke=r.current)==null?void 0:ke.resize)==null||X.call(ke,H,te)),(G=(Z=r.current)==null?void 0:Z.reset)==null||G.call(Z),W&&((fe=r.current)==null||fe.write(W)))};return a.useEffect(()=>{T()},[j]),a.useEffect(()=>{var V;if(!j)return;const W=((V=ze.onRuntimeEvent)==null?void 0:V.call(ze,j,H=>{if(!(!H||H.sessionId!==j)){if(H.type==="runtime_snapshot"){if(!o){I.current={text:H.text||"",seq:H.seq||0,cols:H.cols,rows:H.rows};return}K(H.text||"",H.seq||0,H.cols,H.rows);return}if(H.type==="session_output"){b.current=!0,typeof H.seq=="number"&&(g.current=Math.max(g.current,H.seq)),v||x(!0),typeof H.data=="string"&&J(H.data);return}if(H.type==="session_cleared"){if(!o){N.current=!0,C.current="",I.current=null;return}L()}}}))||(()=>{});return()=>{W()}},[S,j,r,o,v]),a.useEffect(()=>{var V,H,te;if(!j)return;S&&((V=ze.getState)==null?void 0:V.call(ze,S))==="connected"&&(x(!0),(H=ze.requestRuntimeSnapshot)==null||H.call(ze,S,j).catch(()=>{}));const W=(te=ze.onStateChange)==null?void 0:te.call(ze,(ke,X)=>{var Z;ke!==S||X!=="connected"||(x(!0),(Z=ze.requestRuntimeSnapshot)==null||Z.call(ze,S,j).catch(()=>{}))});return()=>{W==null||W()}},[S,j,r]),a.useEffect(()=>{s&&T()},[s,y,r]),a.useEffect(()=>{f("")},[t.tabKey]),a.useEffect(()=>{const W=()=>{k.current||u(P())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),a.useEffect(()=>{var V;if(!o){(V=d.current)==null||V.blur();return}N.current&&(N.current=!1,L());const W=I.current;W&&(I.current=null,K(W.text,W.seq,W.cols,W.rows)),C.current&&h.current===null&&(h.current=requestAnimationFrame(B)),requestAnimationFrame(()=>{var H;(H=r.current)==null||H.bumpResize()})},[o]),a.useEffect(()=>()=>{h.current!==null&&(cancelAnimationFrame(h.current),h.current=null)},[]),a.useEffect(()=>{const W=V=>{var te;const H=V.detail;H!=null&&H.sessionId&&H.sessionId!==j||v&&((te=r.current)==null||te.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[v,j,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:()=>{k.current=!0,u(W=>Math.max(O,Number((W-.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:()=>{k.current=!0,u(W=>Math.min(_,Number((W+.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/w}%`,height:`${100/w}%`,transform:`scale(${w})`,transformOrigin:"top left"},children:e.jsx(ha,{ref:r,readOnly:!v||!o,sizingMode:D,onInput:W=>{v&&(p!=null&&p(S,{type:"pty_input",targetSessionId:j,data:W})||l(S,"pty_input",{targetSessionId:j,data:W}).catch(console.error))}})})}),!v&&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:d,type:"text",placeholder:`Send message to ${Ve(t)}...`,value:m,disabled:!v||!o||i,onChange:W=>f(W.target.value),onPaste:W=>{const V=W.clipboardData.getData("text");V&&f(H=>H+V),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const V=m.trim();!v||!V||i||(f(""),n(V))},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 W=m.trim();!v||!W||i||(f(""),n(W))},disabled:!v||!o||!m.trim()||i,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!i?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!i?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function bc({wsStatus:t,showReconnected:s,loginUrl:r}){const n=t==="disconnected"||t==="reconnecting"||t==="offline"||t==="auth_failed",i=t==="auth_failed"?"red":t==="offline"?"orange":"accent",o={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},d={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return 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:o[i],borderBottom:c[i],color:d[i]},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 gc({terminalBackend:t,isStandalone:s=!1,machineLabel:r,machineKey:n}){const i=a.useMemo(()=>!n||!t?null:`adhdev:terminal-backend-banner:dismissed:${n}:${t.backend}`,[n,t]),[o,c]=a.useState(!1);if(a.useEffect(()=>{if(!i){c(!1);return}try{c(localStorage.getItem(i)==="1")}catch{c(!1)}},[i]),!s||!t||t.backend!=="xterm"||o)return null;const d=(r==null?void 0:r.trim())||"This machine",l=()=>{if(i)try{localStorage.setItem(i,"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:[d," 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:l,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 zr({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(Is,{size:n}):e.jsx(Tt,{size:n})})}function Cn({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const i=Ur(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:rr(t)}),(r||i.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,i.join(" · ")]})]})}function yc({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:i,onOpenHistory:o,onOpenRemote:c,onStopCli:d,activeCliViewMode:l,onSetCliViewMode:p,onOpenConversation:m,onHideConversation:f,hiddenConversations:v=[],onShowConversation:x,onShowAllHidden:w,inboxOpen:u,onInboxOpenChange:k,hiddenOpen:g,onHiddenOpenChange:b,onOpenNewSession:C}){const{ides:I,p2pStates:N={}}=Gt(),h=!!t&&Ke(t)&&!De(t),y=!!t&&De(t),j=l||(t?ka(t)?"terminal":"chat":null),[S,E]=a.useState(!1),D=a.useRef(null),O=a.useRef(null),_=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",P=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",T=I.filter(G=>G.type==="adhdev-daemon"),L=a.useMemo(()=>Ts(I),[I]),B=Object.values(N),J=B.filter(G=>G==="connected").length,K=B.filter(G=>G==="connecting"||G==="new"||G==="checking").length,W=r!=="connected"||T.length===0?null:K>0&&J===0?"P2P connecting...":J>0&&s===0?"Waiting for IDE...":null,V=a.useMemo(()=>i.filter(G=>!Eo(G,i,L)),[i,L]),H=a.useMemo(()=>V.filter(G=>ks(G,L).requiresAction),[V,L]),te=a.useMemo(()=>V.filter(G=>{const fe=(t==null?void 0:t.tabKey)===G.tabKey;return ks(G,L,{hideOpenTaskCompleteUnread:!0,isOpenConversation:fe}).unread}),[t,V,L]),ke=a.useMemo(()=>[...H,...te].slice(0,9),[H,te]),X=H.length+te.length;a.useEffect(()=>{if(!u)return;const G=fe=>{var re;(re=D.current)!=null&&re.contains(fe.target)||k(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[u,k]),a.useEffect(()=>{if(!g)return;const G=fe=>{var re;(re=O.current)!=null&&re.contains(fe.target)||b(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[g,b]),a.useEffect(()=>{if(!g&&!u)return;const G=fe=>{if(!fe.altKey)return;const re=fe.code.match(/^Digit([1-9])$/);if(!re)return;const he=Number(re[1])-1,ve=g?v[he]:void 0,ie=u?ke[he]:void 0,pe=ve||ie;if(pe){if(fe.preventDefault(),fe.stopPropagation(),ve){x==null||x(ve),b(!1);return}m==null||m(pe),k(!1)}};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[v,g,u,ke,b,k,m,x]);const Z=G=>{if(!G)return;const fe=i.find(re=>re.tabKey===G);fe&&(f==null||f(fe))};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(Tt,{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:_,boxShadow:P}})})]}),e.jsxs("div",{className:"header-subtitle",children:[C&&e.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(uo,{size:14})}),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:_,boxShadow:P}}),W&&e.jsxs("span",{className:"header-subtitle-status",children:["· ",W]})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(h||y||!De(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)}),(h||y)&&d&&e.jsxs(e.Fragment,{children:[h&&p&&j&&e.jsx(zr,{mode:j,onChange:p,compact:!0}),e.jsx("button",{onClick:()=>d(t),className:"btn btn-secondary btn-sm",title:y?"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(Rt,{size:14})})]}),!De(t)&&e.jsx("button",{onClick:()=>o(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(Dr,{size:14})}),!h&&!De(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(ct,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[e.jsxs("div",{className:`dashboard-header-hidden${S?" is-drop-target":""}`,ref:O,onDragEnter:G=>{G.dataTransfer.types.includes("text/tab-key")&&(G.preventDefault(),E(!0))},onDragOver:G=>{G.dataTransfer.types.includes("text/tab-key")&&(G.preventDefault(),G.dataTransfer.dropEffect="move",E(!0))},onDragLeave:G=>{G.currentTarget.contains(G.relatedTarget)||E(!1)},onDrop:G=>{const fe=G.dataTransfer.getData("text/tab-key");G.preventDefault(),E(!1),Z(fe)},children:[e.jsxs("button",{type:"button",onClick:()=>b(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx(oo,{size:16}),v.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:v.length})]}),g&&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"}),v.length>0&&w&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{w(),b(!1)},children:"Restore all"})]}),t&&f&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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)})]}),v.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:v.map(G=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{x==null||x(G),b(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Ve(G)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[v.indexOf(G)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",v.indexOf(G)+1]}):null,Qt(G)]})]},G.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>k(!u),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(tr,{size:16}),X>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:X})]}),u&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[H.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),H.map(G=>e.jsx(Cn,{conversation:G,isAttention:!0,shortcutIndex:ke.indexOf(G)>=0?ke.indexOf(G)+1:void 0,onClick:()=>{m==null||m(G),k(!1)}},G.tabKey))]}),te.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),te.map(G=>e.jsx(Cn,{conversation:G,shortcutIndex:ke.indexOf(G)>=0?ke.indexOf(G)+1:void 0,onClick:()=>{m==null||m(G),k(!1)}},G.tabKey))]}),X===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function vc(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 Vr({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:i=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:l,onSwitchSession:p,onRefreshHistory:m,onResumeSavedSession:f}){var g;const v=s.find(b=>b.id===t.ideId),x=(v==null?void 0:v.chats)||[],w=(g=v==null?void 0:v.activeChat)==null?void 0:g.id,u=Ke(t)&&!De(t),k=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[e.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:pc(t)})]}),e.jsx("button",{onClick:d,className:"bg-transparent border-none text-xl text-text-muted cursor-pointer",children:"✕"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&e.jsx("button",{onClick:l,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?e.jsx(e.Fragment,{children:i.map(b=>{const C=t.providerSessionId===b.providerSessionId,I=C||!b.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{I||!f||f(b)},disabled:I,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"} ${I?"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:b.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:vc(b.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.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:[b.workspace||"Workspace unknown",b.currentModel?` · ${b.currentModel}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:C?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})}):x.map(b=>e.jsxs("div",{onClick:()=>{p(t.ideId,b.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${w===b.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 ${w===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.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:[b.id.substring(0,12),"..."]}),w===b.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(u&&!o&&i.length===0||!u&&x.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(xo,{size:32})}),e.jsx("div",{className:"text-[13px]",children:u?"No saved sessions found yet.":"No recent chat sessions found."})]}),u&&o&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:m,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ms,{size:13})," ",u?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?k:aa.createPortal(k,document.body)}const In={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 La({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 i=In[n.type]||In.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 o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${i.accent}, color-mix(in srgb, ${i.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 text-[13px] leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:"×"}),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:i.chipBg,color:i.chipText,border:`1px solid color-mix(in srgb, ${i.accent} 22%, transparent)`},children:i.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((o,c)=>e.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),o.onClick(),s(n.id)},children:o.label},c))})]})]},n.id)})})}const wc=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function jc(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function kc(t){return t.sessionId||t.instanceId||t.agentType}function mr(t,s){return t||s}function _n(t,s){const r=new Set,n=[];for(const i of s)if(i)for(const o of t[i]||[]){const c=o._localId||`${o.role}:${o.timestamp}:${o.content}`;r.has(c)||(r.add(c),n.push(o))}return n.sort((i,o)=>i.timestamp-o.timestamp)}function Ra(t=[]){const s={};for(const r of t)(r.type==="adhdev-daemon"||r.daemonMode)&&(s[r.id]=lt(r,{fallbackId:r.id}));return s}function Ea(t,s={}){var n,i;const r=t.daemonId||((n=t.id)==null?void 0:n.split(":")[0])||t.id;return{machineName:t.daemonId&&((i=s.machineNames)==null?void 0:i[t.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Hr(t,s,r={}){return Nc(t,s,Ea(t,r))}function Nc(t,s,r={}){var v,x,w,u,k,g;const n=[],i=r.machineName,o=r.connectionState,c=jc(t),d=Oe(t.type),l=Array.isArray(t.childSessions)?t.childSessions.map(b=>{var C,I;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,agentType:b.providerType,agentName:b.providerName,status:b.status,title:b.title,messages:((C=b.activeChat)==null?void 0:C.messages)||[],activeModal:((I=b.activeChat)==null?void 0:I.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,surfaceHidden:b.surfaceHidden}}):[],p=wc(t),m=t.activeChat||{title:""},f=m.title&&String(m.title).trim()?String(m.title).trim():"";if(p){const b=t.sessionId||t.instanceId,C=gn(t.type),I=(v=t.activeChat)==null?void 0:v.activeModal,N=I&&Array.isArray(I.buttons)&&I.buttons.length>0,h=nt((x=t.activeChat)==null?void 0:x.status,{activeModal:(w=t.activeChat)==null?void 0:w.activeModal})||nt((k=(u=t.agents)==null?void 0:u[0])==null?void 0:k.status)||"idle",y=t.activeChat||{title:"",messages:[]};let j=y.title&&String(y.title).trim()?String(y.title).trim():"";const S=(g=t.activeChat)==null?void 0:g.id,E=t.chats;if(S&&Array.isArray(E)&&E.length>0){const L=E.find(B=>B.id===S||B.id&&String(B.id)===String(S));L!=null&&L.title&&String(L.title).trim()&&(j=String(L.title).trim())}const D=(Ke(t)||De(t),t.type),O=(Ke(t)||De(t))&&yn(j,C,D)?"":j,_=y.messages||[],P=_n(s,[t.id,b]),T=Sn(_,P);n.push({ideId:t.id,sessionId:b,providerSessionId:t.providerSessionId,nativeSessionId:b,transport:t.transport,daemonId:t.daemonId||void 0,mode:Ke(t)?t.mode||"terminal":"chat",agentName:C,agentType:D,status:h,title:O,messages:[..._,...T],resume:t.resume,ideType:D,workspaceName:c,displayPrimary:c||O||(Ke(t)?t.mode==="chat"?C:"Terminal":C),displaySecondary:d,cdpConnected:t.cdpConnected,modalButtons:N?I.buttons:void 0,modalMessage:N?I.message:void 0,streamSource:"native",tabKey:mr(b,t.id),machineName:i,connectionState:o})}if(p&&(Ke(t)||De(t)))return n;for(const b of l){const C=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,I=Ho(b),N=kc(b),h=`${t.id}:${N}`,y=b.title&&String(b.title).trim()||"",j=yn(y,b.agentName,b.agentType)?"":y,S=b.messages||[],E=_n(s,[h,b.sessionId,b.instanceId]),D=Sn(S,E);(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||S.length>0||D.length>0||C||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(I))&&n.push({ideId:t.id,sessionId:b.sessionId||b.instanceId,providerSessionId:b.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:b.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:b.agentName,agentType:b.agentType,status:I,title:j,messages:[...S,...D],ideType:b.agentType,workspaceName:c,displayPrimary:c||f||j||d,displaySecondary:`${d} · ${b.agentName}`,cdpConnected:t.cdpConnected,modalButtons:C?b.activeModal.buttons:void 0,modalMessage:C?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:mr(b.sessionId||b.instanceId,h),machineName:i,connectionState:o})}return n.length===0&&n.push({ideId: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:gn(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],ideType:t.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:t.cdpConnected,streamSource:"native",tabKey:mr(t.sessionId||t.instanceId,t.id),connectionState:o}),n}function Sc(t){const s=[],r=new Map;for(const n of t)if(n.parentId){const i=r.get(n.parentId)||[];i.push(n),r.set(n.parentId,i)}else s.push(n);return{topLevel:s,childrenByParent:r}}function Cc(t,s){const r=[],{daemonId:n,existingDaemon:i,timestamp:o}=s,c=o||t.timestamp||Date.now(),d=t.sessions||[],{topLevel:l,childrenByParent:p}=Sc(d),m=l.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),f=l.filter(x=>x.kind==="agent"&&x.transport==="pty"),v=l.filter(x=>x.kind==="agent"&&x.transport==="acp");r.push({...i||{},id:n,type:"adhdev-daemon",status:"online",daemonMode:!0,timestamp:c,...t.version&&{version:t.version},...t.machine&&{machine:t.machine,platform:t.machine.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:m.some(x=>!!x.cdpConnected)});for(const x of m){const w=p.get(x.id)||[];r.push({id:`${n}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId,parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,ideType:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:x.id,workspace:x.workspace,terminals:0,childSessions:w,agents:w.map(u=>({id:u.id,name:u.providerName,type:u.providerType,status:u.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,currentModel:x.currentModel,currentPlan:x.currentPlan,currentAutoApprove:x.currentAutoApprove,lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden,controlValues:x.controlValues,providerControls:x.providerControls,timestamp:c})}for(const x of f)r.push({id:`${n}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId,parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,ideType:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:x.id,cliName:x.providerName,mode:x.mode||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,resume:x.resume,runtimeKey:x.runtimeKey,runtimeDisplayName:x.runtimeDisplayName,runtimeWorkspaceLabel:x.runtimeWorkspaceLabel,runtimeWriteOwner:x.runtimeWriteOwner??null,runtimeAttachedClients:x.runtimeAttachedClients??[],lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden,controlValues:x.controlValues,providerControls:x.providerControls,timestamp:c,_isCli:!0});for(const x of v)r.push({id:`${n}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId,parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,ideType:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:x.id,cliName:x.providerName,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,runtimeKey:x.runtimeKey,runtimeDisplayName:x.runtimeDisplayName,runtimeWorkspaceLabel:x.runtimeWorkspaceLabel,runtimeWriteOwner:x.runtimeWriteOwner??null,runtimeAttachedClients:x.runtimeAttachedClients??[],currentModel:x.currentModel,currentPlan:x.currentPlan,lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden,acpConfigOptions:x.acpConfigOptions,acpModes:x.acpModes,controlValues:x.controlValues,providerControls:x.providerControls,timestamp:c,_isAcp:!0});return r}function Ic(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 _c(t,s){const r=Ic(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const $a=[{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:"🏄"}],Da=[{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:"🧩"}],Ba=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"}],Tc={status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},Ac={antigravity:{status:"unverified",testedOn:["macOS 26.4"],testedVersions:["Antigravity 1.22.2"],validatedFlows:["read_chat","list_sessions"],lastValidated:"2026-04-09",notes:"Local smoke test confirmed read_chat and list_sessions. A fresh new_session plus send_chat flow did not produce a readable conversation transcript, so promotion is blocked.",evidence:"Manual local validation via standalone API on 2026-04-09",owner:"core",source:"docs/site/data/provider-catalog.mjs"},cursor:{status:"partial",testedOn:["macOS 26.4"],testedVersions:["Cursor 3.0.13"],validatedFlows:["detect","launch","read_chat","send_chat","list_sessions","switch_session","new_session","list_models","list_modes"],lastValidated:"2026-04-09",notes:"Detection, launch, fresh new-session send/read, session listing, session switching, model listing, and mode listing were validated locally. The tested build currently exposes only Auto in the model picker, and set_model plus resolve_action remain unverified.",evidence:"Manual local validation via standalone API on 2026-04-09",owner:"core",source:"docs/site/data/provider-catalog.mjs"},kiro:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},pearai:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},trae:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},vscode:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},vscodium:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},windsurf:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"aider-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"claude-cli":{status:"partial",testedOn:["macOS 26.4"],testedVersions:["Claude Code 2.1.84"],validatedFlows:["launch","send_chat","read_chat","resume","reconnect","stop"],lastValidated:"2026-04-09",notes:"Saved-session listing, resume launch, daemon-restart reconnect, and live read_chat were confirmed locally. A parser false-positive that trimmed short exact-match answers as prompt echo was fixed during validation; the provider still remains partial until more than one app/version combination is covered.",evidence:"Manual local validation via standalone API on 2026-04-09",owner:"core",source:"docs/site/data/provider-catalog.mjs"},"codex-cli":{status:"partial",testedOn:["macOS 26.4"],testedVersions:["codex-cli 0.118.0"],validatedFlows:["launch","send_chat","read_chat","resume","reconnect","stop"],lastValidated:"2026-04-09",notes:"Fresh launch, live send/read, saved-session resume, daemon-restart reconnect, and stop were validated locally after tightening onboarding-screen parsing, providerSessionId recovery, and history replay dedupe. Some older saved transcripts may still need one-time compaction if they were polluted before the fix.",evidence:"Manual local validation via standalone API and session-host restart recovery on 2026-04-09",owner:"core",source:"docs/site/data/provider-catalog.mjs"},"cursor-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"gemini-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"github-copilot-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"goose-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"opencode-cli":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},cline:{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},codex:{status:"partial",testedOn:["macOS 26.4"],testedVersions:["openai.chatgpt 26.406.31014"],validatedFlows:["read_chat","new_session","send_chat","list_sessions","switch_session","resolve_action"],lastValidated:"2026-04-10",notes:"Cursor-hosted Codex on macOS now has locale-agnostic read/list/switch handling, approve-path resolve_action, and transcript cleanup for localized timestamps plus stale replay turns. It remains Partial because recent-task history can still collapse to the current chat and some send_chat attempts still fail to materialize as a real turn, even though false-success reporting is now blocked.",evidence:"Manual local validation via standalone API on 2026-04-10 against Cursor-hosted Codex webview, including recent-task list/switch, approve-path resolve_action, and transcript cleanup verification",owner:"core",source:"docs/site/data/provider-catalog.mjs"},"roo-code":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"agentpool-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"amp-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"auggie-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"autodev-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"autohand-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"blackbox-ai-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"claude-agent-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"cline-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"codebuddy-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"codex-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"corust-agent-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"crow-cli-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"cursor-acp":{status:"partial",testedOn:["macOS 26.4"],testedVersions:["cursor-agent 2026.03.25-933d5a6"],validatedFlows:["launch","send_chat","read_chat","resolve_action","list_models","set_model","list_modes","set_mode","stop"],lastValidated:"2026-04-09",notes:"Approval flow, model change, mode change, and hard stop were validated locally. Reconnect and session resume are still unverified.",evidence:"Manual local validation via standalone API on 2026-04-09",owner:"core",source:"docs/site/data/provider-catalog.mjs"},"deepagents-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"dimcode-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"docker-cagent-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"factory-droid-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"fast-agent-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"gemini-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"github-copilot-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"goose-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"junie-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"kilo-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"kimi-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"minion-code-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"mistral-vibe-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"nova-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"openclaw-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"opencode-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"openhands-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"pi-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"qoder-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"qwen-code-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"stakpak-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"},"vtcode-acp":{status:"unverified",testedOn:[],testedVersions:[],validatedFlows:[],lastValidated:null,notes:"",evidence:"",owner:"community",source:"docs/site/data/provider-catalog.mjs"}};function Mc(t){return Ac[t]||Tc}const Pc=$a,Lc=Da,Rc=Ba,Ka="adhdev_notification_prefs",Tn={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ec(){try{const t=localStorage.getItem(Ka);if(t){const s=JSON.parse(t);return{...Tn,...s}}}catch{}return{...Tn}}function $c(t){try{localStorage.setItem(Ka,JSON.stringify(t))}catch{}}let _t=Ec(),Us=[];function Dc(){Us.forEach(t=>t())}function Bc(t){_t={..._t,...t},$c(_t),Dc()}function Kc(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return Us.push(r),()=>{Us=Us.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Bc(r)},[]);return[{..._t},s]}function Ut(t){if(!_t.globalEnabled)return!1;switch(t){case"disconnect":return _t.disconnectAlert;case"completion":return _t.completionAlert;case"approval":return _t.approvalAlert;case"browser":return _t.browserNotifications;default:return!0}}const Wc={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Oc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Wa(){return"Notification"in window&&Notification.permission==="granted"}let Wt=null;async function Fc(){if(Wt!==null)return Wt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Wt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Wt=!!await t.pushManager.getSubscription(),Wt):(Wt=!1,!1)}catch{return Wt=!1,!1}}function zs(t,s,r){if(Wa())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 Uc(t,s={}){const r={...Wc,...s},n=a.useRef(new Map),i=a.useRef(0),o=a.useRef(null);a.useEffect(()=>{Fc().then(d=>{o.current=d})},[]);const c=a.useCallback((d,l,p)=>{const m=Date.now();m-i.current<r.throttleMs||(i.current=m,zs(d,l,p))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!Wa())&&Ut("browser")&&o.current!==!0){if(document.hasFocus()){for(const l of t)n.current.set(l.id,nt(l.status,{activeModal:l.activeModal}));return}for(const l of t){const p=n.current.get(l.id),m=nt(l.status,{activeModal:l.activeModal}),f=l.name||l.id;if(r.onApproval&&Ut("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const v=((d=l.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,v.slice(0,120),`approval-${l.id}`)}r.onComplete&&Ut("completion")&&wa(p)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${l.id}`),r.onError&&m==="error"&&p!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${l.id}`),n.current.set(l.id,m)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const zc=/^(run|approve|accept|yes|allow|always)/,Vc=/^(run|approve|accept|yes|allow|always|proceed|save)/,Hc=/^(reject|deny|delete|remove|abort|cancel|no)/;function qr(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function qc(t){const s=qr(t).toLowerCase();return zc.test(s)?"primary":Hc.test(s)?"danger":"default"}function Gc(t){return Vc.test(qr(t).toLowerCase())?"approve":"reject"}function Yc(t){return t.map((s,r)=>({label:qr(s),variant:qc(s),action:Gc(s),button:s,buttonIndex:r}))}function Xc(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(i=>`[${i}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
29
- ${n}`}function Jc(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Zc(t,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(t,s,"approve").catch(i=>n==null?void 0:n("approve",i))}},{label:"Decline",variant:"danger",onClick:()=>{r(t,s,"reject").catch(i=>n==null?void 0:n("reject",i))}}]}class Qc{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(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 i=(n==null?void 0:n.id)||Date.now();this.emitToast({id:i,message:s,type:r,timestamp:i,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[i,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(i);return!1}resolveOwningDaemon(s){if(s.ideType==="adhdev-daemon"&&s.ideId){const i=this.ides.find(o=>o.id===s.ideId&&o.type==="adhdev-daemon");if(i)return i}let r;if(s.targetSessionId&&(r=this.findOwningSession(s.targetSessionId)||void 0),s.ideId&&(r=r||this.ides.find(i=>i.id===s.ideId)),!r&&s.instanceId&&(r=this.ides.find(i=>i.id.endsWith(`:ide:${s.instanceId}`)||i.id.endsWith(`:cli:${s.instanceId}`))),r){const i=r.daemonId;if(i){const o=this.ides.find(c=>c.id===i&&c.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(i=>i.type==="adhdev-daemon");return n.length===1?n[0]:null}resolveRouteId(s,r){for(const n of this.ides)if(n.id.startsWith(s)&&(!r||r===n.type))return n.id;return s}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(i=>(i==null?void 0:i.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.ideId){const r=s.agentType||s.ideType||"";return this.resolveRouteId(s.ideId,r)}if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.ideId?s.ideId:null}handleRawEvent(s,r){var v,x,w;if(!s.ideId&&s.instanceId){for(const u of this.ides)if(u.id.endsWith(`:ide:${s.instanceId}`)||u.id.endsWith(`:cli:${s.instanceId}`)){s.ideId=u.id;break}}const n=this.resolveConversationKey(s),i=n||s.instanceId||s.ideType||s.providerType||"",o=s.effectId||s.message||s.content||s.chatTitle||"",c=`${i}:${s.event}:${o}`;if(this.isDuplicate(c))return;let d=Oe(s.ideType||"");const l=this.resolveOwningDaemon(s);if(l){const u=lt(l,{fallbackId:l.id});u&&(d=s.ideType==="adhdev-daemon"?u:`${u}/${d}`)}const p=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now();let m="",f="info";if(s.event==="provider:message"){n&&s.content&&this.emitSystemMessage(n,{role:"system",timestamp:p,content:s.content,_localId:`sys_provider_${p}_${(s.content||"").slice(0,24)}`});return}else if(s.event==="provider:toast")m=s.message||"",f=s.level||"info";else if(s.event==="provider:notification"){const u=(v=s.channels)!=null&&v.length?s.channels:["toast"],k=s.preferenceKey,g=Ut("browser")&&(!k||k==="browser"||Ut(k));u.includes("bubble")&&n&&s.content&&this.emitSystemMessage(n,{role:"system",timestamp:p,content:s.content,_localId:`sys_provider_notification_${s.effectId||p}`}),u.includes("browser")&&s.title&&s.message&&g&&!document.hasFocus()&&zs(s.title,s.message,`provider-${s.effectId||p}`),u.includes("toast")&&(m=s.message||s.title||"",f=s.level||"info")}else if(s.event==="agent:generating_completed"){const u=s.duration?` (${s.duration}s)`:"";m=`✅ ${d} agent task completed${u}`,f="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(m=`⚡ ${d} approval needed`,f="warning",n&&!((x=s.modalButtons)!=null&&x.length)&&this.emitSystemMessage(n,{role:"system",timestamp:p,content:Xc(s.modalMessage,s.modalButtons),_localId:`sys_approval_${p}`}),(w=s.modalButtons)!=null&&w.length&&this.resolveActionFn){const u=this.resolveActionRouteTarget(s);if(!u)return;const k=s.agentType||s.ideType||"",g=s.ideType||"",b=this.resolveActionFn,C=Yc(s.modalButtons).map(h=>({label:h.label,variant:h.variant,onClick:()=>{b(u,"resolve_action",{action:h.action,button:h.button,buttonIndex:h.buttonIndex,agentType:k,ideType:g,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),I=Jc(d,s.modalMessage,m),N=Date.now();this.emitToast({id:N,message:I,type:f,timestamp:N,targetKey:n||u,actions:C,duration:15e3}),m=""}}else if(s.event==="monitor:long_generating"){const u=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";m=`⚠️ ${d} agent is taking a long time${u}`,f="warning",Ut("browser")&&!document.hasFocus()&&zs(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${u.replace(/[()]/g,"")}`,`long-${s.ideId||s.agentType}`)}else if(s.event==="team:view_request"){const u=s.requesterName||"A team member",k=s.requestId,g=s.orgId;if(m=`👁️ ${u} wants to view your session`,f="warning",k&&g&&this.viewRequestRespondFn){const b=Date.now(),C=Zc(g,k,this.viewRequestRespondFn,(I,N)=>console.error(`[EventManager] ${I} view request failed:`,N));this.emitToast({id:b,message:m,type:f,timestamp:b,actions:C,duration:3e4}),m=""}Ut("browser")&&!document.hasFocus()&&zs("👁️ View Request",`${u} wants to view your session`,`view-request-${k}`)}else s.event==="team:view_request_approved"?(m="✅ View request approved",f="success"):s.event==="team:view_request_rejected"&&(m=`❌ ${s.targetName||"Team member"} declined your view request`,f="warning");if(m){const u=Date.now();this.emitToast({id:u,message:m,type:f,timestamp:u,targetKey:n||s.ideId,duration:5e3})}}}const at=new Qc;function es(...t){return Bi(Ki(t))}function el({icon:t,title:s,subtitle:r,badge:n,actions:i,className:o}){return e.jsxs("div",{className:es("dashboard-header",o),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})]}),i&&e.jsx("div",{className:"flex gap-2",children:i})]})}function Js({icon:t,title:s,subtitle:r,badge:n,actions:i,widthClassName:o="max-w-6xl",contentClassName:c,children:d}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(el,{icon:t,title:s,subtitle:r,badge:n,actions:i}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",o,c),children:d})})]})}function et({title:t,icon:s,description:r,accentColor:n,className:i,children:o}){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]",i),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})]}),o]})}function Gr({icon:t,title:s,description:r,action:n,className:i}){return e.jsxs("div",{className:es("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",i),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 tl={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"},sl={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function rl({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]",tl[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:sl[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 nl={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"},al={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function il({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",nl[t],r),children:[e.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",al[t])}),n]})}function ol(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Tr(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"dark"}function Vs(t){return t==="system"?ol():t}function cl(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Vs(Tr()))}function Oa(){const[t,s]=a.useState(Tr),[r,n]=a.useState(()=>Vs(Tr()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=l=>{t==="system"&&n(l.matches?"light":"dark")};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]);const i=a.useCallback(c=>{s(c),n(Vs(c));try{localStorage.setItem("theme",c)}catch{}},[]),o=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark";n(Vs(d));try{localStorage.setItem("theme",d)}catch{}return d})},[]);return{theme:r,preference:t,setPreference:i,cycleTheme:o,isDark:r==="dark"}}function Ft({label:t,description:s,checked:r,disabled:n,onChange:i,extra:o}){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:[o,e.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>i(!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 ll({onPrefChange:t}){const[s,r]=Kc(),n=(i,o)=>{r({[i]:o}),t==null||t(i,o)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(tr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:i=>n("globalEnabled",i)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ct,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:i=>n("browserNotifications",i)}),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(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fo,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:i=>n("completionAlert",i)}),e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ho,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:i=>n("approvalAlert",i)}),e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yt,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:i=>n("disconnectAlert",i)})]}),!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 dl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function pr(t,s){return t instanceof Error?t.message:s}function ul({ides:t,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i}){const o=t.filter(c=>c.type==="adhdev-daemon");return o.length===0?e.jsx(Gr,{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:o.map(c=>e.jsx(pl,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i},c.id))})}function An({title:t,message:s,confirmLabel:r,confirmColor:n,onConfirm:i,onCancel:o}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return aa.createPortal(e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,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:d=>d.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:o,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:i,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 ml(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Pc,...Lc,...Rc].find(i=>i.id===s||s.includes(i.id)||i.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:t}}function pl({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i}){var _,P;const[o,c]=a.useState("idle"),[d,l]=a.useState(""),[p,m]=a.useState(null),[f,v]=a.useState("idle"),[x,w]=a.useState(""),u=t.version||null,k=((_=t.machine)==null?void 0:_.platform)||((P=t.system)==null?void 0:P.platform)||"",g=lt(t,{fallbackId:t.id}),b=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",C=s.filter(T=>T.daemonId===t.id&&T.transport==="cdp-page"),I=s.filter(T=>T.daemonId===t.id&&T.transport==="pty"),N=s.filter(T=>T.daemonId===t.id&&T.transport==="acp"),h=t.p2p,y=async()=>{if(r){c("upgrading"),l("Starting upgrade...");try{const T=dl(await r(t.id,"daemon_upgrade",{}));T.alreadyLatest?(c("done"),l(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(c("done"),l(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(c("error"),l(T.error||"Upgrade failed"))}catch(T){c("error"),l(pr(T,"Connection lost during upgrade"))}}},j=async()=>{if(m(null),!!n){v("loading");try{await n(t.id),v("done"),w("Machine disconnected.")}catch(T){v("error"),w(pr(T,"Failed to disconnect"))}}},S=async()=>{if(m(null),!!i){v("loading");try{await i(t.id),v("done"),w('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(T){v("error"),w(pr(T,"Failed to revoke token"))}}},E="0.8.33",D=!u||u!==E,O=C.length+I.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:b}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),u&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!D&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&D&&e.jsx("button",{onClick:y,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:o==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`↑ Update${` to v${E}`}`}),n&&e.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),i&&e.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(il,{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:[h&&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 ${h.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${h.state==="connecting"||h.state==="new"?"animate-pulse":""}`,style:h.state==="connecting"||h.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",h.state==="connected"?"connected":h.state==="connecting"||h.state==="new"?"connecting...":h.state||"off"]}),h.peers!==void 0&&h.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",h.peers," peer",h.peers!==1?"s":"",")"]})]}),h&&O>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),O>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(T=>{const L=ml(T.type),B=T.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:L.icon}),e.jsx("span",{children:L.name}),B!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},T.id)}),I.map(T=>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:T.cliName||"CLI"})]},T.id)),N.map(T=>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:T.cliName||"ACP"})]},T.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||x)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||f==="error"?"text-red-400":o==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:x||d})]}),p==="disconnect"&&e.jsx(An,{title:"🔌 Disconnect Machine",message:`Disconnect "${g}" 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:j,onCancel:()=>m(null)}),p==="revoke"&&e.jsx(An,{title:"⚠️ Remove Machine",message:`Remove "${g}" 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:S,onCancel:()=>m(null)})]})}const xl=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function fl(){const{preference:t,setPreference:s}=Oa();return e.jsx("div",{className:"flex gap-2",children:xl.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 hl(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 bl(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function xr(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Mn(t){const{r:s,g:r,b:n}=bl(t);return .2126*xr(s)+.7152*xr(r)+.0722*xr(n)}function Pn(t,s){const r=Mn(t),n=Mn(s),i=Math.max(r,n),o=Math.min(r,n);return(i+.05)/(o+.05)}function Fa(t){const s=hl(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return Pn(s,r)>=Pn(s,n)?r:n}const Ar={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},Mr={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},gl=[{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"}}}],Ua="adhdev-chat-theme",za="adhdev-chat-theme-custom";function Hs(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ua)||"ember"}catch{return"ember"}}function bt(t){try{const s=localStorage.getItem(za);if(s){const r=JSON.parse(s);return{...t==="dark"?Ar:Mr,...r[t]}}}catch{}return t==="dark"?Ar:Mr}function Rs(t,s){try{localStorage.setItem(za,JSON.stringify({dark:t,light:s}))}catch{}}function mt(t,s){const r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),i=parseInt(t.slice(5,7),16);return`rgba(${r}, ${n}, ${i}, ${s})`}function Zs(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),i=Math.min(255,parseInt(t.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}const yl={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function vs(t,s){var i;const r=(i=yl[t])==null?void 0:i[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Zs(r,24)),n.style.setProperty("--accent-on-primary",Fa(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Zs(r,18)})`),n.style.setProperty("--border-accent",mt(r,.35)),n.style.setProperty("--nav-active-bg",mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${mt(r,.06)}`)}function zt(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",mt(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",mt(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",mt(t.borderSubtle,.25)),s.style.setProperty("--text-primary",t.textPrimary),s.style.setProperty("--text-secondary",t.textSecondary),s.style.setProperty("--text-muted",t.textMuted),s.style.setProperty("--border-subtle",mt(t.borderSubtle,.5)),s.style.setProperty("--border-default",mt(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",Zs(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Fa(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${Zs(t.accentColor,40)})`),s.style.setProperty("--border-accent",mt(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",mt(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${mt(t.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",t.userBubble),s.style.setProperty("--chat-user-color",t.userText),s.style.setProperty("--chat-user-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px 4px ${t.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",t.assistantBubble),s.style.setProperty("--chat-assistant-color",t.assistantText),s.style.setProperty("--chat-assistant-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px ${t.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${mt(t.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",t.containerBg),s.style.setProperty("--dashboard-pane-bg",t.containerBg),s.style.setProperty("--chat-thought-accent",t.accentColor),s.style.setProperty("--chat-tool-accent",t.accentColor),s.style.setProperty("--chat-action-color",t.accentColor),s.style.setProperty("--chat-send-bg",t.sendButton),s.style.setProperty("--chat-input-border",t.inputBorder)}function Yr(){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 vl(t){try{localStorage.setItem(Ua,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";zt(bt(s))}else Yr(),vs(t,Vt()?"dark":"light")}function wl(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=Hs();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";zt(bt(s))}else Yr(),vs(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 rt({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 jl({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,i]=a.useState(()=>bt(r));a.useEffect(()=>{i(bt(r))},[r]);const o=a.useCallback((c,d)=>{i(l=>{const p={...l,[c]:d},f=bt(r==="dark"?"light":"dark");return r==="dark"?Rs(p,f):Rs(f,p),zt(p),s(p),p})},[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(rt,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),e.jsx(rt,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),e.jsx(rt,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),e.jsxs(bs,{title:"App Text",children:[e.jsx(rt,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),e.jsx(rt,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),e.jsx(rt,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),e.jsxs(bs,{title:"Borders & Accent",children:[e.jsx(rt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),e.jsx(rt,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),e.jsx(rt,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(bs,{title:"Chat Bubbles",children:[e.jsx(rt,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),e.jsx(rt,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),e.jsx(rt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),e.jsx(rt,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),e.jsxs(bs,{title:"Chat Layout",children:[e.jsx(rt,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),e.jsx(rt,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),e.jsx(rt,{label:"Input border",value:n.inputBorder,onChange:c=>o("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=>o("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?Ar:Mr,l=bt(t?"light":"dark");t?Rs(c,l):Rs(l,c),i(c),zt(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 kl(){const[t,s]=a.useState(Hs),[r,n]=a.useState(!0),[i,o]=a.useState(()=>bt("dark"));a.useEffect(()=>{n(Vt());const l=new MutationObserver(()=>{const f=Vt();n(f);const v=Hs();v==="custom"?zt(bt(f?"dark":"light")):vs(v,f?"dark":"light")});l.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=Vt();n(f);const v=Hs();v==="custom"?zt(bt(f?"dark":"light")):vs(v,f?"dark":"light")};return p.addEventListener("change",m),()=>{l.disconnect(),p.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?zt(bt(r?"dark":"light")):(Yr(),vs(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{o(bt(r?"dark":"light"))},[r]);const c=l=>{s(l),vl(l)},d=[...gl,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText},light:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText}}}];return e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(l=>{const p=t===l.id,m=r?l.preview.dark:l.preview.light,f=l.id==="honey"||l.id==="ember"?"#1a1a1a":l.id==="custom"?i.userText:"#fff";return e.jsxs("button",{onClick:()=>c(l.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&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:l.id==="custom"?"🎨 Custom":l.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:l.description})]})]})]},l.id)})}),t==="custom"&&e.jsx(jl,{dark:r,onColorsChange:l=>o(l)})]})}const Va="adhdev_mobileDashboardMode_v1";function Ha(){try{return localStorage.getItem(Va)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Nl(t){try{localStorage.setItem(Va,t)}catch{}}function Sl(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(Ha()==="chat")},[]),e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Tt,{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),Nl(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}const qa="adhdev_hiddenTabs";function Cl(){try{const t=localStorage.getItem(qa);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function rs(t){try{localStorage.setItem(qa,JSON.stringify([...t]))}catch{}}function Il(){const[t,s]=a.useState(Cl),r=a.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),rs(f),f})},[]),n=a.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),rs(f),f})},[]),i=a.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),rs(f),f})},[]),o=a.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return rs(m),m})},[]),c=a.useCallback((p,m)=>{s(f=>{const v=new Set(f);for(const x of m)v.add(x);return rs(v),v})},[]),d=a.useCallback((p,m)=>{s(f=>{const v=new Set(f);for(const x of m)v.delete(x);return rs(v),v})},[]),l=a.useCallback(p=>t.has(p),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:i,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:d,isHidden:l}}function _l({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Oc()},[]);const i=a.useMemo(()=>t.map(o=>({id:o.tabKey,name:Pa(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[t]);return Uc(i),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const l=Date.now(),p={};for(const[m,f]of Object.entries(d))l-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(d).length?d:p})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const l=d.filter(p=>p.timestamp>c).slice(-100);return l.length===d.length?d:l})},6e4);return()=>clearInterval(o)},[n]),null}function Tl(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Ht(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return Tl(s==null?void 0:s.receivedAt)||0}function Pr(t,s=0){return Ht(t)||s||0}function Ga(t){return Ht(t)}function Ya(t,s,r=Ga){const n=r(s)-r(t);if(n!==0)return n;const i=(t.machineName||"").localeCompare(s.machineName||"");if(i!==0)return i;const o=t.displayPrimary.localeCompare(s.displayPrimary);if(o!==0)return o;const c=t.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:t.tabKey.localeCompare(s.tabKey)}function Lr(t){var r;const s=nt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Al(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!Lr(t)&&!t.title.trim()}function Ml(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(Lr(r))-Number(Lr(s));if(n!==0)return n;const i=r.messages.length-s.messages.length;return i!==0?i:Ya(s,r)})[0]||null}function At(t,s){const r=t.filter(c=>c.ideId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,i=r.filter(c=>c.streamSource==="agent-stream"),o=Ml(i);return n?o&&Al(n)?o:n:o||r[0]||null}function Pl(t){const s=t.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const i=r.get(n.id);if(!i){r.set(n.id,n);continue}const o=(i.workspace?1:0)+(i.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(i.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Es(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 Ll(t,s){const r=Date.now();return t.map(n=>{const i=s[n.tabKey];return i&&r-i<5e3?{...n,messages:[],title:""}:n})}function Rl(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 i of t.childSessions||[]){const o=i.id||i.providerType,c=`${t.id}:${o}`;r.push({key:c,ref:s[c]}),r.push({key:i.id,ref:s[i.id]})}return r}function El(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 $l(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Dl(t){const s=$l(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=Xt(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Bl({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:i}){const o=a.useRef([]),c=a.useRef([]),d=a.useRef([]),l=a.useRef([]),p=a.useMemo(()=>{const h=Pl(t);return Es(o.current,h)?o.current:(o.current=h,h)},[t]),m=a.useMemo(()=>Ra(t),[t]),f=a.useRef(new Map),v=a.useRef(new Map),x=a.useMemo(()=>{const h=new Map,y=[];for(const D of p){const{connectionState:O="new",machineName:_}=Ea(D,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),P=Rl(D,r),T=f.current.get(D.id);if(T&&T.ide===D&&T.connectionState===O&&T.machineName===_&&El(T.localRefs,P)){h.set(D.id,T),y.push(...T.conversations);continue}const L=Hr(D,r,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),B={ide:D,connectionState:O,machineName:_,localRefs:P,conversations:L};h.set(D.id,B),y.push(...L)}f.current=h;const j=new Map,S=D=>{const O=Dl(D),_=v.current.get(D.tabKey);if(_&&_.signature===O)return j.set(D.tabKey,_),_.timestamp;const P={signature:O,timestamp:Ga(D)||(_==null?void 0:_.timestamp)||0};return j.set(D.tabKey,P),P.timestamp},E=[...y].sort((D,O)=>Ya(D,O,S));return v.current=j,E},[p,r,s,m]),w=a.useMemo(()=>{const h=Ll(x,n);return Es(c.current,h)?c.current:(c.current=h,h)},[x,n]),u=a.useMemo(()=>{const h=new Map,y=Array.from(new Set(w.map(j=>j.ideId)));for(const j of y){const S=At(w,j);S&&h.set(j,S)}return h},[w]),k=a.useMemo(()=>{const h=new Map;for(const y of w)if(y.sessionId&&h.set(y.sessionId,y),y.streamSource==="native"&&y.sessionId){const j=u.get(y.ideId);j&&h.set(y.sessionId,j)}return h},[w,u]),g=a.useMemo(()=>{const h=new Map;for(const y of w)y.sessionId&&h.set(y.sessionId,y),h.set(y.ideId,u.get(y.ideId)||y),h.set(y.tabKey,y);return h},[w,u]),b=a.useCallback(h=>{if(h)return k.get(h)},[k]),C=a.useCallback(h=>{if(h)return g.get(h)},[g]),I=a.useMemo(()=>{const h=w.filter(y=>!i.has(y.tabKey));return Es(d.current,h)?d.current:(d.current=h,h)},[w,i]),N=a.useMemo(()=>{const h=I.map(y=>y.tabKey);return Es(l.current,h)?l.current:(l.current=h,h)},[I]);return{chatIdes:p,conversations:w,visibleConversations:I,visibleTabKeys:N,resolveConversationBySessionId:b,resolveConversationByTarget:C}}function Kl({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const i=a.useMemo(()=>{var d;return t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),o=a.useMemo(()=>{var d;return!t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(d=>{const l=new URLSearchParams(d);return l.delete("activeTab"),l},{replace:!0})},[n,s]);return{requestedDesktopTabKey:i,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function Wl({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:i}){a.useEffect(()=>{at.setIdes(t)},[t]),a.useEffect(()=>{at.setResolveAction((o,c,d)=>{s(o,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const o=at.onToast(l=>{r(m=>m.some(v=>v.message===l.message&&l.timestamp-v.timestamp<3e3)?m:[...m.slice(-4),{id:l.id,message:l.message,type:l.type,timestamp:l.timestamp,targetKey:l.targetKey,actions:l.actions}]);const p=l.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==l.id)),p)}),c=at.onSystemMessage((l,p)=>{var x,w;const m=i(l),f=(x=p._localId)==null?void 0:x.startsWith("sys_approval_"),v=!!(m&&(m.status==="waiting_approval"||(w=m.modalButtons)!=null&&w.length||m.modalMessage));f&&v||n(u=>({...u,[l]:[...u[l]||[],p]}))}),d=at.onClearSystemMessage((l,p)=>{n(m=>{var f;return(f=m[l])!=null&&f.length?{...m,[l]:m[l].filter(v=>{var x;return!(v.role==="system"&&((x=v._localId)!=null&&x.startsWith(p)))})}:m})});return()=>{o(),c(),d()}},[r,n]),a.useEffect(()=>{const o=Ta.on("status_event",c=>{!c||typeof c!="object"||typeof c.event!="string"||at.handleRawEvent(c,"ws")});return()=>{o()}},[]),a.useEffect(()=>{var c;const o=d=>{var k;const l=d.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.ideId||l.targetSessionId||l.targetKey))return;const p=l.targetSessionId||l.targetKey||l.ideId,m=i(p),f=(m==null?void 0:m.ideId)||l.ideId;if(!f)return;const v=Number(l.buttonIndex),x=l.button||((k=m==null?void 0:m.modalButtons)==null?void 0:k[v])||"Approve",w=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);s(f,"resolve_action",{action:u?"approve":"reject",button:x,...Number.isFinite(v)&&{buttonIndex:v},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",o),()=>{var d;return(d=navigator.serviceWorker)==null?void 0:d.removeEventListener("message",o)}},[i,s])}const Ol="adhdev_dashboardLayout_v1",Fl="adhdev_dashboardDockview_v1",gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Xa(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function Ja(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Za(t){return`${Ol}:${t}`}function Ul(t){const s=Za(t);return Xa(s,null)}function zl(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=Za(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Qa(t){return`${Fl}:${t}`}function Vl(t){const s=Qa(t);return Xa(s,null)}function Hl(t,s){try{const r=Qa(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function ql(){return{groupAssignments:[...gs.groupAssignments],focusedGroup:gs.focusedGroup,groupActiveTabIds:{...gs.groupActiveTabIds},groupTabOrders:{...gs.groupTabOrders},groupSizes:[...gs.groupSizes]}}function Gl(){const[t]=a.useState(()=>Ja(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,i]=a.useState(0),[o,c]=a.useState({}),[d,l]=a.useState({}),[p,m]=a.useState([]),[f,v]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[x,w]=a.useState(!1),u=a.useCallback(()=>{if(x)return;const k=Ul(t)??ql();r(new Map(k.groupAssignments)),i(k.focusedGroup),c(k.groupActiveTabIds),l(k.groupTabOrders),m(k.groupSizes),w(!0)},[x,t]);return a.useEffect(()=>{x&&zl(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:d,groupSizes:p})},[x,t,s,n,o,d,p]),a.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),g=b=>v(b.matches);return k.addEventListener("change",g),()=>k.removeEventListener("change",g)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:i,groupActiveTabIds:o,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:l,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:x,hydrateStoredLayout:u}}function Yl({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:i,hydrateStoredLayout:o,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:l,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:v,handleRefreshHistory:x}){const w=a.useRef(!1),u=a.useRef(!1),k=a.useRef(null),g=a.useRef(!1);a.useEffect(()=>{if(!t||w.current||s.length===0)return;if(!i){o();return}const b=r(t);if(!b)return;const C=n.get(b.tabKey)??0;c(I=>({...I,[C]:b.tabKey})),d(C),w.current=!0,u.current=!0,k.current!=null&&(window.clearTimeout(k.current),k.current=null),l(I=>{const N=new URLSearchParams(I);return N.delete("activeTab"),N},{replace:!0})},[t,s,r,n,i,o,c,d,l]),a.useEffect(()=>{if(!(u.current||i)&&s.length!==0){if(!t){o(),u.current=!0;return}if(w.current){u.current=!0;return}if(k.current==null)return k.current=window.setTimeout(()=>{k.current=null,!(u.current||i)&&(o(),u.current=!0)},1500),()=>{k.current!=null&&(window.clearTimeout(k.current),k.current=null)}}},[t,s.length,i,o]),a.useEffect(()=>{if(!p){g.current=!1;return}if(!m||g.current||f)return;const b=v.find(C=>C.id===m.ideId);b&&(!b.chats||b.chats.length===0)&&(g.current=!0,x())},[p,m,f,v,x]),a.useEffect(()=>{if(!m)return;let b=null,C=0,I=-1,N=0;const h=()=>{b=null;const y=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(S=>S.offsetParent!==null);if(y.length===0){C<18&&(C+=1,b=requestAnimationFrame(h));return}let j=0;for(const S of y)S.scrollTop=S.scrollHeight,j+=S.scrollHeight;j===I?N+=1:(N=0,I=j),C+=1,!(N>=2||C>=18)&&(b=requestAnimationFrame(h))};return b=requestAnimationFrame(h),()=>{b!=null&&cancelAnimationFrame(b)}},[m==null?void 0:m.tabKey])}function Xl({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:o,ides:c,resolveConversationByTarget:d}){const[l,p]=a.useState(null),[m,f]=a.useState(null),v=a.useMemo(()=>{if(t||!n)return null;const g=d(n);return g&&!Ke(g)&&!De(g)?g:null},[t,n,d]),x=a.useMemo(()=>{const g=l==null?void 0:l.ideId;if(!g)return null;const b=l!=null&&l.tabKey?o.find(C=>C.tabKey===l.tabKey):i?o.find(C=>C.tabKey===i):null;return(b==null?void 0:b.ideId)===g?b:At(o,g)},[o,l,i]),w=a.useMemo(()=>{if(x)return c.find(g=>g.id===x.ideId)},[c,x]);a.useEffect(()=>{v&&(p({ideId:v.ideId,tabKey:vn(v)}),f(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const u=a.useCallback(g=>{g&&(p({ideId:g.ideId,tabKey:vn(g)}),f(g))},[]),k=a.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:x,remoteDialogIdeEntry:w,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:u,closeRemoteDialog:k}}function cs(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return Ke(t)||De(t)?{...s,agentType:Jt(t)}:t.streamSource==="agent-stream"?{...s,agentType:Jt(t)}:s}function Ss(t){return t?Fr(t):""}function $s(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ln({sendDaemonCommand:t,activeConv:s,updateIdeChats:r,setToasts:n,setLocalUserMessages:i,setClearedTabs:o}){const[c,d]=a.useState(!1),[l,p]=a.useState(!1),m=a.useCallback(async w=>{try{await t("standalone","launch_ide",{ideType:w,enableCdp:!0})}catch(u){console.error("Launch failed",u)}},[t]),f=a.useCallback(async(w,u)=>{try{const k=w||(s==null?void 0:s.daemonId)||"",g=await t(k,"switch_chat",{id:u,sessionId:u,...cs(s)}),b=g==null?void 0:g.result;if((g==null?void 0:g.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?$s(n,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?$s(n,`⚠️ Switch error: ${b}`):$s(n,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),$s(n,`❌ Switch failed: ${k.message||"connection error"}`)}},[s,t,n]),v=a.useCallback(async()=>{if(!(!s||c)){d(!0);try{const w=Ss(s);await t(w,"new_chat",{...cs(s)}),o(u=>({...u,[s.tabKey]:Date.now()})),i(u=>({...u,[s.tabKey]:[]}))}catch(w){console.error("New chat failed",w)}finally{d(!1)}}},[s,c,t,o,i]),x=a.useCallback(async()=>{var w;if(!(!s||l)){p(!0);try{const u=Ss(s),k=await t(u,"list_chats",{forceExpand:!0,...cs(s)}),g=(k==null?void 0:k.chats)||((w=k==null?void 0:k.result)==null?void 0:w.chats);k!=null&&k.success&&Array.isArray(g)&&r(s.ideId,g)}catch(u){console.error("Refresh history failed",u)}finally{p(!1)}}},[s,l,t,r]);return{isCreatingChat:c,isRefreshingHistory:l,handleLaunchIde:m,handleSwitchSession:f,handleNewChat:v,handleRefreshHistory:x}}function Jl(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 Zl(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function Rn(t,s){const r=Object.keys(t),n=Object.keys(s);return r.length!==n.length?!1:r.every(i=>s[Number(i)]===t[Number(i)])}function Ds(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of t)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const i={};n.forEach((c,d)=>{i[c]=d}),n.length===0&&(i[0]=0);const o=new Map;for(const[c,d]of t){if(!r.has(c)||d<=0)continue;const l=i[d];typeof l=="number"&&l>0&&o.set(c,l)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:i,usedGroups:n}}function En(t,s){const r={};for(const[n,i]of Object.entries(t)){const o=s[Number(n)];typeof o=="number"&&(r[o]=i)}return r}function Ql(t,s,r){if(s.length===0)return 0;if(typeof r[t]=="number")return r[t];const n=[...s].reverse().find(i=>i<t)??s[0];return r[n]??0}function ed(t,s,r){if(s.length<=1)return[];const n=s.map(c=>t[c]).filter(c=>Number.isFinite(c)),i=n.length===s.length?n:Array(r).fill(100/r),o=i.reduce((c,d)=>c+d,0);return o>0?i.map(c=>c/o*100):Array(r).fill(100/r)}function $n(t,s){const r={};for(const[n,i]of Object.entries(t)){const o=Number(n);r[o>=s?o+1:o]=i}return r}function Dn(t){return Array(t).fill(100/t)}function td({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:i,groupSizes:o,setGroupSizes:c,isMobile:d,visibleConversations:l,visibleTabKeys:p}){const m=a.useRef(null),f=a.useMemo(()=>Ds(t,p),[t,p]),v=f.assignments,x=a.useMemo(()=>d?1:f.groupCount,[f.groupCount,d]),w=x>1,u=a.useCallback((N,h)=>{s(y=>{const j=new Map(Ds(y,p).assignments);return h===0?j.delete(N):j.set(N,h),j}),n(y=>({...y,[h]:N})),r(h)},[s,p,n,r]),k=a.useCallback(N=>{s(h=>{const y=Ds(h,p).assignments,j=new Map;for(const[S,E]of y)E!==N&&(E>N?j.set(S,E-1):j.set(S,E));return j}),c(h=>{if(h.length<=1)return[];const y=[...h];y.splice(N,1);const j=y.reduce((S,E)=>S+E,0);return j>0?y.map(S=>S/j*100):[]}),r(0)},[s,p,c,r]),g=a.useCallback((N,h)=>{h.preventDefault();const y=m.current;if(!y)return;const j=h.clientX,S=y.offsetWidth,E=o.length===x?[...o]:Dn(x),D=_=>{const T=(_.clientX-j)/S*100,L=[...E];L[N]=Math.max(15,E[N]+T),L[N+1]=Math.max(15,E[N+1]-T),c(L)},O=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",O),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",D),document.addEventListener("mouseup",O)},[o,x,c]),b=a.useCallback((N,h,y)=>{if(x>=4)return;const j=y==="left"?h:h+1;s(S=>{const E=Ds(S,p).assignments,D=new Map;for(const O of l){const _=E.get(O.tabKey)??0,P=_>=j?_+1:_;P>0&&D.set(O.tabKey,P)}return j>0&&D.set(N,j),D}),c(S=>{const E=S.length===x?[...S]:Dn(x),D=E[h]??100/x,O=Math.max(15,D/2),_=Math.max(15,D/2),P=[...E];P[h]=O,P.splice(j,0,_);const T=P.reduce((L,B)=>L+B,0);return P.map(L=>L/T*100)}),n(S=>{const E=$n(S,j);return E[j]=N,E}),i(S=>{const E=$n(S,j);return E[j]=[N],E}),r(j)},[x,s,p,l,c,n,i,r]);a.useEffect(()=>{Jl(t,v)||s(v)},[t,v,s]),a.useEffect(()=>{const{mapping:N,usedGroups:h}=f;n(y=>{const j=En(y,N);return Rn(y,j)?y:j}),i(y=>{const j=En(y,N);return Rn(y,j)?y:j}),r(y=>{const j=d?0:Ql(y,h,N);return y===j?y:j}),c(y=>{const j=d?[]:ed(y,h,f.groupCount);return Zl(y,j)?y:j})},[f,d,n,i,r,c]);const C=a.useMemo(()=>{const N=Array.from({length:x},()=>[]);for(const h of l){const y=v.get(h.tabKey)??0,j=Math.min(y,x-1);N[j].push(h)}return N},[l,v,x]),I=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:v,numGroups:x,isSplitMode:w,groupedConvs:C,moveTabToGroup:u,closeGroup:k,handleResizeStart:g,splitTabRelative:b,clearAllSplits:I}}function sd({ides:t,sendDaemonCommand:s}){const r="0.8.33",n=a.useMemo(()=>t.filter(p=>{if(p.type!=="adhdev-daemon")return!1;const m=p.version||p.daemonVersion||null;return!m||!r?!1:m!==r}),[r,t]),[i,o]=a.useState(!1),[c,d]=a.useState({}),l=a.useCallback(async p=>{var m,f;d(v=>({...v,[p]:"upgrading"}));try{const v=await s(p,"daemon_upgrade",{});(m=v==null?void 0:v.result)!=null&&m.upgraded||(f=v==null?void 0:v.result)!=null&&f.success?d(x=>({...x,[p]:"done"})):d(x=>({...x,[p]:"error"}))}catch{d(v=>({...v,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:o,upgradingDaemons:c,handleBannerUpgrade:l}}function Bn(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function Xr(t){return t instanceof Error?t.message:String(t||"")}function Kn(t){const s=Xr(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Wn(t,s){const r=Xr(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function nr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:i}){const[o,c]=a.useState(!1),[d,l]=a.useState(!1),p=a.useRef(!1),m=a.useRef(null),f=a.useCallback(async u=>{if(!s)return;const k=u.trim();if(!k||p.current)return;const g=s.tabKey,b=Date.now(),C=m.current;if(C&&C.tabKey===g&&C.message===k&&b-C.timestamp<2e3)return;p.current=!0,l(!0),m.current={tabKey:g,message:k,timestamp:b};const I=`${b}-${Math.random().toString(36).slice(2,8)}`,N={role:"user",content:k,timestamp:b,_localId:I};r(h=>({...h,[g]:[...h[g]||[],N]}));try{const h=Ss(s);if(!h)return;const y=await t(h,"send_chat",{message:k,...cs(s)}),j=Bn(y);if(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1){r(S=>({...S,[g]:(S[g]||[]).filter(E=>E._localId!==I)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const S=Date.now()-6e4;r(E=>{const D=E[g];if(!D)return E;const O=D.filter(_=>_.timestamp>S);return O.length===D.length?E:{...E,[g]:O}})},6e4)}catch(h){const y=Xr(h);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",h),r(j=>({...j,[g]:(j[g]||[]).filter(S=>S._localId!==I)}))}finally{p.current=!1,l(!1)}},[s,t,r]),v=a.useCallback(async()=>{if(s)try{await t(s.ideId,"launch_ide",{ideType:s.ideType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),x=a.useCallback(async u=>{if(s)try{const g=(s.modalButtons||[]).indexOf(u),b=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(b),I=Ss(s);if(!I)return;const N=await t(I,"resolve_action",{button:u,action:C?"approve":"reject",...g>=0&&{buttonIndex:g},...cs(s)}),h=Bn(N);h.success||n(y=>[...y,{ideId:s.tabKey,text:Wn(u,h==null?void 0:h.error),timestamp:Date.now()}])}catch(k){Kn(k)||console.error("[ModalButton] Error:",k),n(g=>[...g,{ideId:s.tabKey,text:Kn(k)?Wn(u,k):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),w=a.useCallback(async()=>{if(!(!s||o)){c(!0);try{await t(s.ideId,"focus_session",{agentType:s.agentType,...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,o,t]);return{isSendingChat:d,isFocusingAgent:o,handleSendChat:f,handleRelaunch:v,handleModalButton:x,handleFocusAgent:w}}const Jr=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:i,terminalRef:o,handleModalButton:c,handleRelaunch:d,handleSendChat:l,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:x,scrollToBottomRequestNonce:w,isInputActive:u=!0}){return e.jsxs(e.Fragment,{children:[e.jsx(va,{activeConv:s,onModalButton:c}),s.transport!=="pty"&&s.transport!=="acp"&&s.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(Lt,{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:d,children:"Relaunch with CDP"})]})}):null,s.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(hc,{activeConv:s,clearToken:r,terminalRef:o,handleSendChat:l,isSendingChat:p,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(_r,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:x,scrollToBottomRequestNonce:w,isInputActive:u})})]}):e.jsx(_r,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:x,scrollToBottomRequestNonce:w,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function rd({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:i,userName:o,isSendingChat:c,isFocusingAgent:d,onBack:l,onOpenNativeConversation:p,onOpenMachine:m,onOpenHistory:f,onOpenRemote:v,onHideConversation:x,onStopCli:w,cliViewMode:u,onSetCliViewMode:k,handleSendChat:g,handleFocusAgent:b,handleModalButton:C,handleRelaunch:I}){const N=a.useRef(null),h=Ke(t)&&!s,y=h&&u==="terminal",j=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 ${j} 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:l,type:"button","aria-label":"Back",children:e.jsx(Er,{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(Sa,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h&&u&&e.jsx(zr,{mode:u,onChange:k,compact:!0}),h&&w&&e.jsx("button",{onClick:()=>{w(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(Rt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(t),type:"button",children:e.jsx(Dr,{size:14})}),!s&&!h&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(t),type:"button",children:e.jsx(ct,{size:14})}),x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(t),type:"button",title:"Close chat",children:e.jsx(Rt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Jr,{activeConv:t,clearToken:0,isCliTerminal:y,ideEntry:n,terminalRef:N,handleModalButton:C,handleRelaunch:I,handleSendChat:g,isSendingChat:c,handleFocusAgent:b,isFocusingAgent:d,actionLogs:i,userName:o})})]})}const fr={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 nd(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ei(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[i,o]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(nd())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(fr[c].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!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:d,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:fr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:fr[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:i?"✓":"📋"})]}),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 ti({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:ct},{key:"chats",label:"Chats",icon:Tt}];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:i,icon:o})=>{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(o,{size:15})}),e.jsx("span",{children:i})]},n)})})})}function Bs({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 ns({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 ys({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 Ks({item:t,type:s,getAvatarText:r,onOpenConversation:n}){const i=s==="needs_attention"||s==="task_complete",o=s==="working",c=s==="earlier",{isReconnecting:d,isConnecting:l}=ps(t.conversation),p=Ve(t.conversation),m=Qt(t.conversation),f=Ma(t.conversation,{requiresAction:s==="needs_attention"});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] ${i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":"bg-transparent"} ${c?"opacity-70 saturate-50":""}`,onClick:()=>n(t.conversation),type:"button",children:[i||o?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?"bg-accent-primary shadow-glow":o?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":"bg-bg-primary border border-border-subtle text-text-secondary"}`,style:i?{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 text-text-primary truncate tracking-tight",children:p}),!o&&e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:ya(t.timestamp)})]}),e.jsxs("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:[m,d?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-orange-400 animate-pulse",children:"Reconnecting…"})]}):l?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):f==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-orange-400",children:"Action needed"})]})]}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:t.preview})]}),i&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),o&&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 On({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 ad({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:i,hiddenConversations:o,machineCards:c,getAvatarText:d,onOpenConversation:l,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:x,onSectionChange:w,wsStatus:u="connected",isStandalone:k=!1}){const g=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",b=c.length>0,C=s.length>0||r.length>0||n.length>0||i.length>0,I=t==="machines"?"Machines":"Chats",N=k?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",h=k?"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:I}),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(tr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:x,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(er,{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] ${h}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:g?e.jsx(ys,{icon:e.jsx(On,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(ys,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:k?"Waiting for your daemon":"Connect your first machine",subtitle:k?"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:!k&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(ei,{})})}):e.jsx(ns,{children:c.map((y,j)=>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] ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(y.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:d(y.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:y.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:y.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[y.unread," new"]}):y.total>0?`${y.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:y.subtitle}),y.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[y.total," chat",y.total!==1?"s":"",y.unread>0?` · ${y.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},y.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(Bs,{title:"Needs attention",className:"mb-0"}),e.jsx(ns,{children:s.map((y,j)=>e.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:e.jsx(Ks,{item:y,type:"needs_attention",getAvatarText:d,onOpenConversation:l})},y.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(Bs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(ns,{children:r.map((y,j)=>e.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:e.jsx(Ks,{item:y,type:"task_complete",getAvatarText:d,onOpenConversation:l})},y.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(Bs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(ns,{children:n.map((y,j)=>e.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:e.jsx(Ks,{item:y,type:"working",getAvatarText:d,onOpenConversation:l})},y.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[i.length>0&&e.jsx(Bs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),i.length>0?e.jsx(ns,{children:i.map((y,j)=>e.jsx("div",{className:j>0?"border-t border-border-subtle/70":"",children:e.jsx(Ks,{item:y,type:"earlier",getAvatarText:d,onOpenConversation:l})},y.conversation.tabKey))}):C?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):g?e.jsx(ys,{icon:e.jsx(On,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?e.jsx(ys,{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(Tt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are connected. Open the machine screen, choose a workspace, then launch your first IDE, CLI, or ACP session."}):e.jsx(ys,{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"&&o.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(ns,{className:"bg-bg-secondary/25",children:o.map((y,j)=>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 ${j>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(y),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:d(Ve(y))}),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(y)}),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(y)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},y.tabKey))})]})]}),t==="chats"&&f&&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:f,"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(ti,{section:t,onSectionChange:w})]})}function id(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(),i=(r[2]||"").replace(/[\\/]+/g,"\\");return i?`${n}:\\${i}`:`${n}:\\`}return null}function ar(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=id(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 od(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 ir(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 i=typeof(n==null?void 0:n.path)=="string"?n.path:r,o=i.includes("\\")?"\\":"/",c=(l,p)=>/^[A-Za-z]:\\?$/.test(l)?`${l.replace(/\\?$/,"\\")}${p}`:l==="/"||l==="\\"?`${o}${p}`:`${l.replace(/[\\/]+$/,"")}${o}${p}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(l=>(l==null?void 0:l.type)==="directory"&&typeof(l==null?void 0:l.name)=="string").map(l=>({name:l.name,path:c(i,l.name)})).sort((l,p)=>l.name.localeCompare(p.name)):[];return{path:i,directories:d}}function or({title:t,description:s,currentPath:r,directories:n,busy:i=!1,error:o="",confirmLabel:c="Use this folder",onClose:d,onNavigate:l,onConfirm:p}){const[m,f]=a.useState(r);a.useEffect(()=>{f(r)},[r]);const v=od(r),x=m.trim();return e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:e.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:e.jsx(Rt,{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:()=>{!v||i||l(v)},disabled:!v||i,children:[e.jsx(Er,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:w=>f(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!x||i||(w.preventDefault(),l(x))},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:()=>{!x||i||l(x)},disabled:!x||i,children:"Go"})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:i?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?e.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):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(w=>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:()=>l(w.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(ls,{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:w.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:w.path})]})]},w.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:d,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(x||r),disabled:!x&&!r||i,children:c})]})]})})}function Zr({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:i,onWorkspaceChange:o,confirmLabel:c="Launch",busy:d=!1,showArgsInput:l,argsValue:p,onArgsChange:m,showModelInput:f,modelValue:v,onModelChange:x,historyProviderNode:w,onConfirm:u,onCancel:k}){const g=n==null?void 0:n.find(b=>b.key===i);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:k,"aria-label":"Close launch confirmation",children:e.jsx(Rt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&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:i||"",onChange:b=>o(b.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:n.map(b=>e.jsx("option",{value:b.key,children:b.label},b.key))}),(g==null?void 0:g.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),w,r.map(b=>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:b.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:b.value})]},`${b.label}:${b.value}`)),f&&x&&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:v||"",onChange:b=>x(b.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:d})]}),l&&m&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),e.jsx("input",{type:"text",value:p||"",onChange:b=>m(b.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:d})]})]}),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:k,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:u,disabled:d,children:[e.jsx(Kr,{size:14}),d?"Launching…":c]})]})]})})}function Fn(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function qt(t){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:i=!0}=t,o=[];i&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const l of s.workspaces||[])o.push({key:`saved:${l.id}`,label:`${l.id===s.defaultWorkspaceId?"⭐ ":""}${Fn(l.path,l.label)}`,description:l.path,workspaceId:l.id,workspacePath:l.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(l=>l.path===c):null;if(c&&!d&&o.push({key:`custom:${c}`,label:Fn(c),description:c,workspaceId:null,workspacePath:c}),n){const l=`saved:${n}`;if(o.some(p=>p.key===l))return{options:o,selectedKey:l}}return d?{options:o,selectedKey:`saved:${d.id}`}:c?{options:o,selectedKey:`custom:${c}`}:{options:o,selectedKey:"__home__"}}function hr(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function cd({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:i,onListSavedSessions:o}){var ee,ye,A,q;const[c,d]=a.useState(!1),l=(((ee=t.detectedIdes)==null?void 0:ee.length)||0)>0,p=a.useMemo(()=>(t.workspaces||[]).map(F=>({id:F.id,path:F.path,label:F.label})),[t]),m=t.defaultWorkspaceId||null,[f,v]=a.useState(m||((ye=p[0])==null?void 0:ye.id)||""),[x,w]=a.useState(""),[u,k]=a.useState(""),[g,b]=a.useState([]),[C,I]=a.useState(!1),[N,h]=a.useState(""),[y,j]=a.useState(!1),[S,E]=a.useState(hr(l,s.length,r.length)),D=a.useRef(null),[O,_]=a.useState(null),P=a.useRef("__home__"),[T,L]=a.useState("__home__"),[B,J]=a.useState(""),[K,$]=a.useState(""),[W,V]=a.useState(""),[H,te]=a.useState([]),[ke,X]=a.useState(!1),[Z,G]=a.useState(!1),fe=a.useRef(null),re=f==="__custom__"?x.trim():((A=p.find(F=>F.id===f))==null?void 0:A.path)||"",he=f==="__custom__"&&!!re&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=f!=="__custom__"&&((q=p.find(F=>F.id===f))==null?void 0:q.path)||"",ie=a.useCallback(async F=>{I(!0),h("");try{const ae=await i(F);k(ae.path),w(ae.path),b(ae.directories)}catch(ae){h(ae instanceof Error?ae.message:"Could not load folder")}finally{I(!1)}},[i]),pe=a.useCallback(()=>{var ae,de;v("__custom__"),j(!0);const F=ar(t.platform,[x.trim(),ve,(ae=p.find(Ce=>Ce.id===m))==null?void 0:ae.path,(de=p[0])==null?void 0:de.path]);ie(F)},[x,m,ie,ve,t.platform,p]),oe=a.useCallback(F=>{if(F!=null&&F.workspaceId){v(F.workspaceId),w("");return}if(F!=null&&F.workspacePath){v("__custom__"),w(F.workspacePath);return}v(""),w("")},[]),ge=a.useCallback(F=>{if(v(F),F==="__custom__"){pe();return}w("")},[pe]),Y=a.useCallback(F=>{v("__custom__"),w(F)},[]),se=a.useCallback((F,ae)=>{D.current=ae,P.current=F.selectedWorkspaceKey||"__home__",L(F.selectedWorkspaceKey||"__home__"),J(F.initialArgs||""),$(F.initialModel||""),V(""),te([]),_(F),F.providerType&&o&&(X(!0),o(F.providerType).then(de=>te(de||[])).catch(de=>console.warn("Failed to load saved sessions",de)).finally(()=>X(!1)))},[o]),Q=a.useCallback(()=>{D.current&&(G(!0),D.current().finally(()=>{D.current=null,G(!1),_(null)}))},[]),xe=a.useCallback(()=>{D.current=null,_(null)},[]),M=a.useCallback(F=>{P.current=F,L(F)},[]);return a.useEffect(()=>{var F;fe.current!==t.id&&(fe.current=t.id,v(m||((F=p[0])==null?void 0:F.id)||"__custom__"),w(""),k(""),b([]),h(""),j(!1),E(hr(l,s.length,r.length)))},[r.length,s.length,m,l,t.id,p]),a.useEffect(()=>{var F;f!=="__custom__"&&(f&&p.some(ae=>ae.id===f)||v(m||((F=p[0])==null?void 0:F.id)||"__custom__"))},[m,f,p]),a.useEffect(()=>{S==="ide"&&l||S==="cli"&&s.length>0||S==="acp"&&r.length>0||E(hr(l,s.length,r.length))},[S,r.length,s.length,l]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:l,workspaceRows:p,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:x,browseCurrentPath:u,browseDirectories:g,browseBusy:C,browseError:N,browseDialogOpen:y,activeLauncherKind:S,launchConfirm:O,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:T,launchConfirmArgs:B,launchConfirmModel:K,launchConfirmResumeId:W,launchConfirmSavedSessions:H,launchConfirmSessionsLoading:ke,launchConfirmBusy:Z,resolvedWorkspacePath:re,canCreateMissingWorkspace:he,openBrowseDialog:pe,loadBrowsePath:ie,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Y,setCustomWorkspacePath:w,setBrowseDialogOpen:j,setActiveLauncherKind:E,openLaunchConfirm:se,handleConfirmLaunch:Q,closeLaunchConfirm:xe,setWorkspaceSelectionFromOption:oe,setLaunchConfirmWorkspaceKeyAndSync:M,setLaunchConfirmArgs:J,setLaunchConfirmModel:$,setLaunchConfirmResumeId:V}}function ld({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:i,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:d,isStandalone:l,section:p,showBottomNav:m,onBack:f,onSectionChange:v,onOpenConversation:x,onOpenRecent:w,onOpenMachineDetails:u,onMachineUpgrade:k,onLaunchDetectedIde:g,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:I,onListSavedSessions:N}){const h=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",y=r.slice(0,4),j=s.slice(0,3),S=cd({selectedMachineEntry:t,cliProviders:n,acpProviders:i,machineAction:d,onBrowseDirectory:C,onListSavedSessions:N}),E=a.useMemo(()=>y.map(L=>({key:`recent-launch:${L.id}`,primary:L.label,secondary:`${h(L.kind)}${L.subtitle?` · ${L.subtitle}`:""}`,onClick:()=>{const{options:B,selectedKey:J}=qt({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspacePath:L.workspace});S.openLaunchConfirm({title:`Launch ${L.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:B,selectedWorkspaceKey:J,details:[{label:"Mode",value:h(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const K=B.find($=>$.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption(K),await w({...L,workspace:(K==null?void 0:K.workspacePath)??null})})}})),[S,w,y]),D=a.useMemo(()=>j.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:Ve(L.conversation),secondary:uc(L.conversation,{timestampLabel:L.timestamp?ya(L.timestamp):null}),unread:L.unread,onClick:()=>x(L.conversation)})),[x,j]),O=S.showAllRecent?E:E.slice(0,4),_=E.length>0,P=D.length>0,T=l?"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 ${T} 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:f,type:"button","aria-label":"Back",children:e.jsx(Er,{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:lt(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:[P&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(L=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),_&&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:O.map(L=>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:L.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),E.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:()=>S.setShowAllRecent(L=>!L),children:S.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(S.hasIdeOptions||n.length>0||i.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:S.workspaceChoice,onChange:L=>S.handleWorkspaceChoiceChange(L.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:S.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[S.workspaceRows.map(L=>e.jsxs("option",{value:L.id,children:[L.id===S.defaultWorkspaceId?"⭐ ":"",sr(L.path,L.label)||L.path]},L.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),S.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(ls,{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:S.resolvedWorkspacePath||S.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:S.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:()=>{S.resolvedWorkspacePath&&b(S.resolvedWorkspacePath)},disabled:!S.resolvedWorkspacePath||S.browseBusy,children:"Save as workspace"})]})]}),S.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:S.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[S.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${S.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:()=>S.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${S.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:()=>S.setActiveLauncherKind("cli"),children:"CLI"}),i.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${S.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:()=>S.setActiveLauncherKind("acp"),children:"ACP"})]}),S.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:S.activeLauncherKind==="ide"?"Choose an IDE":S.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:S.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(L=>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:B,selectedKey:J}=qt({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspaceId:S.workspaceChoice!=="__custom__"?S.workspaceChoice:null,currentWorkspacePath:S.resolvedWorkspacePath});S.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:B,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const K=B.find($=>$.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption(K),g(L.type,{workspacePath:(K==null?void 0:K.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:S.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(S.activeLauncherKind==="cli"?n:i).map(L=>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 B=S.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:K}=qt({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspaceId:S.workspaceChoice!=="__custom__"?S.workspaceChoice:null,currentWorkspacePath:S.resolvedWorkspacePath});S.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${B.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:K,details:[{label:"Mode",value:B.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:B==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const $=J.find(W=>W.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption($),I(B,L.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:S.launchConfirmArgs,model:S.launchConfirmModel,resumeSessionId:S.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:S.resolvedWorkspacePath||"Use selected workspace"})]},L.type))})]}),d.message&&e.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${d.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[d.message,S.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:()=>b(S.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:[o&&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:k,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),S.browseDialogOpen&&e.jsx(or,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:S.browseCurrentPath,directories:S.browseDirectories,busy:S.browseBusy,error:S.browseError,confirmLabel:"Use this folder",onClose:()=>S.setBrowseDialogOpen(!1),onNavigate:L=>{S.loadBrowsePath(L)},onConfirm:L=>{S.chooseCustomWorkspacePath(L),S.setBrowseDialogOpen(!1)}}),S.launchConfirm&&e.jsx(Zr,{title:S.launchConfirm.title,description:S.launchConfirm.description,details:S.launchConfirm.details,workspaceOptions:S.launchConfirm.workspaceOptions,selectedWorkspaceKey:S.launchConfirmWorkspaceKey,onWorkspaceChange:S.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:S.launchConfirm.confirmLabel,busy:S.launchConfirmBusy,showArgsInput:S.launchConfirm.showArgsInput,argsValue:S.launchConfirmArgs,onArgsChange:S.setLaunchConfirmArgs,showModelInput:S.launchConfirm.showModelInput,modelValue:S.launchConfirmModel,onModelChange:S.setLaunchConfirmModel,historyProviderNode:S.launchConfirm.providerType&&(S.launchConfirmSessionsLoading||S.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"}),S.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:S.launchConfirmResumeId,onChange:L=>S.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),S.launchConfirmSavedSessions.map(L=>e.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]})]}),onConfirm:S.handleConfirmLaunch,onCancel:S.closeLaunchConfirm}),m&&e.jsx(ti,{section:p,onSectionChange:v})]})}function dd(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.daemonMode&&n.daemonId===t.id).map(n=>{var o,c,d,l,p;const i=Ns(n)?"cli":is(n)?"acp":"ide";return{id:`${i}:${n.type}:${n.workspace||""}`,label:((o=n.activeChat)==null?void 0:o.title)||(Ns(n)?n.cliName||n.type:is(n)&&n.cliName||n.type),kind:i,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:is(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((p=(l=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:l.call(d,-1))==null?void 0:p.timestamp)||0}}).sort((n,i)=>i.timestamp-n.timestamp).map(({timestamp:n,...i})=>i)}function ud(t,s){const r=new Map;for(const n of s){const i=Et(n.conversation),o=r.get(i);o?o.push(n):r.set(i,[n])}return t.map(n=>{const i=r.get(n.id)||[],o=[...i].sort((f,v)=>v.timestamp-f.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,d=Ir(n),l=i.filter(f=>f.unread||f.requiresAction).length,p=n.status==="online"?"Connected":n.status||"Unknown",m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:lt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:l,total:i.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:d,preview:c?mc(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,i)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,c=i.latestTimestamp||i.fallbackActivityAt||0;return c!==o?c-o:n.label.localeCompare(i.label)})}function Ws(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 md({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:i,screen:o,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:l,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:v,onRequestedMobileSectionConsumed:x,setSelectedTabKey:w,setScreen:u,setSelectedMachineId:k,setSection:g,setMachineBackTarget:b,resetMachineAction:C}){const I=a.useRef(null),N=a.useCallback(h=>{if(!(h!=null&&h.sessionId))return;const y=js(h,c),j=Math.max(Date.now(),Ht(h),y.lastUpdated||0);Ws("mark_read:start",{tabKey:h.tabKey,sessionId:h.sessionId,displayPrimary:Ve(h),inboxBucket:y.inboxBucket,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:Ht(h),readAt:j}),d(Et(h)||h.ideId,"mark_session_seen",{sessionId:h.sessionId,seenAt:j}).then(S=>{Ws("mark_read:result",{tabKey:h.tabKey,sessionId:h.sessionId,result:S})}).catch(S=>{Ws("mark_read:error",{tabKey:h.tabKey,sessionId:h.sessionId,error:S instanceof Error?S.message:String(S)})})},[c,d]);return a.useEffect(()=>{var y;if(!n){u("inbox"),w(((y=t[0])==null?void 0:y.tabKey)||null),I.current=null;return}if(o!=="chat"){I.current=null;return}const h=`${n.tabKey}:${n.sessionId||""}`;I.current!==h&&(I.current=h,N(n))},[t,N,o,n,u,w]),a.useEffect(()=>{if(!l)return;const h=t.find(y=>y.tabKey===l);h&&(w(h.tabKey),u("chat"),p==null||p())},[t,p,l,u,w]),a.useEffect(()=>{if(!m)return;const h=s.find(y=>y.id===m);h&&(k(h.id),C(),g("machines"),b("inbox"),u("machine"),f==null||f())},[s,f,m,C,b,u,g,k]),a.useEffect(()=>{v&&(g(v),u("inbox"),x==null||x())},[x,v,u,g]),a.useEffect(()=>{const h=r.filter(y=>y.inboxBucket==="task_complete"||y.unread);h.length!==0&&Ws("inbox_state",{screen:o,selectedTabKey:i,items:h.map(y=>{const j=js(y.conversation,c);return{liveState:j,tabKey:y.conversation.tabKey,sessionId:y.conversation.sessionId,displayPrimary:Ve(y.conversation),serverBucket:j.inboxBucket,computedBucket:y.inboxBucket,serverUnread:j.unread,computedUnread:y.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Ht(y.conversation)}})})},[r,c,o,i]),{markConversationRead:N}}function pd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Un(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function xd(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function fd({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[i,o]=a.useState("idle"),[c,d]=a.useState(""),[l,p]=a.useState(null),m=a.useCallback(()=>{o("idle"),d(""),p(null)},[]),f=a.useCallback(async(b,C,I)=>{var N;try{o("loading"),d(`Launching ${C}…`);const h={ideType:C,enableCdp:!0};(N=I==null?void 0:I.workspacePath)!=null&&N.trim()&&(h.workspace=I.workspacePath.trim()),await t(b,"launch_ide",h),o("done"),d(`${C} launch requested`)}catch(h){o("error"),d(h instanceof Error?h.message:"Launch IDE failed"),console.error("Launch IDE failed",h)}},[t]),v=a.useCallback(async(b,C,I)=>{if(C.trim())try{o("loading"),d(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const N=await t(b,"workspace_add",{path:C.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(N!=null&&N.success){o("done"),d(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),d((N==null?void 0:N.error)||"Could not save workspace")}catch(N){o("error"),d(N instanceof Error?N.message:"Could not save workspace")}},[t]),x=a.useCallback(async b=>{var C,I,N,h,y,j;try{o("loading"),d("Starting daemon upgrade…");const S=await t(b,"daemon_upgrade",{});if((C=S==null?void 0:S.result)!=null&&C.alreadyLatest){o("done"),d(`Already on v${((I=S==null?void 0:S.result)==null?void 0:I.version)||"latest"}.`);return}if((N=S==null?void 0:S.result)!=null&&N.upgraded||(h=S==null?void 0:S.result)!=null&&h.success){o("done"),d(`Upgrade to v${((y=S==null?void 0:S.result)==null?void 0:y.version)||"latest"} started. Daemon is restarting…`);return}o("error"),d(((j=S==null?void 0:S.result)==null?void 0:j.error)||"Upgrade failed")}catch(S){o("error"),d(S instanceof Error?S.message:"Upgrade failed")}},[t]),w=a.useCallback(async(b,C,I,N)=>{var j,S,E;const h=Date.now(),y={machineId:b,kind:C,providerType:I,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:h};try{o("loading"),d(`Launching ${I}…`),p(y);const D={cliType:I};(j=N==null?void 0:N.workspacePath)!=null&&j.trim()?D.dir=N.workspacePath.trim():N!=null&&N.workspaceId&&(D.workspaceId=N.workspaceId),N!=null&&N.resumeSessionId&&(D.resumeSessionId=N.resumeSessionId),(S=N==null?void 0:N.args)!=null&&S.trim()&&(D.cliArgs=N.args.trim().split(/\s+/).filter(Boolean)),(E=N==null?void 0:N.model)!=null&&E.trim()&&(D.initialModel=N.model.trim());const O=await t(b,"launch_cli",D),_=(O==null?void 0:O.result)||O,P=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(O!=null&&O.success&&P){p(null),o("done"),d(`${I} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`);return}if(O!=null&&O.success){o("loading"),d(`${I} launch requested — waiting for session…`);return}p(null),o("error"),d((O==null?void 0:O.error)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(xd(D)){o("loading"),d(`${I} launch requested — waiting for session…`);return}p(null),o("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,t]),u=a.useCallback(async(b,C)=>{try{const I=await t(b,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),N=(I==null?void 0:I.result)??I;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[t]),k=a.useCallback(async(b,C)=>ir(t,b,C),[t]);a.useEffect(()=>{var N;if(!l)return;const b=Un(l.workspacePath),C=r.find(h=>{var O,_,P,T;if(!h||h.type==="adhdev-daemon"||h.daemonMode||pd(h.daemonId||h.id)!==l.machineId||(h.transport==="acp"?"acp":h.transport==="pty"?"cli":null)!==l.kind||String(h.agentType||h.ideType||h.type||"")!==l.providerType)return!1;const E=String(h.providerSessionId||"");if(l.resumeSessionId&&E)return E===l.resumeSessionId;if(b){const L=Un(h.workspace||h.runtimeWorkspaceLabel);return L?L===b:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((T=(P=(_=(O=h.activeChat)==null?void 0:O.messages)==null?void 0:_.at)==null?void 0:P.call(_,-1))==null?void 0:T.timestamp)||0)>=l.startedAt-5e3});if(!C)return;const I=typeof C.sessionId=="string"&&C.sessionId?C.sessionId:typeof C.instanceId=="string"&&C.instanceId?C.instanceId:(N=n.find(h=>h.ideId===C.id))==null?void 0:N.sessionId;I&&(p(null),o("done"),d(`${l.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(I)}`))},[n,r,s,l]),a.useEffect(()=>{if(!l)return;const b=window.setTimeout(()=>{p(C=>!C||C.startedAt!==l.startedAt?C:(o("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[l]);const g=a.useCallback(async(b,C)=>{if(C.kind==="ide"&&C.providerType){await f(b,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await w(b,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,w]);return{machineAction:{state:i,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:v,handleMachineUpgrade:x,handleLaunchWorkspaceProvider:w,handleListSavedSessions:u,handleBrowseDirectory:k,handleOpenRecent:g}}function hd({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:i,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:d,setSection:l,setMachineBackTarget:p}){const m=a.useCallback(g=>{o(g.tabKey),c("chat"),n(g)},[n,c,o]),f=a.useCallback(g=>{const b=t.find(C=>C.ideId===g.ideId&&C.streamSource==="native");b&&(o(b.tabKey),c("chat"),n(b))},[t,n,c,o]),v=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),x=a.useCallback((g,b="inbox")=>{d(g),i(),l("machines"),p(b),c("machine")},[i,p,c,l,d]),w=a.useCallback(g=>{const b=Et(g);b&&x(b,"chat")},[x]),u=a.useCallback(()=>{i(),c(r)},[r,i,c]),k=a.useCallback(g=>{l(g),c("inbox")},[c,l]);return{openConversation:m,openNativeConversation:f,backFromConversation:v,openMachine:x,openConversationMachine:w,backFromMachine:u,changeMachineSection:k}}function bd(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function gd(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 yd({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,userName:l,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,onOpenHistory:u,onOpenRemote:k,onStopCli:g,wsStatus:b,isConnected:C,onShowHiddenConversation:I,onShowAllHiddenConversations:N,onHideConversation:h,onOpenNewSession:y}){const[j,S]=a.useState(()=>{var A;return((A=t[0])==null?void 0:A.tabKey)||null}),[E,D]=a.useState(()=>t[0]?"chat":"inbox"),[O,_]=a.useState("chats"),[P,T]=a.useState(null),[L,B]=a.useState("inbox"),J=us(),K="0.8.33",$=a.useMemo(()=>t.find(A=>A.tabKey===j)||t[0]||null,[t,j]),W=a.useMemo(()=>$?r.find(A=>A.id===$.ideId):void 0,[r,$]),V=a.useMemo(()=>!$||De($)||!Ke($)?null:ds($),[$]),H=a.useMemo(()=>r.filter(A=>A.type==="adhdev-daemon"||A.daemonMode).sort(Or),[r]),te=a.useMemo(()=>H.find(A=>A.id===P)||null,[H,P]),ke=a.useMemo(()=>Ts(r),[r]),X=nr({sendDaemonCommand:i,activeConv:$||void 0,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),Z=fd({sendDaemonCommand:i,navigate:J,ides:r,conversations:t}),G=a.useMemo(()=>t.map(A=>{const q=E==="chat"&&($==null?void 0:$.tabKey)===A.tabKey,F=ks(A,ke,{hideOpenTaskCompleteUnread:!0,isOpenConversation:q}),ae=Ht(A),de=Aa(A);return{conversation:A,timestamp:ae,preview:de,unread:F.unread,requiresAction:F.requiresAction,isWorking:F.isWorking,inboxBucket:F.inboxBucket}}),[t,ke,E,$]),{markConversationRead:fe}=md({conversations:t,machineEntries:H,items:G,selectedConversation:$,selectedTabKey:j,screen:E,liveSessionInboxState:ke,sendDaemonCommand:i,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,setSelectedTabKey:S,setScreen:D,setSelectedMachineId:T,setSection:_,setMachineBackTarget:B,resetMachineAction:Z.resetMachineAction}),re=hd({conversations:t,selectedConversation:$,machineBackTarget:L,markConversationRead:fe,resetMachineAction:Z.resetMachineAction,setSelectedTabKey:S,setScreen:D,setSelectedMachineId:T,setSection:_,setMachineBackTarget:B}),he=a.useMemo(()=>G.filter(A=>A.requiresAction),[G]),ve=a.useMemo(()=>G.filter(A=>A.unread&&!A.requiresAction),[G]),ie=a.useMemo(()=>G.filter(A=>!A.unread&&!A.requiresAction&&A.isWorking),[G]),pe=a.useMemo(()=>G.filter(A=>!A.unread&&!A.requiresAction&&!A.isWorking),[G]),oe=a.useMemo(()=>te?G.filter(A=>Et(A.conversation)===te.id):[],[G,te]),ge=a.useMemo(()=>dd(te,r),[r,te]),Y=(te==null?void 0:te.version)||null,se=!!te&&!!Y&&!0&&Y!==K,Q=a.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),xe=a.useMemo(()=>Q.filter(A=>A.category==="cli"&&A.installed!==!1).map(A=>({type:A.type,displayName:A.displayName||A.type,icon:A.icon})),[Q]),M=a.useMemo(()=>Q.filter(A=>A.category==="acp"&&A.installed!==!1).map(A=>({type:A.type,displayName:A.displayName||A.type,icon:A.icon})),[Q]),ee=a.useMemo(()=>ud(H,G),[G,H]),ye=a.useCallback(async A=>{te&&await Z.handleOpenRecent(te.id,A)},[Z,te]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&$?e.jsx(rd,{selectedConversation:$,isAcp:De($),isStandalone:d,selectedIdeEntry:W,actionLogs:n,userName:l,isSendingChat:X.isSendingChat,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:re.backFromConversation,onOpenNativeConversation:re.openNativeConversation,onOpenMachine:re.openConversationMachine,onHideConversation:h,onOpenHistory:u,onOpenRemote:k,onStopCli:g,cliViewMode:V,onSetCliViewMode:async A=>{if($&&V!==A)try{await i(Et($)||$.ideId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:Jt($),mode:A})}catch(q){gd(q)?console.warn("Skipped CLI view mode switch:",q instanceof Error?q.message:String(q)):console.error("Failed to switch CLI view mode:",q)}},handleSendChat:X.handleSendChat,handleFocusAgent:X.handleFocusAgent}):E==="machine"&&te?e.jsx(ld,{selectedMachineEntry:te,selectedMachineConversations:oe,selectedMachineRecentLaunches:ge,cliProviders:xe,acpProviders:M,selectedMachineNeedsUpgrade:se,appVersion:K,machineAction:Z.machineAction,isStandalone:d,section:O,showBottomNav:L==="inbox",onBack:re.backFromMachine,onSectionChange:re.changeMachineSection,onOpenConversation:re.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>J(`/machines/${te.id}`),onMachineUpgrade:()=>Z.handleMachineUpgrade(te.id),onLaunchDetectedIde:(A,q)=>Z.handleLaunchDetectedIde(te.id,A,q),onAddWorkspace:(A,q)=>Z.handleAddWorkspace(te.id,A,q),onBrowseDirectory:A=>Z.handleBrowseDirectory(te.id,A),onLaunchWorkspaceProvider:(A,q,F)=>Z.handleLaunchWorkspaceProvider(te.id,A,q,F),onListSavedSessions:A=>Z.handleListSavedSessions(te.id,A)}):e.jsx(ad,{section:O,attentionItems:he,unreadItems:ve,workingItems:ie,completedItems:pe,hiddenConversations:s,machineCards:ee,getAvatarText:bd,onOpenConversation:re.openConversation,onShowConversation:I,onShowAllHidden:N,onOpenNewSession:y,onOpenMachine:re.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:_,wsStatus:b,isConnected:C,isStandalone:d})})}function br(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function vd({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:i,onClearPreviewOrder:o}){const c=a.useRef(0),[d,l]=a.useState(!1),[p,m]=a.useState(null),f=a.useCallback(()=>{c.current=0,l(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const v=a.useCallback(k=>{k.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,l(!0))},[]),x=a.useCallback(k=>{if(!k.dataTransfer.types.includes("text/tab-key"))return;if(k.preventDefault(),!br(s,r)){m("merge");return}const g=k.currentTarget.getBoundingClientRect(),b=k.clientX-g.left,C=g.width/3;b<C?m("split-left"):b>C*2?m("split-right"):m("merge")},[s,r]),w=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,l(!1),m(null))},[]),u=a.useCallback(k=>{c.current=0,l(!1);const g=k.dataTransfer.getData("text/tab-key"),b=g?t.some(I=>I.tabKey===g):!1,C=p;if(m(null),o(),!!g){if(k.preventDefault(),C==="split-left"&&br(s,r)){r==null||r(g,"split-left");return}if(C==="split-right"&&br(s,r)){r==null||r(g,"split-right");return}if(b){i(g);return}n==null||n(g)}},[t,p,s,r,n,i,o]);return{dragOver:d,dropAction:p,resetDragState:f,handleDragEnter:v,handleDragOver:x,handleDragLeave:w,handleDrop:u}}function wd(t,s){const r=new Set(s.map(o=>o.tabKey)),n=t.filter(o=>r.has(o)),i=s.filter(o=>!t.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...i]}function jd({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:i}){const[o,c]=a.useState(s??null),[d,l]=a.useState(r??[]),[p,m]=a.useState(null),f=a.useRef(null),v=a.useRef(null),x=a.useRef(n),w=a.useRef(i);a.useEffect(()=>{x.current=n},[n]),a.useEffect(()=>{w.current=i},[i]),a.useEffect(()=>{s&&s!==o&&c(s)},[s,o]),a.useEffect(()=>{l(y=>{const j=wd(y,t);return j.length===y.length&&j.every((S,E)=>S===y[E])?y:j})},[t]);const u=a.useMemo(()=>{const y=p??d;if(y.length===0)return t;const j=new Map(y.map((S,E)=>[S,E]));return[...t].sort((S,E)=>{const D=j.get(S.tabKey)??999,O=j.get(E.tabKey)??999;return D-O})},[t,p,d]);a.useEffect(()=>{var j,S;if(u.length===0){o!==null&&(c(null),(j=x.current)==null||j.call(x,null));return}if(o&&u.some(E=>E.tabKey===o))return;const y=u[0].tabKey;y!==o&&(c(y),(S=x.current)==null||S.call(x,y))},[u,o]);const k=a.useMemo(()=>u.find(y=>y.tabKey===o),[u,o]),g=a.useCallback(y=>{var j;c(y),(j=x.current)==null||j.call(x,y)},[]),b=a.useCallback((y,j,S)=>{l(E=>{var P;const D=E.filter(T=>T!==y),O=D.indexOf(j);if(O<0)return E;const _=S==="left"?O:O+1;return D.splice(_,0,y),(P=w.current)==null||P.call(w,D),D}),m(null)},[]),C=a.useCallback((y,j,S)=>{const D=(d.length>0?d:t.map(P=>P.tabKey)).filter(P=>P!==y),O=D.indexOf(j);if(O<0)return;const _=S==="left"?O:O+1;D.splice(_,0,y),f.current=D,m(D)},[d,t]),I=a.useCallback(()=>{var j;const y=f.current;y&&(l(y),(j=w.current)==null||j.call(w,y))},[]),N=a.useCallback(()=>{f.current=null,m(null)},[]),h=a.useCallback(y=>{l(j=>{var E;const S=j.filter(D=>D!==y);return S.push(y),(E=w.current)==null||E.call(w,S),S})},[]);return{activeTabId:o,activeConv:k,sortedConversations:u,previewOrderRef:f,draggingTabRef:v,selectTab:g,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:I,clearPreviewOrder:N,moveTabToEnd:h,setDraggingTabKey:y=>{v.current=y}}}function kd({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 Qr({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:i,handleLaunchIde:o}){const c=!r&&!n,d=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install the ADHDev daemon and link your dashboard to start.";return t===0&&!s&&i&&o?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:d}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),c&&e.jsx(ei,{}),r&&i.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:i.map(p=>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:()=>o(p.type),children:[e.jsx(xa,{size:14,className:"opacity-70"})," Open ",p.name]},p.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 si="adhdev-tab-shortcuts";function Nd(){try{return JSON.parse(localStorage.getItem(si)||"{}")}catch{return{}}}function ri({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const i=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=a.useState(()=>Nd()),[d,l]=a.useState(null),p=a.useCallback(f=>{const v=[];return f.metaKey&&v.push(i?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(i?"⌥":"Alt"),f.shiftKey&&v.push(i?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(f.key.length===1?f.key.toUpperCase():f.key),v.join("+"))},[i]),m=a.useCallback(f=>{c(f);try{localStorage.setItem(si,JSON.stringify(f))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){l(null);return}const x=p(v);if(!x)return;const w={...o};for(const[u,k]of Object.entries(w))k===x&&delete w[u];w[d]=x,m(w),l(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[t,d,o,m,p]),a.useEffect(()=>{if(!t)return;const f=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[x,w]of Object.entries(o))if(s.includes(x)&&p(v)===w){v.preventDefault(),r(),n(x);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t,o,s,r,n,p]),{isMac:i,tabShortcuts:o,shortcutListening:d,setShortcutListening:l,saveShortcuts:m}}const Sd=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:i,shortcut:o,conversationKeys:c,draggingTabRef:d,onFocus:l,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:v,onCommitPreviewOrder:x,onClearPreviewOrder:w,onDragStateReset:u,onDragTabKeyChange:k,onReceiveTab:g,onOpenContextMenu:b,longPressTimer:C,isGroupActive:I}){const N=ps(s),h=N.isGenerating?"agent-tab-generating":N.isWaiting?"agent-tab-waiting":"",y=N.isReconnecting,j=a.useCallback(B=>{d.current=s.tabKey,k(s.tabKey),B.dataTransfer.setData("text/tab-key",s.tabKey),B.dataTransfer.effectAllowed="move"},[s.tabKey,d,k]),S=a.useCallback(()=>{d.current=null,k(null),x(),w(),u()},[d,k,x,w,u]),E=a.useCallback(B=>{const J=d.current;if(!(!J||J===s.tabKey)&&B.dataTransfer.types.includes("text/tab-key")){B.preventDefault(),B.stopPropagation();const K=B.currentTarget.getBoundingClientRect(),$=B.clientX<K.left+K.width/2?"left":"right";f(J,s.tabKey,$)}},[s.tabKey,d,f]),D=a.useCallback(B=>{B.preventDefault(),B.stopPropagation();const J=B.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const K=B.currentTarget.getBoundingClientRect(),$=B.clientX<K.left+K.width/2?"left":"right";c.includes(J)?v(J,s.tabKey,$):g&&g(J)}w()},[s.tabKey,c,v,g,w]),O=a.useCallback(B=>{B.stopPropagation(),l(),p(s.tabKey),m(s)},[s,m,l,p]),_=a.useCallback(B=>{B.preventDefault(),b(B.clientX,B.clientY,s.tabKey)},[s.tabKey,b]),P=a.useCallback(B=>{const J=B.touches[0];C.current=setTimeout(()=>{b(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,C,b]),T=a.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",h,r&&"is-active",I&&"is-group-active",y&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:L,draggable:!0,onDragStart:j,onDragEnd:S,onDragOver:E,onDrop:D,onClick:O,onContextMenu:_,onTouchStart:P,onTouchEnd:T,onTouchMove:T,style:{cursor:"pointer",opacity:n?.4:void 0},children:[i&&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:"▲"}):y?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:y?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)})]}),o&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(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 Cd({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:x,onReceiveTab:w,onHideTab:u,isGroupActive:k,allowTabShortcuts:g=!0}){const[b,C]=a.useState(null),I=a.useRef(null),N=a.useRef(null),h=a.useMemo(()=>t.map(_=>_.tabKey),[t]);_s("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:y,tabShortcuts:j,shortcutListening:S,setShortcutListening:E,saveShortcuts:D}=ri({enabled:g,sortedTabKeys:t.map(_=>_.tabKey),onFocus:o,onSelectTab:c});a.useEffect(()=>{if(!b)return;const _=P=>{const T=document.querySelector("[data-pane-context-menu]");T&&T.contains(P.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[b]),a.useEffect(()=>{const _=N.current;if(!_)return;const P=T=>{Math.abs(T.deltaY)>Math.abs(T.deltaX)&&(T.preventDefault(),_.scrollLeft+=T.deltaY)};return _.addEventListener("wheel",P,{passive:!1}),()=>_.removeEventListener("wheel",P)},[]);const O=a.useCallback((_,P,T)=>{C({x:_,y:P,tabKey:T})},[]);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(_=>e.jsx(Sd,{conv:_,isActive:s===_.tabKey,isDraggedTab:i.current===_.tabKey,isTaskCompleteUnread:n.has(_.tabKey),shortcut:g?j[_.tabKey]:void 0,conversationKeys:h,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:O,longPressTimer:I,isGroupActive:k},_.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[g&&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:_=>{_.stopPropagation(),E(b.tabKey),C(null)},children:["⌨ ",j[b.tabKey]?`Change shortcut (${j[b.tabKey]})`:"Set shortcut"]}),j[b.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 _={...j};delete _[b.tabKey],D(_),C(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[g&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(b.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),g&&S&&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:()=>E(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.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. ",y?"⌘+1":"Ctrl+1",", ",y?"⌥+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 Id({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,hasRegisteredMachines:l,userName:p,groupIndex:m,onFocus:f,isSplitMode:v,numGroups:x,onMoveTab:w,onReceiveTab:u,style:k,detectedIdes:g,handleLaunchIde:b,onActiveTabChange:C,initialActiveTabId:I,initialTabOrder:N,onTabOrderChange:h,onHideTab:y,isFocused:j,allowTabShortcuts:S=!0}){const{sendCommand:E}=$t(),D=a.useRef(null),{activeTabId:O,activeConv:_,sortedConversations:P,draggingTabRef:T,selectTab:L,handleTabReorder:B,updatePreviewOrder:J,commitPreviewOrder:K,clearPreviewOrder:$,moveTabToEnd:W,setDraggingTabKey:V}=jd({conversations:t,initialActiveTabId:I,initialTabOrder:N,onActiveTabChange:C,onTabOrderChange:h}),H=nr({sendDaemonCommand:i,activeConv:_,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),{dragOver:te,dropAction:ke,resetDragState:X,handleDragEnter:Z,handleDragOver:G,handleDragLeave:fe,handleDrop:re}=vd({conversations:t,numGroups:x,onMoveTab:w,onReceiveTab:u,onOwnTabDrop:W,onClearPreviewOrder:$}),he=_&&!De(_)&&ds(_)==="terminal",ve=a.useMemo(()=>_?s.find(Y=>Y.id===_.ideId):void 0,[s,_]),ie=a.useMemo(()=>_?n.filter(Y=>Y.ideId===_.tabKey):[],[n,_]),pe=a.useMemo(()=>Ts(s),[s]),oe=a.useMemo(()=>new Set(P.filter(Y=>Ro(Y,pe,{isOpenConversation:Y.tabKey===O})).map(Y=>Y.tabKey)),[O,pe,P]);_s("PaneGroup",{groupIndex:m,conversationCount:t.length,activeTabId:O,dragOver:te});const ge=a.useCallback(Y=>{Y.streamSource==="agent-stream"&&Y.agentType&&E(Y.ideId,"focus_session",{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...k,outline:te?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(Cd,{conversations:P,activeTabId:O,groupIndex:m,numGroups:x,unreadTabKeys:oe,draggingTabRef:T,onFocus:f,onSelectTab:L,onConversationActivated:ge,onPreviewReorder:J,onReorderTab:B,onCommitPreviewOrder:K,onClearPreviewOrder:$,onDragStateReset:X,onDragTabKeyChange:V,onMoveTab:w,onReceiveTab:u,onHideTab:y,isGroupActive:j??!1,allowTabShortcuts:S}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Z,onDragOver:G,onDragLeave:fe,onDrop:re,children:[te&&e.jsx(kd,{dropAction:ke,canSplit:!!(x<4&&w)}),_?e.jsx(Jr,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!he,ideEntry:ve,terminalRef:D,handleModalButton:H.handleModalButton,handleRelaunch:H.handleRelaunch,handleSendChat:H.handleSendChat,isSendingChat:H.isSendingChat,handleFocusAgent:H.handleFocusAgent,isFocusingAgent:H.isFocusingAgent,actionLogs:ie,userName:p,isInputActive:!v||!!j}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Qr,{conversationsCount:t.length,isSplitMode:v,isStandalone:d,hasRegisteredMachines:l,detectedIdes:g,handleLaunchIde:b})})]})]})}function _d({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:i,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:v,userName:x,focusedGroup:w,setFocusedGroup:u,moveTabToGroup:k,splitTabRelative:g,closeGroup:b,handleResizeStart:C,detectedIdes:I,handleLaunchIde:N,groupActiveTabIds:h,setGroupActiveTabIds:y,groupTabOrders:j,setGroupTabOrders:S,toggleHiddenTab:E,allowTabShortcuts:D=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:i.map((O,_)=>{const P=s&&n.length===r?`${n[_]}%`:void 0;return e.jsxs(He.Fragment,{children:[s&&_>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:T=>C(_-1,T),onDoubleClick:()=>b(_),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(Id,{style:s?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:O,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:v,userName:x,groupIndex:_,isFocused:s&&w===_,onFocus:()=>u(_),isSplitMode:s,numGroups:r,onMoveTab:(T,L)=>{L==="left"&&_>0?k(T,_-1):L==="right"&&_<r-1?k(T,_+1):L==="split-left"&&r<4?g(T,_,"left"):L==="split-right"&&r<4&&g(T,_,"right")},onReceiveTab:T=>k(T,_),detectedIdes:_===0?I:void 0,handleLaunchIde:_===0?N:void 0,onActiveTabChange:T=>y(L=>(L[_]??null)===(T??null)?L:{...L,[_]:T}),initialActiveTabId:h[_],initialTabOrder:j[_],onTabOrderChange:T=>S(L=>{const B=L[_]||[];return B.length===T.length&&B.every((J,K)=>J===T[K])?L:{...L,[_]:T}}),onHideTab:E,allowTabShortcuts:D})]},_)})})}function ni({doId:t,ideId:s,ideType:r,connState:n,viewMode:i,instanceId:o}){const[c,d]=a.useState(null),[l,p]=a.useState(null),m=a.useMemo(()=>{if(!s)return r;const v=s.split(":");return v.length>=3&&v[1]==="ide"?v.slice(2).join(":"):r},[s,r]);a.useEffect(()=>t?ze.onScreenshot("ide-page",(x,w)=>{if(x!==t)return;const u=new FileReader;u.onload=()=>d(u.result),u.readAsDataURL(w)}):void 0,[t]),a.useEffect(()=>{n!=="connected"&&d(null)},[n]),a.useEffect(()=>{var x;return t?((x=ze.onStatus)==null?void 0:x.call(ze,(w,u)=>{w===t&&u!=null&&u.screenshotUsage&&p(u.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{d(null)},[t,s,m]),a.useEffect(()=>{const v=t?ze.get(t):null;if(!(!v||n!=="connected"))return i!=="chat"&&m?v.startScreenshots(m):v.stopScreenshots(m),()=>{v.stopScreenshots(m)}},[i,n,m,t]);const f=a.useCallback(async(v,x)=>{const w=t?ze.get(t):null;return!w||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):w.sendInput(v,x,o||m)},[t,n,o,m]);return{connScreenshot:c,screenshotUsage:l,handleRemoteAction:f}}const ai=a.createContext(null);function cr(){const t=a.useContext(ai);if(!t)throw new Error("DashboardDockviewContext missing");return t}function qs(t){return Ve(t)||t.tabKey}function Td(t){return`remote:${t}`}function Cs(t){return t.startsWith("remote:")}function Ad(t){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(i=>i+1),n=[t.api.onDidActiveGroupChange(r),t.api.onDidTitleChange(r),t.api.onDidGroupChange(r),t.containerApi.onDidActivePanelChange(r)];return()=>{for(const i of n)i.dispose()}},[t.api,t.containerApi])}function Md(t,s,r){var d;const n=[s];let i;for(const l of n){let p;for(const m of l){const f=t.addPanel({id:m.tabKey,component:"conversation",title:qs(m),params:{kind:"conversation",tabKey:m.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:i?{position:{referencePanel:i,direction:"right"},inactive:!0}:{}});p||(p=f.id)}i=p??i}const o=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!o)return;const c=t.getPanel(o);c&&c.group.model.openPanel(c)}function zn(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Cs(n.id)||r.has(n.id)||t.removePanel(n);for(const n of s){const i=t.getPanel(n.tabKey);if(i){i.update({params:{tabKey:n.tabKey}}),i.title!==qs(n)&&i.api.setTitle(qs(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:qs(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 Vn(t,s,r){var l,p;const n=r?Td(r):null;for(const m of[...t.panels])Cs(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const i=At(s,r);if(!i&&t.totalPanels===0)return;const o=t.getPanel(n),c=fc(i);if(o){o.title!==c&&o.api.setTitle(c);return}const d=(i==null?void 0:i.tabKey)??((l=t.activePanel)==null?void 0:l.id)??((p=t.panels.find(m=>!Cs(m.id)))==null?void 0:p.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",ideId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function Pd({params:t,api:s}){var f;const r=cr(),n=a.useRef(null),[i,o]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=nr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{o(s.isActive);const v=[s.onDidActiveChange(x=>o(x.isActive)),s.onDidActiveGroupChange(x=>{if(!s.isActive&&!x.isActive){o(!1);return}o(s.isActive)})];return()=>{for(const x of v)x.dispose()}},[s]);const l=a.useMemo(()=>c?r.ides.find(v=>v.id===c.ideId):void 0,[r.ides,c]),p=a.useMemo(()=>c?r.actionLogs.filter(v=>v.ideId===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(Qr,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!De(c)&&ds(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Jr,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:l,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:i})})}function Ld({params:t}){var l;const s=cr(),r=a.useMemo(()=>At([...s.conversationsByTabKey.values()],t.ideId),[s.conversationsByTabKey,t.ideId]),n=a.useMemo(()=>s.ides.find(p=>p.id===t.ideId),[s.ides,t.ideId]),i=(r==null?void 0:r.daemonId)||((l=r==null?void 0:r.ideId)==null?void 0:l.split(":")[0])||t.ideId.split(":")[0]||t.ideId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:d}=ni({doId:i,ideId:t.ideId,ideType:(r==null?void 0:r.ideType)||(n==null?void 0:n.type),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote",instanceId:n==null?void 0:n.instanceId});return r?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(ba,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:c,transportType:r.transport,onAction:d})}):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 Rd(){const t=cr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Qr,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function Ed(t){var x,w;Ad(t);const s=cr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=At([...s.conversationsByTabKey.values()],t.params.ideId),k=((x=t.api.group.activePanel)==null?void 0:x.id)===t.api.id,g=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${g?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const i=((w=t.api.group.activePanel)==null?void 0:w.id)===t.api.id,o=t.api.isGroupActive,c=ks(n,s.liveSessionInboxState,{isOpenConversation:i}),d=c.isReconnecting,l=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,v=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${i?" is-active":""}${o?" is-group-active":""}${d?" is-reconnecting":""}`,title:Ve(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey})},children:[f&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):l?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:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(n)}):l?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:os(n)}):e.jsx("span",{children:os(n)})})]}),v&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function $d({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,hasRegisteredMachines:l,initialDataLoaded:p,userName:m,detectedIdes:f,handleLaunchIde:v,toggleHiddenTab:x,registerActionHandlers:w,onActiveTabChange:u,requestedActiveTabKey:k,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C}){const{theme:I}=Oa(),{sendCommand:N}=$t(),h=a.useRef(null),y=a.useRef(null),j=a.useRef(!1),S=a.useRef(!1),E=a.useRef(!1),D=a.useRef(null),[O,_]=a.useState(null),[P,T]=a.useState(!1),[L,B]=a.useState(!1),J=a.useRef(null),K=a.useMemo(()=>Ja(typeof window<"u"?window.innerWidth:1280),[]),$=a.useMemo(()=>new Map(t.map(A=>[A.tabKey,A])),[t]),W=a.useMemo(()=>Ts(r),[r]),V=a.useCallback(()=>{var A;(A=h.current)==null||A.focus()},[]),H=a.useCallback(A=>{const q=h.current;if(!q)return;const F=q.getPanel(A);F&&(F.group.model.openPanel(F),F.api.setActive())},[]),te=a.useCallback(A=>{const q=h.current,F=q==null?void 0:q.activePanel,ae=(q==null?void 0:q.activeGroup)||(F==null?void 0:F.group);if(!q||!F||!ae)return;const de=ae.panels||[];if(de.length<=1)return;const Ce=de.findIndex(Fe=>Fe.id===F.id);if(Ce<0)return;const Ee=(Ce+A+de.length)%de.length,Ae=de[Ee];Ae&&(Ae.group.model.openPanel(Ae),Ae.api.setActive())},[]),ke=a.useCallback(A=>{var it;const q=h.current,F=(q==null?void 0:q.activeGroup)||((it=q==null?void 0:q.activePanel)==null?void 0:it.group);if(!q||!F)return;const ae=q.groups||[],de=ae.find(Re=>Re.id===F.id);if(!de)return;const Ce=de.element.getBoundingClientRect(),Ee=Ce.left+Ce.width/2,Ae=Ce.top+Ce.height/2,Fe=(Re,Ie,Je,Ge)=>Math.max(0,Math.min(Ie,Ge)-Math.max(Re,Je)),xt=Re=>{const Ie=Re.element.getBoundingClientRect(),Je=Ie.left+Ie.width/2,Ge=Ie.top+Ie.height/2;let z=0,we=0,Ne=0,Le=!1;if(A==="left"?(Le=Je<Ee,z=Math.max(0,Ce.left-Ie.right),we=Math.abs(Ge-Ae),Ne=Fe(Ce.top,Ce.bottom,Ie.top,Ie.bottom)):A==="right"?(Le=Je>Ee,z=Math.max(0,Ie.left-Ce.right),we=Math.abs(Ge-Ae),Ne=Fe(Ce.top,Ce.bottom,Ie.top,Ie.bottom)):A==="above"?(Le=Ge<Ae,z=Math.max(0,Ce.top-Ie.bottom),we=Math.abs(Je-Ee),Ne=Fe(Ce.left,Ce.right,Ie.left,Ie.right)):(Le=Ge>Ae,z=Math.max(0,Ie.top-Ce.bottom),we=Math.abs(Je-Ee),Ne=Fe(Ce.left,Ce.right,Ie.left,Ie.right)),!Le)return Number.POSITIVE_INFINITY;const qe=Ne>0?0:120;return z*3+we+qe};let Xe=null,We=Number.POSITIVE_INFINITY;for(const Re of ae){if(Re.id===de.id)continue;const Ie=xt(Re);Number.isFinite(Ie)&&(Ie>=We||(We=Ie,Xe=Re))}return Xe||void 0},[]),X=a.useCallback(A=>{const q=ke(A);if(!q)return;const F=q.activePanel||q.panels[0];F&&(q.model.openPanel(F),F.api.setActive())},[ke]),Z=a.useCallback((A,q)=>{const F=h.current,ae=F==null?void 0:F.activePanel,de=(F==null?void 0:F.activeGroup)||(ae==null?void 0:ae.group);if(!F||!ae||!de)return;let Ce=ke(A);!Ce&&(q!=null&&q.createGroupIfMissing)&&(Ce=F.addGroup({referenceGroup:de,direction:A})),Ce&&(ae.api.moveTo({group:Ce,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive())},[ke]),{isMac:G,tabShortcuts:fe,shortcutListening:re,setShortcutListening:he,saveShortcuts:ve}=ri({sortedTabKeys:t.map(A=>A.tabKey),onFocus:V,onSelectTab:H}),ie=a.useCallback(()=>{var F;const A=h.current;if(!A)return;const q=A.activePanel;if(q){if(Cs(q.id)){const ae=((F=q.params)==null?void 0:F.ideId)||q.id.slice(7),de=At(t,ae);de!=null&&de.tabKey&&he(de.tabKey);return}$.has(q.id)&&he(q.id)}},[$,he,t]);a.useEffect(()=>(w==null||w({setShortcutForActiveTab:ie,activatePreviousTabInGroup:()=>te(-1),activateNextTabInGroup:()=>te(1),splitActiveTabRight:()=>Z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>X("left"),focusRightPane:()=>X("right"),focusUpPane:()=>X("above"),focusDownPane:()=>X("below"),moveActiveTabToLeftPane:()=>Z("left"),moveActiveTabToRightPane:()=>Z("right"),moveActiveTabToUpPane:()=>Z("above"),moveActiveTabToDownPane:()=>Z("below")}),()=>w==null?void 0:w(null)),[te,X,Z,w,ie]),a.useEffect(()=>{if(!O)return;const A=q=>{const F=document.querySelector("[data-dockview-tab-context-menu]");F&&F.contains(q.target)||_(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[O]);const pe=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:$,detectedIdes:f,handleLaunchIde:v,ides:r,isStandalone:d,hasRegisteredMachines:l,liveSessionInboxState:W,sendDaemonCommand:i,setActionLogs:c,setLocalUserMessages:o,toggleHiddenTab:x,userName:m,scrollToBottomRequest:C,tabShortcuts:fe,openTabContextMenu:({x:A,y:q,tabKey:F})=>_({x:A,y:q,tabKey:F})}),[n,s,$,f,v,r,d,l,W,i,c,o,x,m,C,fe]),oe=a.useCallback(A=>{if(!A)return!1;const q=h.current;if(!q)return!1;const F=q.getPanel(A);return F?(F.group.model.openPanel(F),F.api.setActive(),b==null||b(),!0):!1},[b]),ge=a.useCallback(()=>{if(E.current)return!1;const A=oe(D.current);return A&&(E.current=!0),A},[oe]),Y=a.useCallback(()=>{var q;const A=h.current;A&&Hl(K,{activeTabId:((q=A.activePanel)==null?void 0:q.id)??null,layout:A.toJSON()})},[K]),se=a.useCallback(()=>{const A=y.current;if(!A)return;const q=A.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const F of q)F.setAttribute("data-adhdev-force-hidden","true")},[]),Q=a.useCallback(()=>{const A=y.current;if(!A)return;const q=A.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of q)F.removeAttribute("data-adhdev-force-hidden")},[]),xe=a.useCallback(()=>{const A=y.current;if(!A)return;const q=A.querySelectorAll(".dv-drop-target-container");for(const de of q)de.remove();const F=A.querySelectorAll(".dv-drop-target-dropzone");for(const de of F)de.remove();const ae=A.querySelectorAll(".dv-drop-target");for(const de of ae)de.classList.remove("dv-drop-target")},[]),M=a.useCallback(()=>{T(!1),B(!1),Q(),se(),xe(),!(typeof window>"u")&&(J.current!=null&&window.clearTimeout(J.current),window.requestAnimationFrame(()=>{se(),xe()}),J.current=window.setTimeout(()=>{se(),xe(),J.current=null},80))},[Q,se,xe]),ee=a.useCallback(A=>{var F;h.current=A.api;const q=Vl(K);D.current=(q==null?void 0:q.activeTabId)??null,q!=null&&q.layout&&A.api.fromJSON(q.layout,{reuseExistingPanels:!1}),S.current=!!(q!=null&&q.layout)&&!p&&t.length===0,S.current||(zn(A.api,t),Vn(A.api,t,g)),A.api.totalPanels===0&&t.length>0?Md(A.api,t,k):!S.current&&!oe(k)&&ge(),j.current=!0,A.api.onDidActivePanelChange(ae=>{var Ce;if(D.current=(ae==null?void 0:ae.id)??null,E.current=!0,ae&&Cs(ae.id)){const Ee=((Ce=ae.params)==null?void 0:Ce.ideId)||ae.id.slice(7),Ae=At(t,Ee);u((Ae==null?void 0:Ae.tabKey)??null),Y();return}if(u((ae==null?void 0:ae.id)??null),Y(),!ae)return;const de=$.get(ae.id);(de==null?void 0:de.streamSource)==="agent-stream"&&de.agentType&&N(de.ideId,"focus_session",{agentType:de.agentType,...de.sessionId&&{targetSessionId:de.sessionId}}).catch(()=>{})}),A.api.onDidLayoutChange(()=>{Y()}),A.api.onWillDragPanel(()=>{T(!0),B(!1),se()}),A.api.onWillDragGroup(()=>{T(!0),B(!1),se()}),A.api.onWillShowOverlay(()=>{Q(),B(!0)}),A.api.onDidMovePanel(M),A.api.onDidDrop(M),u(((F=A.api.activePanel)==null?void 0:F.id)??null)},[oe,M,Q,$,p,K,se,xe,u,Y,k,g,N,t]);a.useEffect(()=>{const A=h.current;if(!A||!j.current||S.current&&!p||(S.current&&(S.current=!1),zn(A,t),Vn(A,t,g),k&&oe(k)))return;!A.activePanel&&A.panels[0]&&(A.panels[0].group.model.openPanel(A.panels[0]),A.panels[0].api.setActive()),!!(A.activePanel&&A.getPanel(A.activePanel.id))||ge()},[oe,ge,p,k,g,t]),a.useEffect(()=>{j.current&&oe(k)},[oe,k]),a.useEffect(()=>{if(!P||typeof window>"u")return;const A=()=>M();return window.addEventListener("pointerup",A),window.addEventListener("mouseup",A),window.addEventListener("dragend",A),()=>{window.removeEventListener("pointerup",A),window.removeEventListener("mouseup",A),window.removeEventListener("dragend",A)}},[M,P]),a.useEffect(()=>()=>{typeof window>"u"||J.current!=null&&window.clearTimeout(J.current)},[]),a.useEffect(()=>{const A=q=>{const F=q.target;if(!F)return;const ae=F.querySelector("[data-tab-key]")||F.closest("[data-tab-key]");if(ae){const de=ae.getAttribute("data-tab-key");de&&q.dataTransfer&&q.dataTransfer.setData("text/tab-key",de)}};return window.addEventListener("dragstart",A),()=>window.removeEventListener("dragstart",A)},[]);const ye=I==="light"?Oi:Fi;return e.jsxs(ai.Provider,{value:pe,children:[e.jsx("div",{ref:y,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Wi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${P?" is-dragging-dockview":""}${L?" is-showing-dockview-overlay":""}`,components:{conversation:Pd,remote:Ld},defaultTabComponent:Ed,watermarkComponent:Rd,onReady:ee,singleTabMode:"default",tabAnimation:"smooth",theme:ye})}),O&&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-[160px]",style:{left:O.x,top:O.y},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(),he(O.tabKey),_(null)},children:["⌨ ",fe[O.tabKey]?`Change shortcut (${fe[O.tabKey]})`:"Set shortcut"]}),fe[O.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={...fe};delete A[O.tabKey],ve(A),_(null)},children:"✕ Remove shortcut"})]}),re&&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:()=>he(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. ",G?"⌘+1":"Ctrl+1",", ",G?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}const ii="adhdev-recent-launch-args-v1",Dd=8;function Bd(t){return String(t||"").trim().replace(/\s+/g," ")}function oi(t,s){return`${t.trim()}::${s.trim()}`}function ci(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(ii)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Kd(t){if(!(typeof window>"u"))try{window.localStorage.setItem(ii,JSON.stringify(t))}catch{}}function li(t,s){var o;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((o=ci().byKey[oi(r,n)])==null?void 0:o.items)||[]}function di(t,s,r){var m;const n=String(t||"").trim(),i=String(s||"").trim(),o=Bd(r);if(!n||!i||!o)return;const c=ci(),d=oi(n,i),l=((m=c.byKey[d])==null?void 0:m.items)||[],p=[o,...l.filter(f=>f!==o)].slice(0,Dd);c.byKey[d]={items:p},Kd(c)}function gr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Wd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Hn(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function qn(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 i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function Od(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Fd(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 Ud(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 zd(t){var r;const s=new Map;for(const n of t){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const i=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!i)continue;const o=`${n.providerType}::${n.workspace}::${i}`;s.set(o,(s.get(o)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Vd({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:i,onOpenConversation:o,onClose:c}){var O;const[d,l]=a.useState(n||((O=t[0])==null?void 0:O.id)||null),[p,m]=a.useState(null),[f,v]=a.useState(!0),[x,w]=a.useState(""),[u,k]=a.useState(null);a.useEffect(()=>{var _;l(n||((_=t[0])==null?void 0:_.id)||null)},[n,t]);const g=a.useMemo(()=>t.find(_=>_.id===d)||t[0]||null,[d,t]),b=a.useMemo(()=>r.filter(_=>{if(_.daemonMode||_.transport!=="pty")return!1;const P=Wd(_.daemonId||_.id);return!!(g!=null&&g.id)&&P===g.id}),[g==null?void 0:g.id,r]),C=a.useMemo(()=>{const _=new Map;for(const P of b){const T=s.find(L=>L.sessionId===P.sessionId||L.ideId===P.id);P.sessionId&&T&&_.set(P.sessionId,T)}return _},[b,s]),I=a.useCallback(async _=>{if(g!=null&&g.id){_!=null&&_.silent||v(!0);try{const P=await i(g.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),T=gr(P);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load session host diagnostics");m(T.diagnostics||T.result||null),w("")}catch(P){const T=P instanceof Error?P.message:"Could not load session host diagnostics";w(T)}finally{_!=null&&_.silent||v(!1)}}},[g==null?void 0:g.id,i]);a.useEffect(()=>{I();const _=window.setInterval(()=>{I({silent:!0})},1e4);return()=>window.clearInterval(_)},[I]);const N=a.useCallback(async(_,P)=>{if(!(g!=null&&g.id)||_==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
41
- This will terminate the hosted runtime.`))return;const T=`${_}:${P.sessionId}`;k(T);try{const L=await i(g.id,_,{sessionId:P.sessionId}),B=gr(L);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Session host action failed");const J=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${J}: ${P.displayName}`,"success"),await I({silent:!0})}catch(L){const B=L instanceof Error?L.message:"Session host action failed";w(B),at.showToast(B,"warning")}finally{k(L=>L===T?null:L)}},[g==null?void 0:g.id,I,i]),h=a.useCallback(async()=>{if(!(!(g!=null&&g.id)||!window.confirm(`Prune duplicate hosted runtimes?
42
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){k("session_host_prune_duplicate_sessions");try{const P=await i(g.id,"session_host_prune_duplicate_sessions",{}),T=gr(P);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const L=T.result||{},B=Array.isArray(L.prunedSessionIds)?L.prunedSessionIds.length:0,J=typeof L.duplicateGroupCount=="number"?L.duplicateGroupCount:0;at.showToast(`Pruned ${B} duplicate runtime(s) across ${J} group(s)`,"success"),await I({silent:!0})}catch(P){const T=P instanceof Error?P.message:"Duplicate prune failed";w(T),at.showToast(T,"warning")}finally{k(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[g==null?void 0:g.id,I,i]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((_,P)=>(P.lastActivityAt||0)-(_.lastActivityAt||0)),[p==null?void 0:p.sessions]),j=a.useMemo(()=>zd(y),[y]),S=a.useMemo(()=>y.reduce((_,P)=>{var T;return _+(((T=P.attachedClients)==null?void 0:T.length)||0)},0),[y]),E=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[p==null?void 0:p.recentLogs]),D=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-3).reverse(),[p==null?void 0:p.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:_=>_.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(Pt,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(g==null?void 0:g.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:()=>{I()},disabled:f,"aria-label":"Refresh session host",children:e.jsx(ms,{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(Rt,{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(_=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${_.id===(g==null?void 0:g.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>l(_.id),children:_.label},_.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&&!p&&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(Lt,{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})]})]})}),p&&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:p.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:S})]}),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:qn(p.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Hn(p.hostStartedAt)})]})]}),E&&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(Lt,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:E.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(Is,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:u==="session_host_prune_duplicate_sessions",onClick:()=>{h()},children:u==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${j}`}),e.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),y.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:y.map(_=>{var W,V;const P=C.get(_.sessionId),T=b.find(H=>H.sessionId===_.sessionId),L=u===`session_host_resume_session:${_.sessionId}`,B=u===`session_host_restart_session:${_.sessionId}`,J=u===`session_host_stop_session:${_.sessionId}`,K=Fd(_.meta),$=typeof((W=_.meta)==null?void 0:W.runtimeRecoveryError)=="string"?String(_.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:_.displayName||(T==null?void 0:T.runtimeDisplayName)||(T==null?void 0:T.cliName)||_.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Ud(_.lifecycle)}`,children:_.lifecycle}),K&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:K})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:_.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||_.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:_.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((V=_.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Od(_.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($r,{size:11})," ",_.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",qn(_.lastActivityAt),_.osPid?` · pid ${_.osPid}`:""]}),$&&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:$})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[P&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{o(P),c()},children:"Open chat"}),(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!u,onClick:()=>{N("session_host_resume_session",_)},children:L?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!u,onClick:()=>{N("session_host_restart_session",_)},children:B?"Restarting…":"Restart"}),(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:!!u,onClick:()=>{N("session_host_stop_session",_)},children:J?"Stopping…":"Stop"})]})]},_.sessionId)})}),D.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:D.map(_=>{const P=y.find(T=>T.sessionId===_.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:(P==null?void 0:P.displayName)||_.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Hn(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]})]})]})]})})}function yr(t){var n;if(!t)return null;const s=t.availableProviders||[];return s.some(i=>i.category==="cli"&&i.installed!==!1)?"cli":(((n=t.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(i=>i.category==="acp"&&i.installed!==!1)?"acp":null}function Os(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Hd({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:i,onSaveWorkspace:o,onLaunchIde:c,onLaunchProvider:d,onListSavedSessions:l,sendDaemonCommand:p,onOpenConversation:m}){var Je,Ge;const f=a.useMemo(()=>[...t].sort(Or),[t]),[v,x]=a.useState(((Je=f[0])==null?void 0:Je.id)||""),w=a.useMemo(()=>f.find(z=>z.id===v)||f[0],[v,f]),u=a.useMemo(()=>((w==null?void 0:w.workspaces)||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[w]),k=(w==null?void 0:w.defaultWorkspaceId)||null,[g,b]=a.useState(""),[C,I]=a.useState(""),[N,h]=a.useState(yr(f[0])),[y,j]=a.useState(""),[S,E]=a.useState(""),[D,O]=a.useState([]),[_,P]=a.useState(""),[T,L]=a.useState([]),[B,J]=a.useState(!1),[K,$]=a.useState(""),[W,V]=a.useState(!1),[H,te]=a.useState(!1),[ke,X]=a.useState(null),[Z,G]=a.useState(!1),[fe,re]=a.useState(""),[he,ve]=a.useState(!1),[ie,pe]=a.useState(""),[oe,ge]=a.useState([]),[Y,se]=a.useState(!1),[Q,xe]=a.useState(""),[M,ee]=a.useState(!1),ye=a.useRef(null),A=a.useRef(0);a.useEffect(()=>{var z;!v&&((z=f[0])!=null&&z.id)&&x(f[0].id)},[v,f]);const q=a.useMemo(()=>((w==null?void 0:w.availableProviders)||[]).filter(z=>z.category==="cli"&&z.installed!==!1),[w]),F=a.useMemo(()=>((w==null?void 0:w.availableProviders)||[]).filter(z=>z.category==="acp"&&z.installed!==!1),[w]),ae=a.useMemo(()=>((w==null?void 0:w.detectedIdes)||[]).map(z=>({id:z.type,label:z.name||z.type,meta:z.running?"Detected locally":"Available to open"})),[w]),de=a.useMemo(()=>N==="cli"?q.map(z=>({id:z.type,label:z.displayName||z.type,meta:"CLI provider"})):N==="acp"?F.map(z=>({id:z.type,label:z.displayName||z.type,meta:"ACP provider"})):ae,[F,N,q,ae]);a.useEffect(()=>{var we;if(!w)return;if(ye.current!==w.id){ye.current=w.id,b(k||((we=u[0])==null?void 0:we.id)||"__home__"),I(""),h(yr(w)),j(""),E(""),P(""),L([]),$(""),re("");return}b(Ne=>{var Le;return Ne==="__custom__"||Ne==="__home__"||u.some(qe=>qe.id===Ne)?Ne:k||((Le=u[0])==null?void 0:Le.id)||"__home__"}),h(Ne=>Ne==="ide"&&ae.length>0||Ne==="cli"&&q.length>0||Ne==="acp"&&F.length>0?Ne:yr(w))},[F.length,q.length,k,ae.length,w,u]),a.useEffect(()=>{var z;N&&(de.some(we=>we.id===y)||j(((z=de[0])==null?void 0:z.id)||""))},[N,de,y]);const Ce=a.useCallback(async(z,we)=>{const Ne=A.current+1;return A.current=Ne,J(!0),$(""),l(z,we).then(Le=>{A.current===Ne&&L(Le)}).catch(Le=>{A.current===Ne&&(L([]),$(Le instanceof Error?Le.message:"Could not load saved sessions"))}).finally(()=>{A.current===Ne&&J(!1)})},[l]),Ee=a.useCallback((z,we)=>{O(li(z,we))},[]);a.useEffect(()=>{if(P(""),!w||!y||N==="ide"?O([]):Ee(w.id,y),N!=="cli"){L([]),$(""),J(!1);return}if(!w||!y){L([]),$(""),J(!1);return}Ce(w.id,y)},[N,Ee,Ce,w,y]),a.useEffect(()=>{if(!_)return;const z=T.find(we=>we.providerSessionId===_);z!=null&&z.canResume||P("")},[T,_]);const Ae=g==="__custom__"?C.trim():g==="__home__"?"":((Ge=u.find(z=>z.id===g))==null?void 0:Ge.path)||"",Fe=a.useCallback(z=>{const we=String(z.workspace||"").trim();if(!we)return;const Ne=u.find(Le=>Os(Le.path)===Os(we));if(Ne){b(Ne.id),I("");return}b("__custom__"),I(we)},[u]),xt=a.useCallback(z=>{const we=String(z.workspace||"").trim();if(!we)return{workspaceId:null,workspacePath:null};const Ne=u.find(Le=>Os(Le.path)===Os(we));return Ne?{workspaceId:Ne.id,workspacePath:null}:{workspaceId:null,workspacePath:we}},[u]),Xe=a.useMemo(()=>{var we;if(N!=="cli"||!w||!y)return null;const z=((we=q.find(Ne=>Ne.type===y))==null?void 0:we.displayName)||y;return{ideId:w.id,daemonId:w.id,providerSessionId:_||void 0,transport:"pty",mode:"chat",agentName:z,agentType:y,status:"idle",title:z,messages:[],ideType:y,workspaceName:Ae,displayPrimary:z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${w.id}:${y}`,machineName:lt(w,{fallbackId:w.id})}},[N,q,Ae,w,_,y]),We=a.useCallback(()=>{var we,Ne;if(!w)return;b("__custom__"),ve(!0),xe("");const z=ar(w.platform,[C.trim(),Ae,(we=u.find(Le=>Le.id===k))==null?void 0:we.path,(Ne=u[0])==null?void 0:Ne.path]);se(!0),i(w.id,z).then(Le=>{pe(Le.path),I(Le.path),ge(Le.directories)}).catch(Le=>{xe(Le instanceof Error?Le.message:"Could not load folder")}).finally(()=>se(!1))},[C,k,i,Ae,w,u]),it=a.useCallback(z=>{w&&(se(!0),xe(""),i(w.id,z).then(we=>{pe(we.path),I(we.path),ge(we.directories)}).catch(we=>{xe(we instanceof Error?we.message:"Could not load folder")}).finally(()=>se(!1)))},[i,w]),Re=a.useCallback(async()=>{if(!w||!Ae)return;ee(!0),re("");const z=await o(w.id,Ae);if(ee(!1),!z.ok){re(z.error||"Could not save workspace");return}re("Workspace saved. It will appear in the list once the machine state refreshes.")},[o,Ae,w]),Ie=a.useCallback(async()=>{if(!w||!N||!y)return;G(!0),re("");const z=S.trim()?S.trim().split(/\s+/).filter(Boolean):[],we=N==="ide"?await c(w.id,y,{workspacePath:Ae||null}):await d(w.id,N,y,{workspaceId:g!=="__home__"&&g!=="__custom__"?g:null,workspacePath:g==="__custom__"&&Ae||null,resumeSessionId:N==="cli"&&_?_:null,cliArgs:z});if(G(!1),!we.ok){re(we.error||"Could not start session");return}N!=="ide"&&S.trim()&&(di(w.id,y,S),Ee(w.id,y)),n()},[N,S,Ee,n,c,d,Ae,w,_,y,g]);return w?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(Rt,{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:w.id,onChange:z=>x(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:Z,children:f.map(z=>e.jsx("option",{value:z.id,children:lt(z,{fallbackId:z.id})},z.id))})]}),N==="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:Z||!w,onClick:()=>te(!0),children:[e.jsx(Pt,{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:We,disabled:Z,children:"Browse…"})]}),e.jsxs("select",{value:g,onChange:z=>{const we=z.target.value;b(we),we==="__custom__"?We():re("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Z,children:[e.jsx("option",{value:"__home__",children:"Home directory"}),u.map(z=>e.jsxs("option",{value:z.id,children:[z.id===k?"⭐ ":"",sr(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:g==="__home__"?"Launch without a workspace.":Ae||"Select a workspace folder."}),g==="__custom__"&&Ae&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:We,disabled:Z,children:[e.jsx(ls,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:Z||M,children:M?"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:q.length>0},{id:"ide",label:"IDE",enabled:ae.length>0},{id:"acp",label:"ACP",enabled:F.length>0}].map(z=>e.jsx("button",{type:"button",className:`btn btn-sm ${N===z.id?"btn-primary":"btn-secondary"}`,onClick:()=>h(z.id),disabled:!z.enabled||Z,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:N==="ide"?"Choose IDE":N==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[de.map(z=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>j(z.id),disabled:Z,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)),de.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."})]})]}),N!=="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:S,onChange:z=>E(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:Z}),D.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:D.map(z=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>E(z),disabled:Z,title:z,children:z},z))})]}),N==="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:Z||!w||!y||B,onClick:()=>{!w||!y||Ce(w.id,y)},children:B?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:Z||!w||!y,onClick:()=>{!w||!y||(V(!0),Ce(w.id,y))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:_,onChange:z=>{const we=z.target.value;if(P(we),!we)return;const Ne=T.find(Le=>Le.providerSessionId===we);!Ne||!Ne.canResume||Fe(Ne)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Z||B,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),T.map(z=>e.jsxs("option",{value:z.providerSessionId,disabled:!z.canResume,children:[z.title||z.providerSessionId,z.canResume?"":" (workspace missing)"]},z.providerSessionId))]})}),_&&(()=>{const z=T.find(we=>we.providerSessionId===_);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})(),K&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:K}),!B&&!K&&T.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),fe&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${fe.includes("saved")||fe.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:fe})]}),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:Z,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:Ie,disabled:Z||!N||!y||g==="__custom__"&&!Ae,children:[e.jsx(Kr,{size:14}),Z?"Starting…":"Start session"]})]})]})}),he&&e.jsx(or,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ie,directories:oe,busy:Y,error:Q,onClose:()=>ve(!1),onNavigate:it,onConfirm:z=>{I(z),pe(z),b("__custom__"),ve(!1)}}),W&&Xe&&e.jsx(Vr,{activeConv:Xe,ides:[],isCreatingChat:!1,isRefreshingHistory:B,savedSessions:T,isSavedSessionsLoading:B,isResumingSavedSessionId:ke,onClose:()=>V(!1),onNewChat:()=>{P(""),V(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!w||!y||Ce(w.id,y)},onResumeSavedSession:z=>{if(!w||!y||ke||!z.canResume)return;const we=xt(z);P(z.providerSessionId),Fe(z),X(z.providerSessionId),V(!1),G(!0),re(""),d(w.id,"cli",y,{workspaceId:we.workspaceId,workspacePath:we.workspacePath,resumeSessionId:z.providerSessionId}).then(Ne=>{if(!Ne.ok){re(Ne.error||"Could not resume session");return}n()}).finally(()=>{G(!1),X(Ne=>Ne===z.providerSessionId?null:Ne)})}}),H&&w&&e.jsx(Vd,{machineCards:[{id:w.id,label:lt(w,{fallbackId:w.id}),subtitle:[w.platform||"machine",w.status||"Connected"].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:w.id,sendDaemonCommand:p,onOpenConversation:z=>{te(!1),n(),m(z)},onClose:()=>te(!1)})]}):null}const ui="adhdev-dashboard-action-shortcuts",qd=1200,Gd={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Yd(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Ue(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 mi(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Ue("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Ue("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Ue("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Ue("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Ue("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:Ue("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:Ue("splitActiveTabDown",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Ue("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Ue("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Ue("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Ue("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Ue("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Ue("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Ue("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Ue("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Ue("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Ue("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Ue("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Ue("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Ue("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Ue("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Ue("toggleCliView",t)}]}function Xd(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Gn(t){const s=Object.fromEntries(mi(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ui)||"{}"),n={...s,...r};for(const[i,o]of Object.entries(Gd))n[i]===o&&(n[i]=s[i]);return n}catch{return s}}function Jd(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Zd({enabled:t=!0,onTrigger:s}){const r=Yd(),[n,i]=a.useState(()=>Gn(r)),[o,c]=a.useState(null),[d,l]=a.useState([]),p=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const k=[];return u.metaKey&&k.push(r?"⌘":"Meta"),u.ctrlKey&&k.push("Ctrl"),u.altKey&&k.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&k.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(k.push(Jd(u.key)),k.join("+"))},[r]),f=a.useCallback(u=>{i(u);try{localStorage.setItem(ui,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=Gn(r),k=Object.entries(n),g=Object.entries(u);k.length===g.length&&k.every(([b,C])=>u[b]===C)||f(u)},[n,r,f]);const v=a.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),x=a.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},qd))},[]);a.useEffect(()=>{if(!o)return;const u=k=>{if(k.preventDefault(),k.stopPropagation(),k.key==="Escape"){c(null),l([]);return}const g=m(k);if(!g)return;const C=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(g);if(d.length===0&&C){l([g]);return}const N=[...d,g].slice(0,2).join(" "),h={...n};for(const[y,j]of Object.entries(h))j===N&&delete h[y];h[o]=N,f(h),c(null),l([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,f,o,d]),a.useEffect(()=>{if(!t||o)return;const u=k=>{if(k.defaultPrevented)return;const g=m(k);if(!g)return;const b=k.metaKey||k.ctrlKey||k.altKey;if(Xd(k.target)&&!b)return;const C=p.current.parts,I=b?[g]:[...C.slice(-1),g].slice(-2),N=I.join(" "),h=I[I.length-1],y=Object.entries(n).filter(([,O])=>!!O),j=y.find(([,O])=>O===N);if(j){k.preventDefault(),v(),s(j[0]);return}if(y.some(([,O])=>O.startsWith(`${N} `))){k.preventDefault(),p.current.parts=I,x();return}const E=y.find(([,O])=>O===h);if(E){k.preventDefault(),v(),s(E[0]);return}if(y.some(([,O])=>O.startsWith(`${h} `))){k.preventDefault(),p.current.parts=[h],x();return}v()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,x,t,m,s,v,o]),a.useEffect(()=>()=>v(),[v]);const w=a.useMemo(()=>mi(r),[r]);return{isMac:r,actionDefinitions:w,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:l,saveShortcuts:f}}function Qd(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 eu(t){return t instanceof Error?t.message:String(t||"")}function tu(t){const s=eu(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function su({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:i,isConnected:o,onOpenHistory:c,onOpenRemote:d,onStopCli:l,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:v,ides:x,actionLogs:w,sendDaemonCommand:u,setLocalUserMessages:k,setActionLogs:g,isStandalone:b,initialDataLoaded:C,userName:I,requestedMobileTabKey:N,onRequestedMobileTabConsumed:h,requestedMachineId:y,onRequestedMachineConsumed:j,requestedMobileSection:S,onRequestedMobileSectionConsumed:E,containerRef:D,isSplitMode:O,numGroups:_,groupSizes:P,groupedConvs:T,clearedTabs:L,focusedGroup:B,setFocusedGroup:J,moveTabToGroup:K,splitTabRelative:$,closeGroup:W,handleResizeStart:V,detectedIdes:H,handleLaunchIde:te,groupActiveTabIds:ke,setGroupActiveTabIds:X,groupTabOrders:Z,setGroupTabOrders:G,toggleHiddenTab:fe,visibleConversations:re,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:ve,onDesktopActiveTabChange:ie,onHideConversation:pe,onShowHiddenConversation:oe,onShowAllHiddenConversations:ge,scrollToBottomRequest:Y,machineEntries:se,onBrowseMachineDirectory:Q,onSaveMachineWorkspace:xe,onLaunchMachineIde:M,onLaunchMachineProvider:ee,onListMachineSavedSessions:ye}){const A=He.useRef(null),[q,F]=He.useState(!1),[ae,de]=He.useState(!1),[Ce,Ee]=He.useState(!1),[Ae,Fe]=He.useState(!1),[xt,Xe]=He.useState(!1),[We,it]=He.useState("quickstart"),[Re,Ie]=He.useState("workspace"),Je=!t&&!s,Ge=He.useCallback(ne=>{F(ne),ne&&de(!1)},[]),z=He.useCallback(ne=>{de(ne),ne&&F(!1)},[]),we=He.useCallback(()=>{it(re.length===0?"quickstart":"shortcuts"),Ie("workspace"),Ee(!0),F(!1),de(!1)},[re.length]),Ne=He.useCallback(async ne=>{var St;if(!r)return;const $e=(St=r.modalButtons)==null?void 0:St[ne];if(!$e)return;const yt=Ss(r);if(!yt)return;const Nt=$e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),vt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Nt);try{await u(yt,"resolve_action",{button:$e,action:vt?"approve":"reject",buttonIndex:ne,...cs(r)})}catch(R){tu(R)||console.error("[Shortcut approval] Failed:",R)}},[r,u]),{isMac:Le,actionDefinitions:qe,actionShortcuts:Dt,shortcutListening:dt,shortcutListeningDraft:ft,setShortcutListening:Bt,setShortcutListeningDraft:jt,saveShortcuts:gt}=Zd({enabled:Je&&!Ce,onTrigger:ne=>{var $e,yt,Nt,vt,St,R,U,ce,be,_e,Se,Be,tt;if(ne==="openShortcutHelp"){we();return}if(ne==="hideCurrentTab"){r&&pe(r);return}if(ne==="toggleHiddenTabs"){z(!ae);return}if(ne==="openHistoryForActiveTab"){r&&!De(r)&&c(r);return}if(ne==="openRemoteForActiveTab"){r&&!Ke(r)&&!De(r)&&d(r);return}if(ne==="splitActiveTabRight"){($e=A.current)==null||$e.splitActiveTabRight();return}if(ne==="splitActiveTabDown"){(yt=A.current)==null||yt.splitActiveTabDown();return}if(ne==="focusLeftPane"){(Nt=A.current)==null||Nt.focusLeftPane();return}if(ne==="focusRightPane"){(vt=A.current)==null||vt.focusRightPane();return}if(ne==="focusUpPane"){(St=A.current)==null||St.focusUpPane();return}if(ne==="focusDownPane"){(R=A.current)==null||R.focusDownPane();return}if(ne==="moveActiveTabToLeftPane"){(U=A.current)==null||U.moveActiveTabToLeftPane();return}if(ne==="moveActiveTabToRightPane"){(ce=A.current)==null||ce.moveActiveTabToRightPane();return}if(ne==="moveActiveTabToUpPane"){(be=A.current)==null||be.moveActiveTabToUpPane();return}if(ne==="moveActiveTabToDownPane"){(_e=A.current)==null||_e.moveActiveTabToDownPane();return}if(ne==="triggerPrimaryApprovalAction"){Ne(0);return}if(ne==="triggerSecondaryApprovalAction"){Ne(1);return}if(ne==="triggerTertiaryApprovalAction"){Ne(2);return}if(ne==="setActiveTabShortcut"){(Se=A.current)==null||Se.setShortcutForActiveTab();return}if(ne==="selectPreviousGroupTab"){(Be=A.current)==null||Be.activatePreviousTabInGroup();return}if(ne==="selectNextGroupTab"){(tt=A.current)==null||tt.activateNextTabInGroup();return}!r||!Ke(r)||De(r)||ne==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),kt=He.useCallback(()=>{Ee(!1),Bt(null),jt([])},[Bt,jt]),Me=He.useMemo(()=>Re==="all"?qe:qe.filter(ne=>Qd(ne)===Re),[qe,Re]),Kt=He.useCallback(()=>{const ne=Object.fromEntries(qe.map($e=>[$e.id,""]));gt(ne)},[qe,gt]),ts=He.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ne=Object.fromEntries(qe.map($e=>[$e.id,$e.defaultShortcut]));gt(ne)},[qe,gt]);return He.useEffect(()=>{const ne=$e=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?$e.metaKey&&$e.key.toLowerCase()==="w":$e.ctrlKey&&$e.key.toLowerCase()==="w")&&($e.preventDefault(),r&&pe&&pe(r))};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[r,pe]),He.useEffect(()=>{if(!Ce||dt)return;const ne=$e=>{$e.key==="Escape"&&($e.preventDefault(),kt())};return window.addEventListener("keydown",ne,!0),()=>window.removeEventListener("keydown",ne,!0)},[kt,Ce,dt]),He.useEffect(()=>{if(!Je||re.length>0){Xe(!1);return}Xe(!0);const ne=window.setTimeout(()=>{Xe(!1)},1e4);return()=>window.clearTimeout(ne)},[Je,re.length]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(yc,{activeConv:r,agentCount:n.length,wsStatus:i,isConnected:o,conversations:re,hiddenConversations:v,onOpenHistory:c,onOpenConversation:oe,onHideConversation:pe,onShowConversation:oe,onShowAllHidden:ge,inboxOpen:q,onInboxOpenChange:Ge,hiddenOpen:ae,onHiddenOpenChange:z,onOpenNewSession:s?void 0:()=>Fe(!0),onOpenRemote:()=>{!r||Ke(r)||De(r)||d(r)},onStopCli:l,activeCliViewMode:p,onSetCliViewMode:m}),t?e.jsx(yd,{conversations:f,hiddenConversations:v,ides:x,actionLogs:w,sendDaemonCommand:u,setLocalUserMessages:k,setActionLogs:g,isStandalone:b,userName:I,requestedActiveTabKey:N,onRequestedActiveTabConsumed:h,requestedMachineId:y,onRequestedMachineConsumed:j,requestedMobileSection:S,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:d,onStopCli:l,wsStatus:i,isConnected:o,onShowHiddenConversation:oe,onShowAllHiddenConversations:ge,onOpenNewSession:()=>Fe(!0)}):s?e.jsx(_d,{containerRef:D,isSplitMode:O,numGroups:_,groupSizes:P,groupedConvs:T,clearedTabs:L,ides:x,actionLogs:w,sendDaemonCommand:u,setLocalUserMessages:k,setActionLogs:g,isStandalone:b,hasRegisteredMachines:se.length>0,userName:I,focusedGroup:B,setFocusedGroup:J,moveTabToGroup:K,splitTabRelative:$,closeGroup:W,handleResizeStart:V,detectedIdes:H,handleLaunchIde:te,groupActiveTabIds:ke,setGroupActiveTabIds:X,groupTabOrders:Z,setGroupTabOrders:G,toggleHiddenTab:fe,allowTabShortcuts:!1}):e.jsx($d,{visibleConversations:re,clearedTabs:L,ides:x,actionLogs:w,sendDaemonCommand:u,setLocalUserMessages:k,setActionLogs:g,isStandalone:b,hasRegisteredMachines:se.length>0,initialDataLoaded:C,userName:I,detectedIdes:H,handleLaunchIde:te,toggleHiddenTab:fe,registerActionHandlers:ne=>{A.current=ne},onActiveTabChange:ie,requestedActiveTabKey:he,onRequestedActiveTabConsumed:ve,scrollToBottomRequest:Y}),Ae&&e.jsx(Hd,{machines:se,conversations:f,ides:x,onClose:()=>Fe(!1),onBrowseDirectory:Q,onSaveWorkspace:xe,onLaunchIde:M,onLaunchProvider:ee,onListSavedSessions:ye,sendDaemonCommand:u,onOpenConversation:ne=>{Fe(!1),oe(ne),ie(ne.tabKey)}}),Ce&&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:kt,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:ne=>ne.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:kt,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(ne=>e.jsx("button",{type:"button",className:`btn btn-sm ${We===ne.id?"btn-primary":"btn-secondary"}`,onClick:()=>it(ne.id),children:ne.label},ne.id))}),We==="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 ",Le?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),We==="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."]})]})]})]}),We==="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(ne=>e.jsx("button",{type:"button",className:`btn btn-sm ${Re===ne.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ie(ne.id),children:ne.label},ne.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Kt,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:ts,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:Me.map(ne=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${dt===ne.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:ne.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ne.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:ne.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:dt===ne.id?ft.length>0?`${ft.join(" ")} ...`:"Listening...":Dt[ne.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Bt(ne.id),jt([])},children:dt===ne.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const $e={...Dt};$e[ne.id]="",gt($e)},children:"Disable"})]})]})},ne.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Le?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&xt&&e.jsxs("button",{type:"button",onClick:we,className:"fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center gap-2 rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur px-2.5 py-2 text-xs text-text-secondary hover:text-text-primary transition-colors",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:"?"}),e.jsx("span",{children:"Guide"})]})]})}const vr=[{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 ru({onClose:t}){const[s,r]=a.useState(0),n=vr[s],i=s===vr.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:o=>{o.target===o.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,style:{position:"absolute",top:12,right:16,background:"transparent",border:"none",color:"var(--text-muted)",fontSize:"1.2rem",cursor:"pointer"},children:"✕"}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:vr.map((o,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]}),i&&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",{style:{display:"flex",justifyContent:"space-between",marginTop:"1.5rem"},children:[e.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:"var(--text-muted)",fontSize:"0.85rem",cursor:"pointer"},children:"Skip"}),e.jsx("button",{onClick:()=>i?t():r(o=>o+1),className:"transition-opacity hover:opacity-90",style:{background:"linear-gradient(135deg, #7c3aed, #6366f1)",color:"#fff",border:"none",borderRadius:"0.5rem",padding:"0.55rem 1.5rem",fontSize:"0.9rem",fontWeight:600,cursor:"pointer"},children:i?"Get Started →":"Next →"})]})]}),e.jsx("style",{children:`
43
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
44
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
45
- `})]})}function nu({hasExtensions:t,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:i}){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:()=>i("native"),children:s}),n.map(o=>{const c=r===o.tabKey,d=o.status==="waiting_approval",l=o.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:()=>i(o.tabKey),children:[e.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:d?"var(--status-warning)":l?"var(--accent-primary)":"var(--text-muted)",boxShadow:l?"0 0 6px var(--accent-primary)":"none"}}),o.title,d&&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:"!"})]},o.tabKey)})]}):null}function au({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:i,preferredTabKey:o}){const[c,d]=a.useState(()=>o||"native"),l=a.useMemo(()=>Ra(s),[s]),p=a.useMemo(()=>t?Hr(t,n,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,l,r]),m=a.useMemo(()=>p.find(k=>k.streamSource==="native"),[p]),f=a.useMemo(()=>p.filter(k=>k.streamSource==="agent-stream"),[p]),v=a.useMemo(()=>t?At(p,t.id):null,[p,t]);a.useEffect(()=>{o&&d(o)},[o]),a.useEffect(()=>{if(o||!v)return;const k=v.streamSource==="native"?"native":v.tabKey;!k||c===k||c==="native"&&d(k)},[c,v,o]),a.useEffect(()=>{var k;c!=="native"&&(f.some(g=>g.tabKey===c)||d(((k=f[0])==null?void 0:k.tabKey)||"native"))},[c,f]),a.useEffect(()=>{c==="native"&&(m||f[0]&&d(f[0].tabKey))},[c,m,f]);const x=a.useMemo(()=>c==="native"&&m?m:f.find(k=>k.tabKey===c)||v||m||f[0],[c,m,v,f]),w=a.useMemo(()=>f.map(k=>({tabKey:k.tabKey,title:Pa(k)||i,status:k.status})),[f,i]),u=a.useCallback(k=>{if(k)return p.find(g=>g.sessionId===k||g.ideId===k||g.tabKey===k||g.ideType===k||g.agentType===k)},[p]);return{activeChatTab:c,setActiveChatTab:d,activeConv:x,conversations:p,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:u}}function iu({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:i,localUserMessages:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:p,userName:m,onOpenHistory:f,onConversationChange:v,onClose:x}){const[w,u]=a.useState("split"),[k,g]=a.useState(()=>wt(t)?"native":t.tabKey),b=a.useMemo(()=>s||r.find(L=>L.id===t.ideId),[t.ideId,s,r]),C=a.useMemo(()=>Oe((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:I,extensionTabs:N,hasExtensions:h}=au({ideData:b,allIdes:r,connectionStates:n,localUserMessages:o,ideName:C||"IDE",preferredTabKey:wt(t)?void 0:t.tabKey}),y=a.useMemo(()=>b?At(I,b.id):null,[b,I]);a.useEffect(()=>{if(wt(t)){g((y==null?void 0:y.streamSource)==="agent-stream"?y.tabKey:"native");return}g(t.tabKey)},[t.streamSource,t.tabKey,y]);const j=a.useMemo(()=>k==="native"?I.find(L=>L.streamSource==="native")||t:I.find(L=>L.tabKey===k)||t,[t,I,k]),S=Fr(j),E=nr({sendDaemonCommand:c,activeConv:j,setLocalUserMessages:d,setActionLogs:l,isStandalone:p}),{connScreenshot:D,screenshotUsage:O,handleRemoteAction:_}=ni({doId:S,ideId:j.ideId,ideType:j.ideType,connState:j.connectionState||"new",viewMode:w,instanceId:b==null?void 0:b.instanceId}),P=a.useMemo(()=>i.filter(L=>L.ideId===j.tabKey),[i,j.tabKey]);a.useEffect(()=>{v==null||v(j)},[j,v]),a.useEffect(()=>{const L=B=>{B.key==="Escape"&&x()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[x]);const T=a.useCallback(L=>{L.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:x,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:T,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(ct,{size:16})}),e.jsx("span",{className:"truncate",children:rr(j)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:x,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(L=>{const B=w===L;return e.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${B?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>u(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?e.jsx(lo,{size:15}):e.jsx(ct,{size:15})},L)})}),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:()=>f(j),title:"Chat History",children:[e.jsx(Dr,{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:x,children:"Close"})]})]}),e.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${w==="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:[w!=="remote"&&e.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${w==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[e.jsx(nu,{hasExtensions:h,ideName:C||"IDE",activeChatTab:k,extensionTabs:N,onSelectTab:g}),e.jsx(va,{activeConv:j,onModalButton:E.handleModalButton}),e.jsx(_r,{activeConv:j,ideEntry:b,showMetaChips:!1,handleSendChat:E.handleSendChat,isSendingChat:E.isSendingChat,handleFocusAgent:E.handleFocusAgent,isFocusingAgent:E.isFocusingAgent,actionLogs:P,userName:m})]}),e.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${w==="split"?"order-1 md:order-2":""}`,children:e.jsx(ba,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:D,screenshotUsage:O,transportType:j.transport,onAction:_})})]})]})})}function ou({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:i}){const o=xc(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 ",o,"?"]}),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:i,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 cu({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:i,savedHistorySessions:o,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:l,onNewHistoryChat:p,onSwitchHistorySession:m,onRefreshHistory:f,onResumeSavedHistorySession:v,remoteDialogConv:x,remoteDialogIdeEntry:w,connectionStates:u,actionLogs:k,localUserMessages:g,sendDaemonCommand:b,setLocalUserMessages:C,setActionLogs:I,isStandalone:N,userName:h,onOpenRemoteHistory:y,onRemoteConversationChange:j,onCloseRemoteDialog:S,cliStopDialogOpen:E,cliStopTargetConv:D,onCancelCliStop:O,onStopCliNow:_,onSaveCliAndStop:P,toasts:T,onDismissToast:L,onClickToast:B,showOnboarding:J,onCloseOnboarding:K}){var $;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(Vr,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:i,savedSessions:o,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:l,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:v}),x&&e.jsx(iu,{activeConv:x,ideEntry:w,ides:r,connectionStates:u,actionLogs:k,localUserMessages:g,sendDaemonCommand:b,setLocalUserMessages:C,setActionLogs:I,isStandalone:N,userName:h,onOpenHistory:y,onConversationChange:j,onClose:S}),E&&D&&(Ke(D)||De(D))&&e.jsx(ou,{activeConv:D,canSaveAndStop:Ke(D)&&!De(D)&&!!(($=D.resume)!=null&&$.supported),onCancel:O,onStopNow:_,onSaveAndStop:P}),e.jsx(La,{toasts:T,onDismiss:L,onClickToast:B}),J&&e.jsx(ru,{onClose:K})]})}function lu({daemons:t,targetVersion:s,upgradingDaemons:r,onUpgrade:n,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:"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[e.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:"var(--status-warning)"},children:e.jsx(ms,{size:14})}),e.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[e.jsxs("span",{children:["Update available",s?e.jsxs(e.Fragment,{children:[": ",e.jsxs("strong",{children:["v",s]})]}):null]}),t.map(o=>{const c=lt(o,{fallbackId:o.id}),d=r[o.id],l=o.version||o.daemonVersion||"unknown";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 15%, transparent)"},children:[e.jsx("span",{className:"font-medium text-text-primary",children:c}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",l]}),d==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:"var(--status-warning)"},children:"upgrading…"}):d==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>n(o.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},onClick:()=>n(o.id),children:"Upgrade"})]},o.id)})]}),e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors text-sm px-1 shrink-0",onClick:i,title:"Dismiss",children:"✕"})]})}function du(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Yn(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function uu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function mu(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 pu(){var rn,nn,an;const{sendCommand:t}=$t(),s=Rr(),r=us(),[n,i]=Ui(),o=n.get("activeTab"),c=((rn=s.state)==null?void 0:rn.openRemoteForTabKey)||null,d=((nn=s.state)==null?void 0:nn.openMachineId)||null,l=((an=s.state)==null?void 0:an.mobileSection)||null,p=_a(),m=p.ides||[],f=p.initialLoaded??!0,{updateIdeChats:v,setToasts:x}=p,[w,u]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),k=p.toasts||[],g=p.wsStatus||"connected",b=p.isConnected??!0,C=p.connectionStates||{},I=p.showReconnected||!1,{groupAssignments:N,setGroupAssignments:h,focusedGroup:y,setFocusedGroup:j,groupActiveTabIds:S,setGroupActiveTabIds:E,groupTabOrders:D,setGroupTabOrders:O,groupSizes:_,setGroupSizes:P,isMobile:T,hasHydratedStoredLayout:L,hydrateStoredLayout:B}=Gl(),[J,K]=a.useState(!1),[$,W]=a.useState(!1),[V,H]=a.useState(null),[te,ke]=a.useState([]),[X,Z]=a.useState(!1),[G,fe]=a.useState(null),[re]=a.useState(()=>Ha()),[he,ve]=a.useState([]),[ie,pe]=a.useState({}),[oe,ge]=a.useState({}),[Y,se]=a.useState(null),[Q,xe]=a.useState(null),[M,ee]=a.useState(null),ye=a.useRef(null);_s("Dashboard",{ideCount:m.length,toastCount:k.length,focusedGroup:y,groupCount:Object.keys(N).length,localMessageTabs:Object.keys(ie).length,actionLogCount:he.length});const A=m.find(le=>le.type==="adhdev-daemon"),q=(A==null?void 0:A.detectedIdes)||[],F=a.useMemo(()=>m.filter(le=>le.type==="adhdev-daemon"||le.daemonMode).sort(Or),[m]),ae=!!A,de=(A==null?void 0:A.terminalBackend)||null,Ce=A?lt(A,{fallbackId:A.id}):null,Ee=(A==null?void 0:A.id)||null,{hiddenTabs:Ae,hideTab:Fe,toggleTab:xt,showTab:Xe,showAllTabs:We}=Il(),{chatIdes:it,conversations:Re,visibleConversations:Ie,visibleTabKeys:Je,resolveConversationBySessionId:Ge,resolveConversationByTarget:z}=Bl({ides:m,connectionStates:C,localUserMessages:ie,clearedTabs:oe,hiddenTabs:Ae}),we=a.useMemo(()=>Ts(m),[m]),Ne=a.useRef(null),{containerRef:Le,normalizedGroupAssignments:qe,numGroups:Dt,isSplitMode:dt,groupedConvs:ft,moveTabToGroup:Bt,closeGroup:jt,handleResizeStart:gt,splitTabRelative:kt}=td({groupAssignments:N,setGroupAssignments:h,setFocusedGroup:j,setGroupActiveTabIds:E,setGroupTabOrders:O,groupSizes:_,setGroupSizes:P,isMobile:T,visibleConversations:Ie,visibleTabKeys:Je}),Me=a.useMemo(()=>{var je,me;if(!T){if(Y){const ue=Re.find(Te=>Te.tabKey===Y);if(ue)return ue}return Ie[0]}const le=S[y];if(le){const ue=Re.find(Te=>Te.tabKey===le);if(ue)return ue}return((je=ft[y])==null?void 0:je[0])||((me=ft[0])==null?void 0:me[0])},[Y,T,S,y,Re,ft,Ie]);a.useEffect(()=>{if(T){Ne.current=null;return}if(!(Me!=null&&Me.sessionId)){Ne.current=null;return}const le=`${Me.tabKey}:${Me.sessionId}`;if(Ne.current===le)return;const je=()=>{if(document.visibilityState!=="visible"||Ne.current===le)return;Ne.current=le;const me=js(Me,we),ue=Math.max(Date.now(),Ht(Me),me.lastUpdated||0);t(Me.daemonId||Me.ideId,"mark_session_seen",{sessionId:Me.sessionId,seenAt:ue}).catch(()=>{})};if(document.visibilityState==="visible"){const me=setTimeout(je,1500),ue=()=>{document.visibilityState!=="visible"&&clearTimeout(me)};return document.addEventListener("visibilitychange",ue),()=>{clearTimeout(me),document.removeEventListener("visibilitychange",ue)}}else{const me=()=>{document.visibilityState==="visible"&&(setTimeout(je,800),document.removeEventListener("visibilitychange",me))};return document.addEventListener("visibilitychange",me),()=>{document.removeEventListener("visibilitychange",me)}}},[Me,T,we,t]);const{requestedDesktopTabKey:Kt,requestedMobileTabKey:ts,consumeRequestedActiveTab:ne}=Kl({isMobile:T,urlActiveTab:o,resolveConversationBySessionId:Ge,setSearchParams:i}),{remoteDialogConv:$e,remoteDialogIdeEntry:yt,remoteDialogActiveConv:Nt,setRemoteDialogActiveConv:vt,openRemoteDialog:St,closeRemoteDialog:R}=Xl({isMobile:T,location:s,navigate:r,requestedRemoteTabTarget:c,requestedDesktopTabKey:Kt,conversations:Re,ides:m,resolveConversationByTarget:z}),U=Nt||$e||Me,ce=!!U&&Ke(U)&&!De(U),be=a.useMemo(()=>{if(!U||!ce)return null;const le=U.daemonId||U.ideId||"",je=U.agentType||U.ideType||"";return`${le}:${je}`},[U,ce]),_e=a.useMemo(()=>Ie,[Ie]),Se=T&&re==="chat",Be=a.useMemo(()=>Re.filter(le=>Ae.has(le.tabKey)),[Re,Ae]),tt=a.useCallback(le=>{const je=new URLSearchParams(n);je.set("activeTab",le),i(je,{replace:!0})},[n,i]),ut=a.useCallback(async(le,je)=>ir(t,le,je),[t]),Ze=a.useCallback(async(le,je)=>{if(!je.trim())return{ok:!1,error:"Choose a workspace path first."};try{const me=await t(le,"workspace_add",{path:je.trim()});return me!=null&&me.success?{ok:!0}:{ok:!1,error:(me==null?void 0:me.error)||"Could not save workspace"}}catch(me){return{ok:!1,error:me instanceof Error?me.message:"Could not save workspace"}}},[t]),xs=a.useCallback(async(le,je,me)=>{var ue;try{const Te={ideType:je,enableCdp:!0};(ue=me==null?void 0:me.workspacePath)!=null&&ue.trim()&&(Te.workspace=me.workspacePath.trim());const Qe=await t(le,"launch_ide",Te);return!(Qe!=null&&Qe.success)&&(Qe==null?void 0:Qe.success)!==void 0?{ok:!1,error:(Qe==null?void 0:Qe.error)||"Could not launch IDE"}:(ee({machineId:le,kind:"ide",providerType:je,workspacePath:(me==null?void 0:me.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Te){return{ok:!1,error:Te instanceof Error?Te.message:"Could not launch IDE"}}},[t]),pi=a.useCallback(async(le,je,me,ue)=>{var Qe,fs,ss;const Te=Date.now();try{const ht={cliType:me};(Qe=ue==null?void 0:ue.workspacePath)!=null&&Qe.trim()?ht.dir=ue.workspacePath.trim():ue!=null&&ue.workspaceId&&(ht.workspaceId=ue.workspaceId),(fs=ue==null?void 0:ue.resumeSessionId)!=null&&fs.trim()&&(ht.resumeSessionId=ue.resumeSessionId.trim()),Array.isArray(ue==null?void 0:ue.cliArgs)&&ue.cliArgs.length>0&&(ht.cliArgs=ue.cliArgs),(ss=ue==null?void 0:ue.initialModel)!=null&&ss.trim()&&(ht.initialModel=ue.initialModel.trim());const st=await t(le,"launch_cli",ht),ot=(st==null?void 0:st.result)||st,hs=(ot==null?void 0:ot.sessionId)||(ot==null?void 0:ot.id);return st!=null&&st.success&&hs?(tt(hs),{ok:!0}):st!=null&&st.success?(ee({machineId:le,kind:je,providerType:me,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Te}),{ok:!0}):{ok:!1,error:(st==null?void 0:st.error)||(ot==null?void 0:ot.error)||`Could not launch ${je.toUpperCase()} session`}}catch(ht){return uu(ht)?(ee({machineId:le,kind:je,providerType:me,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Te}),{ok:!0}):{ok:!1,error:ht instanceof Error?ht.message:`Could not launch ${je.toUpperCase()} session`}}},[tt,t]),xi=a.useCallback(async(le,je)=>{if(!le||!je)return[];try{const me=await t(le,"list_saved_sessions",{providerType:je,kind:"cli",limit:30}),ue=(me==null?void 0:me.result)??me;return Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[]}catch(me){return console.error("List saved sessions failed",me),[]}},[t]);a.useEffect(()=>{var ue;if(!M)return;const le=Yn(M.workspacePath),je=m.find(Te=>{var st,ot,hs,on;if(!Te||Te.type==="adhdev-daemon"||Te.daemonMode||du(Te.daemonId||Te.id)!==M.machineId||(Ns(Te)?"cli":is(Te)?"acp":"ide")!==M.kind||String(Te.agentType||Te.ideType||Te.type||"")!==M.providerType)return!1;if(M.resumeSessionId)return String(Te.providerSessionId||"")===M.resumeSessionId;if(le){const dr=Yn(Te.workspace||Te.runtimeWorkspaceLabel);return dr?dr===le:!1}return Number(Te.lastUpdated||Te._lastUpdate||Te.timestamp||((on=(hs=(ot=(st=Te.activeChat)==null?void 0:st.messages)==null?void 0:ot.at)==null?void 0:hs.call(ot,-1))==null?void 0:on.timestamp)||0)>=M.startedAt-5e3});if(!je)return;const me=typeof je.sessionId=="string"&&je.sessionId?je.sessionId:typeof je.instanceId=="string"&&je.instanceId?je.instanceId:(ue=Re.find(Te=>Te.ideId===je.id))==null?void 0:ue.sessionId;me&&(ee(null),tt(me))},[Re,tt,m,M]),a.useEffect(()=>{if(!M)return;const le=window.setTimeout(()=>{ee(je=>!je||je.startedAt!==M.startedAt?je:null)},45e3);return()=>window.clearTimeout(le)},[M]),_l({visibleConversations:Ie,clearedTabs:oe,setClearedTabs:ge,setActionLogs:ve}),Wl({ides:m,sendDaemonCommand:t,setToasts:x,setLocalUserMessages:pe,resolveConversationByTarget:z});const{isRefreshingHistory:fi,handleLaunchIde:hi,handleRefreshHistory:bi}=Ln({sendDaemonCommand:t,activeConv:Me,updateIdeChats:v,setToasts:x,setLocalUserMessages:pe,setClearedTabs:ge}),{isCreatingChat:gi,isRefreshingHistory:yi,handleSwitchSession:vi,handleNewChat:wi,handleRefreshHistory:ji}=Ln({sendDaemonCommand:t,activeConv:U,updateIdeChats:v,setToasts:x,setLocalUserMessages:pe,setClearedTabs:ge}),lr=a.useCallback(async()=>{if(!(!U||!ce||X)){Z(!0);try{const le=U.daemonId||U.ideId,je=U.agentType||U.ideType,me=await t(le,"list_saved_sessions",{agentType:je,providerType:je,kind:"cli",limit:50}),ue=(me==null?void 0:me.result)??me;ke(Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[])}catch(le){console.error("Refresh saved sessions failed",le),ke([])}finally{Z(!1)}}},[U,X,ce,t]);a.useEffect(()=>{if(!J){ye.current=null;return}if(!ce){ye.current=null,ke([]),Z(!1);return}!be||X||ye.current!==be&&(ye.current=be,lr())},[lr,J,X,ce,be]);const ki=a.useCallback(async le=>{if(!U||!ce||!le.providerSessionId||!le.workspace)return;const je=U.daemonId||U.ideId,me=U.agentType||U.ideType;try{fe(le.providerSessionId);const ue=await t(je,"launch_cli",{cliType:me,dir:le.workspace,resumeSessionId:le.providerSessionId,initialModel:le.currentModel}),Te=(ue==null?void 0:ue.result)??ue,Qe=typeof(Te==null?void 0:Te.sessionId)=="string"?Te.sessionId:typeof(Te==null?void 0:Te.id)=="string"?Te.id:"";Qe&&i(fs=>{const ss=new URLSearchParams(fs);return ss.set("activeTab",Qe),ss},{replace:!0}),K(!1)}catch(ue){console.error("Resume saved session failed",ue)}finally{fe(null)}},[U,ce,t,i]);Yl({urlActiveTab:T&&!Se?o:null,conversations:Re,resolveConversationBySessionId:Ge,normalizedGroupAssignments:qe,hasHydratedStoredLayout:T&&!Se?L:!0,hydrateStoredLayout:T&&!Se?B:()=>{},setGroupActiveTabIds:E,setFocusedGroup:j,setSearchParams:i,historyModalOpen:J,activeConv:Me,isRefreshingHistory:fi,ides:m,handleRefreshHistory:bi});const en=a.useCallback(async(le,je)=>{const me=je||V||Me;if(!me||!Ke(me)&&!De(me))return;const ue=me.ideType||me.agentType||"",Te=me.ideId||me.daemonId||"";try{await t(Te,"stop_cli",{cliType:ue,targetSessionId:me.sessionId,mode:le})}catch(Qe){console.error("Stop CLI failed:",Qe)}},[Me,V,t]),Ni=a.useCallback(async le=>{const je=le||Me;!je||!Ke(je)&&!De(je)||(H(je),W(!0))},[Me]),Si=a.useMemo(()=>!Me||!Ke(Me)||De(Me)?null:ds(Me),[Me]),Ci=a.useCallback(async le=>{if(!(!Me||!Ke(Me)||De(Me)||ds(Me)===le))try{await t(Et(Me)||Me.ideId,"set_cli_view_mode",{targetSessionId:Me.sessionId,cliType:Jt(Me),mode:le})}catch(me){mu(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[Me,t]),{versionMismatchDaemons:Ii,appVersion:_i,versionBannerDismissed:Ti,setVersionBannerDismissed:Ai,upgradingDaemons:Mi,handleBannerUpgrade:Pi}=sd({ides:m,sendDaemonCommand:t}),tn=a.useCallback(le=>{se(le.tabKey),i(je=>{const me=new URLSearchParams(je),ue=ec(le);return ue?me.set("activeTab",ue):me.delete("activeTab"),me},{replace:!0})},[i]),sn=a.useCallback(le=>{Xe(le.tabKey),tn(le)},[tn,Xe]),Li=a.useCallback(le=>{Fe(le.tabKey)},[Fe]);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(bc,{wsStatus:g,showReconnected:I}),e.jsx(gc,{terminalBackend:de,isStandalone:ae,machineLabel:Ce,machineKey:Ee}),!Ti&&e.jsx(lu,{daemons:Ii,targetVersion:_i,upgradingDaemons:Mi,onUpgrade:Pi,onDismiss:()=>Ai(!0)}),e.jsx(su,{showMobileChatMode:Se,isMobile:T,activeConv:Me,chatIdes:it,wsStatus:g,isConnected:b,onOpenHistory:le=>{le&&vt(le),K(!0)},onOpenRemote:St,onStopCli:Ni,activeCliViewMode:Si,onSetActiveCliViewMode:Ci,mobileChatConversations:_e,ides:m,actionLogs:he,sendDaemonCommand:t,setLocalUserMessages:pe,setActionLogs:ve,isStandalone:ae,initialDataLoaded:f,userName:p.userName,requestedMobileTabKey:ts,onRequestedMobileTabConsumed:ne,requestedMachineId:d,onRequestedMachineConsumed:()=>{r(s.pathname+s.search,{replace:!0,state:null})},requestedMobileSection:l,onRequestedMobileSectionConsumed:()=>{r(s.pathname+s.search,{replace:!0,state:null})},containerRef:Le,isSplitMode:dt,numGroups:Dt,groupSizes:_,groupedConvs:ft,clearedTabs:oe,focusedGroup:y,setFocusedGroup:j,moveTabToGroup:Bt,splitTabRelative:kt,closeGroup:jt,handleResizeStart:gt,detectedIdes:q,handleLaunchIde:hi,groupActiveTabIds:S,setGroupActiveTabIds:E,groupTabOrders:D,setGroupTabOrders:O,toggleHiddenTab:xt,visibleConversations:Ie,hiddenConversations:Be,requestedDesktopTabKey:Kt,onRequestedDesktopTabConsumed:ne,onDesktopActiveTabChange:se,onHideConversation:Li,onShowHiddenConversation:sn,onShowAllHiddenConversations:We,scrollToBottomRequest:Q,machineEntries:F,onBrowseMachineDirectory:ut,onSaveMachineWorkspace:Ze,onLaunchMachineIde:xs,onLaunchMachineProvider:pi,onListMachineSavedSessions:xi}),e.jsx("style",{children:`
46
- body { overflow: hidden; overscroll-behavior: none; }
47
- `}),e.jsx(cu,{historyModalOpen:J,historyTargetConv:U,ides:m,isHistoryCreatingChat:gi,isHistoryRefreshingHistory:ce?!1:yi,savedHistorySessions:te,isSavedHistoryLoading:X,isResumingSavedHistorySessionId:G,onCloseHistory:()=>K(!1),onNewHistoryChat:wi,onSwitchHistorySession:vi,onRefreshHistory:ce?lr:ji,onResumeSavedHistorySession:ki,remoteDialogConv:$e,remoteDialogIdeEntry:yt,connectionStates:C,actionLogs:he,localUserMessages:ie,sendDaemonCommand:t,setLocalUserMessages:pe,setActionLogs:ve,isStandalone:ae,userName:p.userName,onOpenRemoteHistory:le=>{le&&vt(le),K(!0)},onRemoteConversationChange:vt,onCloseRemoteDialog:R,cliStopDialogOpen:$,cliStopTargetConv:V,onCancelCliStop:()=>{W(!1),H(null)},onStopCliNow:async()=>{W(!1),await en("hard",V),H(null)},onSaveCliAndStop:async()=>{W(!1),await en("save",V),H(null)},toasts:k,onDismissToast:le=>x(je=>je.filter(me=>me.id!==le)),onClickToast:le=>{if(le.targetKey){const je=z(le.targetKey);je&&(j(qe.get(je.tabKey)??0),sn(je),xe({tabKey:je.tabKey,nonce:Date.now()}))}},showOnboarding:w,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}u(!1)}})]})}function xu({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:i}){const[o,c]=a.useState([]),[d,l]=a.useState(null),[p,m]=a.useState(null),[f,v]=a.useState(!1),[x,w]=a.useState(null),[u,k]=a.useState(!1),[g,b]=a.useState(""),C=a.useRef(null),I=a.useCallback(K=>{C.current=K},[]),N=a.useCallback((K,$,W=!1)=>{c(V=>[...V.slice(-100),{timestamp:Date.now(),level:K,message:$}]),setTimeout(()=>{var V;return(V=i.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),W&&at.showToast($,K==="error"||K==="warn"?"warning":"success")},[i]),h=a.useCallback(K=>{const $=K instanceof Error?K.message:String(K||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),y=a.useCallback(async(K,$)=>{var W;if(!t||d)return!1;l(K),N("info",`Launching ${Oe(K)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const V={ideType:K,enableCdp:!0};(W=$==null?void 0:$.workspace)!=null&&W.trim()?V.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(V.useDefaultWorkspace=!0);const H=await r(t,"launch_ide",V);return N(H!=null&&H.success?"info":"error",H!=null&&H.success?`${Oe(K)} launched`:`Failed: ${H==null?void 0:H.error}`,!0),!!(H!=null&&H.success)}catch(V){return N("error",`Launch error: ${V.message}`,!0),!1}finally{l(null)}},[t,d,N,r]),j=a.useCallback(async K=>{if(!t)return{success:!1};const{cliType:$,dir:W,workspaceId:V,useDefaultWorkspace:H,useHome:te,argsStr:ke,model:X,resumeSessionId:Z}=K;if(!$)return N("warn","Select a CLI or ACP provider first",!0),{success:!1};const G=ke?ke.split(/\s+/).filter(Boolean):void 0,fe=(W==null?void 0:W.trim())||(V?"(saved id)":H?"(default workspace)":te?"(home)":"");N("info",`Launching ${$}${fe?` in ${fe}`:""}${X?` (model: ${X})`:""}...`),m($);try{const re={cliType:$,cliArgs:G,initialModel:X||void 0};W!=null&&W.trim()?re.dir=W.trim():V?re.workspaceId=V:H?re.useDefaultWorkspace=!0:te&&(re.useHome=!0),Z&&(re.resumeSessionId=Z);const he=await r(t,"launch_cli",re),ve=(he==null?void 0:he.result)||he;return he!=null&&he.success?(N("info",`${$} launched`,!0),(ve==null?void 0:ve.launchSource)==="home"?N("info","📂 Running in home directory (explicit choice)"):(ve==null?void 0:ve.launchSource)==="defaultWorkspace"&&N("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ve==null?void 0:ve.sessionId}):(N("error",`Failed: ${(he==null?void 0:he.error)||(ve==null?void 0:ve.error)}`,!0),(he==null?void 0:he.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&w({cliType:$,argsStr:ke,model:X}),{success:!1,sessionId:ve==null?void 0:ve.sessionId})}catch(re){return h(re)?(N("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(N("error",`Launch error: ${re.message}`,!0),{success:!1})}finally{m(null)}},[t,N,h,r]),S=a.useCallback(async(K,$,W,V)=>t?K?$.trim()?j({cliType:K,dir:$,argsStr:W,model:V}):(w({cliType:K,argsStr:W,model:V}),{success:!1}):(N("warn","Select a provider",!0),{success:!1}):{success:!1},[t,N,j]),E=a.useCallback(async(K,$,W)=>{if(t&&window.confirm(`Stop ${K}?
48
- This will terminate the process.`))try{const V=await r(t,"stop_cli",{cliType:K,dir:$,targetSessionId:W});V!=null&&V.success?N("info",`${K} stopped`,!0):N("error",`Stop failed: ${(V==null?void 0:V.error)||"Unknown error"}`,!0)}catch(V){N("error",`Stop failed: ${V.message}`,!0)}},[t,N,r]),D=a.useCallback(async K=>{try{await r(K.daemonId,"restart_ide",{ideType:K.type}),N("info",`${Oe(K.type)} restart initiated`,!0)}catch($){N("error",`Restart failed: ${$.message}`,!0)}},[N,r]),O=a.useCallback(async K=>{if(window.confirm(`Stop ${Oe(K.type)}?
49
- This will disconnect CDP and optionally kill the process.`))try{const $=await r(K.daemonId,"stop_ide",{ideType:K.type,killProcess:!0});$!=null&&$.success?N("info",`${Oe(K.type)} stopped`,!0):N("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){N("error",`Stop failed: ${$.message}`,!0)}},[N,r]),_=a.useCallback(async()=>{if(t)try{const K=await r(t,"detect_ides",{});N("info",`Found ${((K==null?void 0:K.result)||[]).length} IDE(s)`,!0)}catch(K){N("error",`Detection failed: ${K.message}`,!0)}},[t,N,r]),P=a.useCallback(async K=>{if(!t||!K.trim())return!1;v(!0);try{const $=await r(t,"workspace_add",{path:K.trim()});return $!=null&&$.success?(N("info",`Workspace added: ${K.trim()}`),!0):(N("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return N("error",$.message),!1}finally{v(!1)}},[t,N,r]),T=a.useCallback(async K=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){v(!0);try{const $=await r(t,"workspace_remove",{id:K});$!=null&&$.success?N("info","Workspace removed",!0):N("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){N("error",$.message,!0)}finally{v(!1)}}},[t,N,r]),L=a.useCallback(async K=>{var $;if(t){v(!0);try{const W=await r(t,"workspace_set_default",K===null?{clear:!0}:{id:K});if(W!=null&&W.success){N("info",K?"Default workspace updated":"Default workspace cleared",!0);const V=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";V&&(($=C.current)==null||$.call(C,V))}else N("error",(W==null?void 0:W.error)||"workspace_set_default failed",!0)}catch(W){N("error",W.message,!0)}finally{v(!1)}}},[t,N,r]),B=a.useCallback(async K=>{var W;if(!t||!K.trim())return;const $=K.trim();v(!0);try{const V=await r(t,"workspace_set_default",{path:$});V!=null&&V.success?(N("info","Default workspace set from history"),(W=C.current)==null||W.call(C,$)):N("error",(V==null?void 0:V.error)||"Could not set default (path missing on disk?)")}catch(V){N("error",V.message)}finally{v(!1)}},[t,N,r]),J=a.useCallback(async()=>{if(t)try{if(await r(t,"set_machine_nickname",{nickname:g}),n)try{await n({machineRuntimeId:t,registeredMachineId:s,nickname:g})}catch(K){N("warn",`Live nickname updated, but account sync failed: ${K.message}`)}N("info",`Nickname set to "${g||"(cleared)"}"`),k(!1)}catch(K){N("error",`Failed: ${K.message}`)}},[t,g,s,N,n,r]);return{logs:o,launchingIde:d,launchingAgentType:p,workspaceBusy:f,launchPick:x,setLaunchPick:w,editingNickname:u,setEditingNickname:k,nicknameInput:g,setNicknameInput:b,addLog:N,handleLaunchIde:y,runLaunchCliCore:j,handleLaunchCli:S,handleStopCli:E,handleRestartIde:D,handleStopIde:O,handleDetectIdes:_,handleWorkspaceAdd:P,handleWorkspaceRemove:T,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:B,handleSaveNickname:J,setOnDefaultWorkspaceChanged:I}}function fu({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:i,actions:o,sendDaemonCommand:c}){const{workspaceBusy:d,handleWorkspaceAdd:l,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=o,[f,v]=a.useState(!1),[x,w]=a.useState(""),[u,k]=a.useState([]),[g,b]=a.useState(!1),[C,I]=a.useState(""),N=a.useCallback(async E=>{b(!0),I("");try{const D=await ir(c,t,E);w(D.path),k(D.directories)}catch(D){I(D instanceof Error?D.message:"Could not load folder")}finally{b(!1)}},[t,c]),h=a.useCallback(()=>{var D;v(!0);const E=ar(s.platform,[s.defaultWorkspacePath,(D=s.workspaces[0])==null?void 0:D.path]);N(E)},[N,s.defaultWorkspacePath,s.platform,s.workspaces]),y=s.availableMem??s.freeMem,j=s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/s.totalMem*100))):0,S=s.loadavg[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(Ps,{icon:e.jsx(Br,{size:16}),label:"Uptime",value:Oo(s.uptime)}),e.jsx(Ps,{icon:e.jsx(ct,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Ps,{icon:e.jsx(Is,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Ps,{icon:e.jsx(mo,{size:16}),label:"ACPs",value:`${i.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(xn,{value:Math.min(Math.round(S/s.cpus*100),100),max:100,label:"CPU Load",color:"#8b5cf6",detail:`${S.toFixed(2)} avg / ${s.cpus} cores`}),e.jsx(xn,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:`${bn(s.totalMem-y)} / ${bn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`})]})]}),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(ls,{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:d,value:s.defaultWorkspaceId||"",onChange:E=>void m(E.target.value===""?null:E.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(E=>e.jsx("option",{value:E.id,children:E.label||E.path},E.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:d,onClick:h,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(E=>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:[E.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:sr(E.path,E.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:E.path,children:E.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:d,onClick:()=>void p(E.id),children:"Remove"})]},E.id))})]}),f&&e.jsx(or,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:x,directories:u,busy:g,error:C,confirmLabel:"Add workspace",onClose:()=>v(!1),onNavigate:E=>{N(E)},onConfirm:E=>{(async()=>{if(!E)return;await l(E)&&v(!1)})()}})]})}function hu(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 bu(t,s,r){const n=[];for(const[i,o]of Object.entries(t.settings)){const c=o;if(c.length===0)continue;const d=s.find(l=>l.type===i);n.push({type:i,displayName:(d==null?void 0:d.displayName)||i,icon:(d==null?void 0:d.icon)||"",category:(d==null?void 0:d.category)||"unknown",schema:c,values:t.values[i]||{}})}return n}const Xn=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],gu=[{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 yu({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[i,o]=a.useState("config"),[c,d]=a.useState("codex-cli"),[l,p]=a.useState([]),[m,f]=a.useState(""),[v,x]=a.useState([]),[w,u]=a.useState(""),k=a.useRef(null),g=a.useRef(null),b=j=>{p(S=>S.includes(j)?S.filter(E=>E!==j):[...S,j])},C=()=>p([...Xn]),I=()=>p([]);a.useEffect(()=>{var j;(j=k.current)==null||j.scrollIntoView({behavior:"smooth"})},[v]),a.useEffect(()=>()=>{g.current&&clearInterval(g.current)},[]);const N=a.useCallback(()=>{g.current&&clearInterval(g.current),g.current=setInterval(async()=>{try{const j=await r(t,"provider_auto_fix_status",{providerType:s.type});(j==null?void 0:j.running)===!1&&i==="running"&&(o("done"),x(S=>[...S,`
50
- ✅ Auto-fix completed!`]),g.current&&clearInterval(g.current))}catch{}},3e3)},[t,s.type,r,i]),h=async()=>{if(l.length!==0){o("running"),x(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${l.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),u("");try{const j=await r(t,"provider_auto_fix",{providerType:s.type,functions:l,agent:c,...m?{comment:m}:{}});j!=null&&j.success&&(j!=null&&j.started||j!=null&&j.running)?(x(S=>[...S,"✅ Agent started. Monitoring progress..."]),N()):(o("error"),u((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){o("error"),u((j==null?void 0:j.message)||"Connection failed")}}},y=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),x(j=>[...j,`
51
- ⚠️ Auto-fix cancelled.`]),o("done"),g.current&&clearInterval(g.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:j=>j.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:[i==="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:gu.map(j=>e.jsxs("button",{onClick:()=>d(j.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===j.value?j.color+"66":"var(--border-subtle)",background:c===j.value?j.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===j.value?j.color:"var(--text-primary)"},children:j.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:j.desc})]},j.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:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Xn.map(j=>e.jsxs("button",{onClick:()=>b(j),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:l.includes(j)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l.includes(j)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:l.includes(j)?"#a78bfa":"var(--text-secondary)"},children:[l.includes(j)?"☑ ":"☐ ",j]},j))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:m,onChange:j=>f(j.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"})]})]}),(i==="running"||i==="done"||i==="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:[v.map((j,S)=>e.jsx("div",{className:j.startsWith("✅")?"text-green-400":"",style:j.startsWith("❌")||j.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:j},S)),i==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:k})]}),w&&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:w})]})]}),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:[i==="config"&&l.length>0&&`${l.length} script(s) selected`,i==="running"&&"Agent is generating...",i==="done"&&"Run `adhdev provider verify` to validate"]}),e.jsxs("div",{className:"flex gap-2",children:[i==="config"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:h,disabled:l.length===0,className:"machine-btn",style:{background:l.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:l.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:l.length>0?"#a78bfa":void 0,opacity:l.length===0?.4:1},children:"🚀 Start Fix"})]}),i==="running"&&e.jsx("button",{onClick:y,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(i==="done"||i==="error")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{o("config"),x([]),u("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function vu({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:i}){var N;const o=s.filter(h=>h.category==="ide"),[c,d]=a.useState(((N=o[0])==null?void 0:N.type)||""),[l,p]=a.useState(""),[m,f]=a.useState(""),[v,x]=a.useState(!1),[w,u]=a.useState(""),[k,g]=a.useState(!1),b=h=>{const y=h.toLowerCase().replace(/[^a-z0-9-]/g,"");p(y),(!m||m===C(l))&&f(C(y))},C=h=>h.split("-").map(y=>y.charAt(0).toUpperCase()+y.slice(1)).join(" "),I=async()=>{if(!(!l||!m||!c)){x(!0),u("");try{const h=await r(t,"provider_clone",{type:l,name:m,category:"ide",location:"user",cloneFrom:c});h!=null&&h.success||h!=null&&h.created?(g(!0),i==null||i(l)):u((h==null?void 0:h.error)||"Failed to create provider")}catch(h){u((h==null?void 0:h.message)||"Connection failed")}x(!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:h=>h.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:k?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:l})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",l,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",l]})," 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:o.map(h=>e.jsxs("button",{onClick:()=>d(h.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===h.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===h.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:h.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===h.type?"#a78bfa":"var(--text-secondary)"},children:h.displayName})]},h.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:l,onChange:h=>b(h.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/",l||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:m,onChange:h=>f(h.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"})]}),w&&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:w})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:k?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:I,disabled:!l||!m||v,className:"machine-btn",style:{background:l&&m?"rgba(34,197,94,0.12)":void 0,borderColor:l&&m?"rgba(34,197,94,0.3)":void 0,color:l&&m?"#86efac":void 0,opacity:!l||!m||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function wu({machineId:t,providers:s,sendDaemonCommand:r}){const[n,i]=a.useState([]),[o,c]=a.useState(!1),[d,l]=a.useState(null),[p,m]=a.useState("all"),[f,v]=a.useState(null),[x,w]=a.useState(!1),u=a.useCallback(async()=>{if(t){c(!0);try{const g=await r(t,"get_provider_settings",{}),b=hu(g);if(b){const C=bu(b,s);C.sort((I,N)=>I.category.localeCompare(N.category)||I.displayName.localeCompare(N.displayName)),i(C)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const k=async(g,b,C)=>{l(`${g}.${b}`),i(I=>I.map(N=>N.type===g?{...N,values:{...N.values,[b]:C}}:N));try{const I=await r(t,"set_provider_setting",{providerType:g,key:b,value:C});I!=null&&I.success||u()}catch{u()}l(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(g=>e.jsx("button",{onClick:()=>m(g),className:`machine-btn text-[10px] px-2 py-0.5 ${p===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>w(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),e.jsx("button",{onClick:u,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),p!=="all"&&n.filter(g=>g.category===p).length>1&&(()=>{const g=n.filter(N=>N.category===p),b=new Map;for(const N of g)for(const h of N.schema){if(h.type!=="boolean")continue;const y=b.get(h.key),j=!!(N.values[h.key]??h.default);y?(y.onCount+=j?1:0,y.total+=1):b.set(h.key,{label:h.label||h.key,onCount:j?1:0,total:1})}const C=[...b.entries()].filter(([,N])=>N.total===g.length);if(C.length===0)return null;const I=async(N,h)=>{for(const y of g)await k(y.type,N,h)};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 ",p.toUpperCase()," providers (",g.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(([N,h])=>{const y=h.onCount===h.total,j=h.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:h.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",h.onCount,"/",h.total,")"]}),e.jsx("button",{onClick:()=>void I(N,!0),disabled:y,className:`machine-btn text-[9px] px-1.5 py-px ${y?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void I(N,!1),disabled:j,className:`machine-btn text-[9px] px-1.5 py-px ${j?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),o&&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(g=>p==="all"||g.category===p).map(g=>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:g.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:g.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:g.category==="acp"?"rgba(139,92,246,0.08)":g.category==="cli"?"rgba(59,130,246,0.08)":g.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:g.category==="acp"?"#a78bfa":g.category==="cli"?"#60a5fa":g.category==="ide"?"#86efac":"var(--status-warning)"},children:g.category}),g.category==="ide"&&e.jsx("button",{onClick:()=>v(s.find(b=>b.type===g.type)||{type:g.type,name:g.displayName,displayName:g.displayName,icon:g.icon,category:g.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:g.schema.map(b=>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:[b.label||b.key,d===`${g.type}.${b.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),b.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:b.description})]}),e.jsx("div",{className:"shrink-0",children:b.type==="boolean"?e.jsx("button",{onClick:()=>k(g.type,b.key,!(g.values[b.key]??b.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:g.values[b.key]??b.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:g.values[b.key]??b.default?21:3}})}):b.type==="number"?e.jsx("input",{type:"number",value:Number(g.values[b.key]??b.default??0)||0,min:b.min,max:b.max,onChange:C=>{const I=parseInt(C.target.value)||0;b.min!==void 0&&I<b.min||b.max!==void 0&&I>b.max||k(g.type,b.key,I)},className:"machine-input w-20 text-center text-[11px]"}):b.type==="select"&&b.options?e.jsx("select",{value:String(g.values[b.key]??b.default??""),onChange:C=>k(g.type,b.key,C.target.value),className:"machine-input text-[11px]",children:b.options.map(C=>e.jsx("option",{value:C,children:C},C))}):e.jsx("input",{type:"text",value:String(g.values[b.key]??b.default??""),onBlur:C=>k(g.type,b.key,C.target.value),className:"machine-input w-[120px] text-[11px]"})})]},b.key))})]},g.type))}),f&&e.jsx(yu,{machineId:t,provider:f,sendDaemonCommand:r,onClose:()=>v(null)}),x&&e.jsx(vu,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>w(!1),onCreated:()=>{w(!1),u()}})]})}function ju({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[i,o]=a.useState(0),[c,d]=a.useState(!0),[l,p]=a.useState("debug"),m=a.useRef(null),f=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const v=async()=>{try{const w=await s(t,"get_logs",{count:200,minLevel:l,since:i}),u=(w==null?void 0:w.result)||w;if(w!=null&&w.success&&Array.isArray(u==null?void 0:u.logs)&&u.logs.length>0){n(g=>[...g,...u.logs.map(C=>({timestamp:C.ts,level:C.level,message:`[${C.category}] ${C.message}`}))].slice(-300));const k=Math.max(...u.logs.map(g=>g.ts));o(k)}}catch{}};v();const x=setInterval(v,3e3);return()=>clearInterval(x)},[t,c,i,l,s]),a.useEffect(()=>{if(c&&r.length>0){const v=f.current?"smooth":"instant";setTimeout(()=>{var x;(x=m.current)==null||x.scrollIntoView({behavior:v}),f.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(v=>e.jsx("button",{onClick:()=>{p(v),n([]),o(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${l===v?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.toUpperCase()},v))]}),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:()=>d(!c),className:`machine-btn ${c?"text-green-500 border-green-500/30":""}`,children:c?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),o(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((v,x)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:v.level==="error"?"#ef4444":v.level==="warn"?"var(--status-warning)":v.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(v.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:v.level==="error"?"#ef4444":v.level==="warn"?"var(--status-warning)":v.level==="debug"?"#475569":"#8b5cf6"},children:v.level==="error"?"ERR":v.level==="warn"?"WRN":v.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:v.message})]},x)),e.jsx("div",{ref:m})]})]})}function wr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function jr(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Jn(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 i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function ku(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Nu(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 Su(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 Cu(t){var r;const s=new Map;for(const n of t){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const i=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!i)continue;const o=`${n.providerType}::${n.workspace}::${i}`;s.set(o,(s.get(o)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Iu({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,i]=a.useState(null),[o,c]=a.useState(!0),[d,l]=a.useState(""),[p,m]=a.useState(null),f=a.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),v=a.useCallback(async I=>{if(t){I!=null&&I.silent||c(!0);try{const N=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),h=wr(N);if(!(h!=null&&h.success))throw new Error((h==null?void 0:h.error)||"Could not load session host diagnostics");i(h.diagnostics||h.result||null),l("")}catch(N){const h=N instanceof Error?N.message:"Could not load session host diagnostics";l(h)}finally{I!=null&&I.silent||c(!1)}}},[t,r]);a.useEffect(()=>{v();const I=window.setInterval(()=>{v({silent:!0})},8e3);return()=>window.clearInterval(I)},[v]);const x=a.useCallback(async(I,N)=>{const h=`${I}:${N.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${N.displayName}?
52
- This will terminate the hosted runtime.`))){m(h);try{const y=await r(t,I,{sessionId:N.sessionId}),j=wr(y);if(!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||"Session host action failed");const S=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";at.showToast(`Session host ${S}: ${N.displayName}`,"success"),await v({silent:!0})}catch(y){const j=y instanceof Error?y.message:"Session host action failed";at.showToast(j,"warning"),l(j)}finally{m(y=>y===h?null:y)}}},[v,t,r]),w=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
53
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){m("session_host_prune_duplicate_sessions");try{const N=await r(t,"session_host_prune_duplicate_sessions",{}),h=wr(N);if(!(h!=null&&h.success))throw new Error((h==null?void 0:h.error)||"Duplicate prune failed");const y=h.result||{},j=Array.isArray(y.prunedSessionIds)?y.prunedSessionIds.length:0,S=typeof y.duplicateGroupCount=="number"?y.duplicateGroupCount:0;at.showToast(`Pruned ${j} duplicate runtime(s) across ${S} group(s)`,"success"),await v({silent:!0})}catch(N){const h=N instanceof Error?N.message:"Duplicate prune failed";at.showToast(h,"warning"),l(h)}finally{m(N=>N==="session_host_prune_duplicate_sessions"?null:N)}}},[v,t,r]),u=a.useMemo(()=>[...(n==null?void 0:n.sessions)||[]].sort((I,N)=>(N.lastActivityAt||0)-(I.lastActivityAt||0)),[n==null?void 0:n.sessions]),k=a.useMemo(()=>Cu(u),[u]),g=a.useMemo(()=>u.reduce((I,N)=>{var h;return I+(((h=N.attachedClients)==null?void 0:h.length)||0)},0),[u]),b=a.useMemo(()=>[...(n==null?void 0:n.recentTransitions)||[]].slice(-6).reverse(),[n==null?void 0:n.recentTransitions]),C=a.useMemo(()=>[...(n==null?void 0:n.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[n==null?void 0:n.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(Pt,{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:[k>0&&e.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:p==="session_host_prune_duplicate_sessions",children:p==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${n?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:n?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{v()},disabled:o,children:[e.jsx(ms,{size:13}),o?"Refreshing…":"Refresh"]})]})]}),d&&!n&&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(Lt,{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:d})]})]})}),n&&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:n.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:g})]}),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:n.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:Jn(n.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:jr(n.hostStartedAt)})]})]}),C&&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(Lt,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:C.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[jr(C.timestamp),C.sessionId?` · ${C.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(Is,{size:14})," Hosted Runtimes"]}),u.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:u.map(I=>{var D;const N=p===`session_host_resume_session:${I.sessionId}`,h=p===`session_host_restart_session:${I.sessionId}`,y=p===`session_host_stop_session:${I.sessionId}`,j=Nu(I.meta),S=f.get(I.sessionId),E=I.attachedClients.length===1?"1 client":`${I.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:I.displayName||(S==null?void 0:S.cliName)||I.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Su(I.lifecycle)}`,children:I.lifecycle}),j&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:j})]}),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:I.workspaceLabel||(S==null?void 0:S.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:((D=I.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ku(I.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($r,{size:11})," ",E]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Jn(I.lastActivityAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!p,onClick:()=>{x("session_host_resume_session",I)},children:N?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!p,onClick:()=>{x("session_host_restart_session",I)},children:h?"Restarting…":"Restart"}),(I.lifecycle==="running"||I.lifecycle==="starting"||I.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:!!p,onClick:()=>{x("session_host_stop_session",I)},children:y?"Stopping…":"Stop"})]})]})},I.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"}),b.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:b.map(I=>{var h;const N=u.find(y=>y.sessionId===I.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:(N==null?void 0:N.displayName)||((h=f.get(I.sessionId))==null?void 0:h.cliName)||I.sessionId}),e.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:jr(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",e.jsx("span",{className:"font-mono text-text-primary",children:n.endpoint||"unknown"}),d?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",d]}):null]})]})]})}function _u({machine:t,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:i}=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(o=>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:()=>{i(null),n({cliType:s.cliType,workspaceId:o.id,argsStr:s.argsStr,model:s.model})},children:[e.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.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:()=>{i(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:()=>{i(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:()=>i(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 Nr({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 Tu({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:i,onOpenRecent:o,onOpenConversation:c}){const d=n.slice(0,6),l=r.slice(0,4),p=m=>m==="ide"?"IDE":m==="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:[d.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(kr,{icon:e.jsx(Tt,{size:13}),children:"Current Chats"}),e.jsx(Nr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(m=>{const f=Pr(m);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(m),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(m)}),f>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ga(f)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Qt(m)})]},m.tabKey)})})})]}),l.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(kr,{icon:e.jsx(Br,{size:13}),children:"Recent Launches"}),e.jsx(Nr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(m=>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:()=>o(m),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:m.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[p(m.kind),m.subtitle?` · ${m.subtitle}`:""]})]},m.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(kr,{icon:e.jsx(Lt,{size:13}),children:"Daemon Update"}),e.jsx(Nr,{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:"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:"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:i,children:[e.jsx(ms,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Au(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Mu={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 Fs(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Pu(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 Sr({category:t,machine:s,machineId:r,providers:n,managedEntries:i,getIcon:o,actions:c,sendDaemonCommand:d,initialWorkspaceId:l,initialWorkspacePath:p}){const m=us(),{handleLaunchIde:f,handleStopCli:v,handleRestartIde:x,handleStopIde:w,handleDetectIdes:u,launchingIde:k,launchingAgentType:g,addLog:b}=c,[C,I]=a.useState(null),N=a.useCallback(R=>{R&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(R)}`})},[m]),h=Mu[t],y=t==="ide",j=t==="acp",S=a.useMemo(()=>n.filter(R=>R.category===t&&(t==="ide"||R.installed!==!1)),[t,n]),E=a.useMemo(()=>new Map(S.map(R=>[R.type,R.displayName||R.type])),[S]),[D,O]=a.useState(""),[_,P]=a.useState(""),[T,L]=a.useState([]),[B,J]=a.useState(""),[K,$]=a.useState(""),[W,V]=a.useState([]),[H,te]=a.useState(!1),[ke,X]=a.useState(""),[Z,G]=a.useState(!1),[fe,re]=a.useState(null),[he,ve]=a.useState(p?"__custom__":l||s.defaultWorkspaceId||""),[ie,pe]=a.useState(p||""),[oe,ge]=a.useState([]),[Y,se]=a.useState(!1),[Q,xe]=a.useState(""),[M,ee]=a.useState([]),[ye,A]=a.useState(!1),[q,F]=a.useState(""),ae=a.useRef(null),[de,Ce]=a.useState(null),Ee=a.useRef("__home__"),[Ae,Fe]=a.useState("__home__"),[xt,Xe]=a.useState(!1),We=a.useRef(0),it=oe.filter(R=>!i.some(U=>U.type===R&&nt(U.status)!=="stopped")),Re=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!he&&ve(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(p){ve("__custom__"),pe(p);return}l&&(ve(l),pe(""))},[l,p]),a.useEffect(()=>{y||D&&(S.some(R=>R.type===D)||(O(""),$("")))},[S,y,D]);const Ie=(()=>{if(he==="__custom__")return ie.trim();if(!he)return"";const R=(s.workspaces||[]).find(U=>U.id===he);return(R==null?void 0:R.path)||""})(),Je=a.useCallback(R=>{const U=Re.current[R];U&&(clearTimeout(U),delete Re.current[R]),ge(ce=>ce.includes(R)?ce.filter(be=>be!==R):ce)},[]),Ge=a.useRef(new Set),z=a.useCallback(async R=>{if(d){A(!0),F("");try{const U=await ir(d,r,R);xe(U.path),pe(U.path),ee(U.directories)}catch(U){F(U instanceof Error?U.message:"Could not load folder")}finally{A(!1)}}},[r,d]),we=a.useCallback(()=>{var U;if(!d)return;ve("__custom__"),se(!0);const R=ar(s.platform,[ie.trim(),Ie,s.defaultWorkspacePath,(U=s.workspaces[0])==null?void 0:U.path]);z(R)},[ie,z,s.defaultWorkspacePath,s.platform,s.workspaces,Ie,d]),Ne=a.useCallback(R=>{const U=String(R.workspace||"").trim();if(!U)return;const ce=(s.workspaces||[]).find(be=>Fs(be.path)===Fs(U));if(ce){ve(ce.id),pe("");return}ve("__custom__"),pe(U)},[s.workspaces]),Le=a.useCallback(R=>{const U=String(R.workspace||"").trim();if(!U)return{workspaceId:null,workspacePath:"",useHome:!0};const ce=(s.workspaces||[]).find(be=>Fs(be.path)===Fs(U));return ce?{workspaceId:ce.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:U,useHome:!1}},[s.workspaces]),qe=a.useCallback(async R=>{if(!d||!R||t!=="cli"){V([]),te(!1),X("");return}const U=We.current+1;We.current=U,te(!0),X("");try{const ce=await d(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(We.current!==U)return;const be=(ce==null?void 0:ce.result)??ce;V(Array.isArray(be==null?void 0:be.sessions)?be.sessions:[])}catch(ce){if(We.current!==U)return;V([]),X(ce instanceof Error?ce.message:"Could not load saved sessions")}finally{We.current===U&&te(!1)}},[t,r,d]),Dt=a.useMemo(()=>{if(t!=="cli"||!D)return null;const R=E.get(D)||D;return{ideId:r,daemonId:r,providerSessionId:K||void 0,transport:"pty",mode:"chat",agentName:R,agentType:D,status:"idle",title:R,messages:[],ideType:D,workspaceName:Ie,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${D}`}},[t,r,E,Ie,K,D]),dt=a.useCallback(R=>{if(t==="ide"||!R){L([]);return}L(li(r,R))},[t,r]);a.useEffect(()=>{if($(""),dt(D),t!=="cli"||!D){V([]),X(""),te(!1);return}qe(D)},[t,dt,qe,D]),a.useEffect(()=>{if(!K)return;const R=W.find(U=>U.providerSessionId===K);R!=null&&R.canResume||$("")},[W,K]);const ft=a.useCallback((R,U)=>{ae.current=U,Ee.current=R.selectedWorkspaceKey||"__home__",Fe(R.selectedWorkspaceKey||"__home__"),Ce(R)},[]),Bt=a.useCallback(()=>{ae.current&&(Xe(!0),ae.current().finally(()=>{ae.current=null,Xe(!1),Ce(null)}))},[]),jt=a.useCallback(R=>{if(!R)return;ge(ce=>ce.includes(R)?ce:[...ce,R]);const U=Re.current[R];U&&clearTimeout(U),Re.current[R]=setTimeout(()=>{ge(ce=>ce.includes(R)?ce.filter(be=>be!==R):ce),delete Re.current[R]},2e4)},[]);a.useEffect(()=>{for(const U of i)nt(U.status)!=="stopped"&&(oe.includes(U.type)&&!Ge.current.has(U.type)&&(Ge.current.add(U.type),b("info",`${E.get(U.type)||U.type} launched`,!0)),Je(U.type));const R=new Set(i.filter(U=>nt(U.status)!=="stopped").map(U=>U.type));Ge.current.forEach(U=>{!oe.includes(U)&&!R.has(U)&&Ge.current.delete(U)})},[b,Je,i,oe,E]),a.useEffect(()=>()=>{Object.values(Re.current).forEach(clearTimeout),Re.current={}},[]);const[gt,kt]=a.useState({}),[Me,Kt]=a.useState(null);a.useEffect(()=>{if(!y||!r||!d)return;(async()=>{try{const U=await d(r,"get_ide_extensions",{}),ce=(U==null?void 0:U.result)||U;ce!=null&&ce.success&&(ce!=null&&ce.ideExtensions)&&kt(ce.ideExtensions)}catch{}})()},[y,r,d]);const ts=R=>y?Oe(R.type):t==="cli"?R.cliName:R.acpName,ne=y?s.detectedIdes||[]:[],$e=a.useCallback(async R=>{const U=(R==null?void 0:R.type)||D,ce=(R==null?void 0:R.workspacePath)??Ie;if(y){await f(U,ce?{workspace:ce}:void 0)&&jt(U);return}const be=await c.runLaunchCliCore({cliType:U,dir:R!=null&&R.workspaceId?void 0:ce||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!ce,argsStr:(R==null?void 0:R.argsStr)??(_||void 0),model:(R==null?void 0:R.model)??(j&&B||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!j&&t==="cli"&&U===D&&K||void 0});if(be.success||be.pending){const _e=(R==null?void 0:R.argsStr)??_;!y&&(_e!=null&&_e.trim())&&(di(r,U,_e),dt(U)),jt(U),be.success&&be.sessionId&&N(be.sessionId)}},[c,f,j,y,_,B,dt,jt,r,N,Ie,K,D]),yt=()=>{var be;const R=y?Oe(D):E.get(D)||D,{options:U,selectedKey:ce}=qt({machine:s,currentWorkspaceId:he&&he!=="__custom__"?he:null,currentWorkspacePath:Ie});ft({title:`Launch ${R}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:U,selectedWorkspaceKey:ce,details:[{label:"Mode",value:h.label},{label:"Provider",value:R},...!y&&t==="cli"&&K?[{label:"Resume",value:((be=W.find(_e=>_e.providerSessionId===K))==null?void 0:be.title)||K}]:[],...!y&&_.trim()?[{label:"Arguments",value:_.trim()}]:[],...j&&B.trim()?[{label:"Model",value:B.trim()}]:[]]},async()=>{const _e=U.find(Se=>Se.key===Ee.current);_e!=null&&_e.workspaceId?(ve(_e.workspaceId),pe("")):_e!=null&&_e.workspacePath?(ve("__custom__"),pe(_e.workspacePath)):(ve(""),pe("")),await $e({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},Nt=R=>{y?w(R):v(R.type,R.workspace,R.id)},vt=a.useCallback(async(R,U,ce=!1)=>{if(R.mode===U){ce&&R.sessionId&&N(R.sessionId);return}if(!d||!R.sessionId){ce&&R.sessionId&&N(R.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:U}),ce&&N(R.sessionId)}catch(be){Pu(be)?console.warn("Skipped CLI view mode switch:",be instanceof Error?be.message:String(be)):console.error("Failed to switch CLI view mode:",be)}},[r,N,d]),St=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:he,onChange:R=>{const U=R.target.value;if(ve(U),U==="__custom__"&&d){we();return}U!=="__custom__"&&pe("")},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(R=>e.jsxs("option",{value:R.id,children:[R.id===s.defaultWorkspaceId?"⭐ ":"",sr(R.path,R.label)]},R.id)),e.jsx("option",{value:"__custom__",children:d?"📁 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:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),he==="__custom__"&&(d?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:we,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ie,onChange:R=>pe(R.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:he==="__custom__"?Ie?e.jsx("span",{className:"font-mono truncate block",title:Ie,children:Ie}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ie?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:he===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ie,children:Ie})]}):"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 ${h.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 ",h.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:y?ne.length>0?ne.map(R=>{const U=i.find(Be=>(Be.type||"").toLowerCase()===(R.type||"").toLowerCase()&&nt(Be.status)!=="stopped"),ce=R.running||!!U,be=!!U&&U.cdpConnected,_e=oe.includes(R.type||R.id||""),Se=D===(R.type||"");return e.jsxs("button",{onClick:()=>{if(be&&U){const Be=U.sessionId;Be?m(`/dashboard?activeTab=${encodeURIComponent(Be)}`,{state:{openRemoteForTabKey:Be}}):m("/dashboard",{state:{openRemoteForTabKey:U.id}});return}_e||O(Be=>Be===(R.type||"")?"":R.type||"")},disabled:!!k||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${be?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Se?"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:k&&k!==R.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:o(R.type)}),ce&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${be?"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:R.name||Oe(R.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${be?"text-green-400":_e?"text-orange-400":Se?"text-accent-primary":"text-text-muted"}`,children:be?"Open Session":_e?"Starting...":Se?"Configure":"Select"})]})]},R.type)}):e.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",e.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[e.jsx(io,{size:14})," Scan System"]})]}):S.length>0?S.map(R=>{const U=D===R.type,ce=oe.includes(R.type),_e=!!i.find(Se=>Se.type===R.type&&nt(Se.status)!=="stopped");return e.jsxs("button",{onClick:()=>O(Se=>Se===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${U?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:R.icon}),_e&&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:R.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-orange-400":U?"text-accent-primary":"text-text-muted"}`,children:ce?"Starting...":U?"Configure":"Select"})]})]},R.type)}):e.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",t.toUpperCase()," providers available.",e.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),D&&(y?ne.find(R=>R.type===D):S.find(R=>R.type===D))&&e.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:y?Oe(D):E.get(D)||D})]}),St,!y&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&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 qe(D),disabled:!D||H,children:H?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{D&&(G(!0),qe(D))},disabled:!D,children:"Open History"})]})]}),K?(()=>{const R=W.find(U=>U.providerSessionId===K);return R?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:R.title||R.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:R.providerSessionId}),e.jsx("div",{children:R.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>$(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),ke&&e.jsx("div",{className:"text-[10px] text-red-400",children:ke})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&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:B,onChange:R=>J(R.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:_,onChange:R=>P(R.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),T.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:T.map(R=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(R),title:R,children:R},R))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:yt,disabled:!!g||!!k||oe.includes(D),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:g===D||k===D?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",i.length+oe.filter(R=>!i.some(U=>U.type===R&&nt(U.status)!=="stopped")).length,")"]}),i.length===0&&it.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 ",h.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[it.map(R=>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:o(R)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:y?Oe(R):E.get(R)||R}),e.jsx("div",{className:"text-[11px] text-text-muted",children:g===R?"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:${R}`)),i.map(R=>{const U=y?R:null,ce=j?R:null,be=!y&&!j?R:null,_e=nt(R.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:o(R.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ts(R),(U==null?void 0:U.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",U.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:R.workspace||"—"}),(ce==null?void 0:ce.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",ce.currentModel]}),(ce==null?void 0:ce.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",ce.currentPlan]}),(be==null?void 0:be.mode)&&e.jsx("span",{className:be.mode==="chat"?"text-violet-400":"text-text-secondary",children:be.mode==="chat"?"Chat view":"Terminal view"})]}),be&&(be.runtimeKey||be.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[be.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 ",be.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 Se;(Se=navigator.clipboard)==null||Se.writeText(`adhdev attach ${be.runtimeKey}`),I(be.runtimeKey||null),window.setTimeout(()=>{I(Be=>Be===be.runtimeKey?null:Be)},1200)},children:C===be.runtimeKey?"Copied":"Copy"})]}),be.runtimeWriteOwner&&e.jsx("span",{style:{color:be.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:be.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Au(be.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 ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Se=R.sessionId;if(Se){m(`/dashboard?activeTab=${encodeURIComponent(Se)}`,{state:{openRemoteForTabKey:Se}});return}m("/dashboard",{state:{openRemoteForTabKey:R.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(ct,{size:13})}),e.jsx("button",{onClick:()=>{const Se=R.workspace||"",{options:Be,selectedKey:tt}=qt({machine:s,currentWorkspacePath:Se});ft({title:`Restart ${Oe(R.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Be,selectedWorkspaceKey:tt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Oe(R.type)}]},async()=>{const ut=Be.find(xs=>xs.key===Ee.current),Ze=(ut==null?void 0:ut.workspacePath)??"";if(Ze&&Ze!==Se){await $e({type:R.type,workspacePath:Ze});return}await x(R)})},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(ms,{size:14})})]}),j&&e.jsx("button",{onClick:()=>{const Se=R.sessionId;Se&&N(Se)},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:!R.sessionId,children:e.jsx(Tt,{size:14})}),be&&_e!=="stopped"&&e.jsxs(e.Fragment,{children:[be.mode&&e.jsx(zr,{mode:be.mode,onChange:Se=>void vt(be,Se,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Se=R.sessionId;Se&&N(Se)},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:!R.sessionId,children:be.mode==="chat"?e.jsx(Tt,{size:14}):e.jsx(ct,{size:13})})]}),_e==="stopped"?e.jsx("button",{onClick:()=>{const Se=R.workspace||"",Be=y?Oe(R.type):ts(R),{options:tt,selectedKey:ut}=qt({machine:s,currentWorkspacePath:Se});ft({title:`Launch ${Be}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:tt,selectedWorkspaceKey:ut,details:[{label:"Mode",value:h.label},{label:"Provider",value:Be}]},async()=>{const Ze=tt.find(xs=>xs.key===Ee.current);await $e({type:R.type,workspaceId:(Ze==null?void 0:Ze.workspaceId)??null,workspacePath:(Ze==null?void 0:Ze.workspacePath)??"",useHome:!(Ze!=null&&Ze.workspaceId)&&!(Ze!=null&&Ze.workspacePath),model:ce==null?void 0:ce.currentModel})})},disabled:oe.includes(R.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:oe.includes(R.type)?"⏳":e.jsx(Kr,{size:14})}):e.jsx("button",{onClick:()=>Nt(R),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(Rt,{size:14})})]})]}),U&&U.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:U.aiAgents.map(Se=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${wa(Se.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Se.name," · ",nt(Se.status)]},Se.id))}),U&&(gt[U.type]||[]).length>0&&d&&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:(gt[U.type]||[]).map(Se=>e.jsxs("button",{disabled:Me===`${U.type}.${Se.type}`,onClick:async()=>{const Be=`${U.type}.${Se.type}`;Kt(Be);try{await d(r,"set_ide_extension",{ideType:U.type,extensionType:Se.type,enabled:!Se.enabled}),kt(tt=>({...tt,[U.type]:(tt[U.type]||[]).map(ut=>ut.type===Se.type?{...ut,enabled:!ut.enabled}:ut)}))}catch(tt){console.error("Extension toggle failed:",tt)}finally{Kt(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 ${Se.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 ${Se.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Se.name,e.jsx("span",{className:"text-[9px] font-normal",children:Se.enabled?"ON":"OFF"})]},Se.type))})]})]},R.id)})]}),Y&&d&&e.jsx(or,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Q,directories:M,busy:ye,error:q,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:R=>{z(R)},onConfirm:R=>{pe(R),ve("__custom__"),se(!1)}}),de&&e.jsx(Zr,{title:de.title,description:de.description,details:de.details,workspaceOptions:de.workspaceOptions,selectedWorkspaceKey:Ae,onWorkspaceChange:R=>{Ee.current=R,Fe(R)},confirmLabel:de.confirmLabel,busy:xt,onConfirm:Bt,onCancel:()=>{ae.current=null,Ce(null)}}),Z&&Dt&&e.jsx(Vr,{activeConv:Dt,ides:[],isCreatingChat:!1,isRefreshingHistory:H,savedSessions:W,isSavedSessionsLoading:H,isResumingSavedSessionId:fe,onClose:()=>G(!1),onNewChat:()=>{$(""),G(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{qe(D)},onResumeSavedSession:R=>{if(!R.canResume||fe)return;const U=Le(R);$(R.providerSessionId),Ne(R),re(R.providerSessionId),G(!1),$e({type:R.providerType,workspaceId:U.workspaceId,workspacePath:U.workspacePath,useHome:U.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{re(ce=>ce===R.providerSessionId?null:ce)})}})]})}const Zn=[{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 Lu({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:i,acpSessions:o,actions:c,getIcon:d,initialCategory:l="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var u;const[v,x]=a.useState(l);a.useEffect(()=>{x(l)},[l]);const w=a.useMemo(()=>({ide:n.length,cli:i.length,acp:o.length}),[n.length,i.length,o.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:Zn.map(k=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===k.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>x(k.id),children:[e.jsx("span",{children:k.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===k.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:w[k.id]})]},k.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=Zn.find(k=>k.id===v))==null?void 0:u.helper})]}),v==="ide"&&e.jsx(Sr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),v==="cli"&&e.jsx(Sr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),v==="acp"&&e.jsx(Sr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Ru({onNicknameSynced:t}={}){var ve,ie,pe,oe,ge,Y,se,Q,xe;const{id:s}=zi(),r=us(),n=Rr(),{sendCommand:i}=$t(),o=_a(),c=o.ides||[],d=o.initialLoaded??!0,l=c.find(M=>M.id===s&&M.daemonMode===!0),p=c.some(M=>M.type==="adhdev-daemon"),[m,f]=a.useState("workspace"),[v,x]=a.useState("ide"),w=a.useRef(null),[u,k]=a.useState(null),g=a.useRef("__home__"),[b,C]=a.useState("__home__"),[I,N]=a.useState(!1),h=a.useRef(null),y=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=xu({machineId:s,registeredMachineId:(l==null?void 0:l.machineId)||null,sendDaemonCommand:i,onNicknameSynced:t,logsEndRef:h});a.useEffect(()=>at.onToast(ee=>{o.setToasts(A=>{if(A.some(ae=>ae.message===ee.message&&ee.timestamp-ae.timestamp<3e3))return A;const F={id:ee.id,message:ee.message,type:ee.type,timestamp:ee.timestamp,targetKey:ee.targetKey,actions:ee.actions};return[...A.slice(-4),F]});const ye=ee.duration||5e3;setTimeout(()=>o.setToasts(A=>A.filter(q=>q.id!==ee.id)),ye)}),[o]);const S=(l==null?void 0:l.availableProviders)||[],E={};for(const M of S)E[M.type]=M.icon;const D=M=>E[M]||"",O=l?{id:l.id,hostname:ja(l,{fallbackId:l.id}),platform:((ve=l.machine)==null?void 0:ve.platform)||"unknown",arch:((ie=l.machine)==null?void 0:ie.arch)||"",cpus:((pe=l.machine)==null?void 0:pe.cpus)||0,totalMem:((oe=l.machine)==null?void 0:oe.totalMem)||0,freeMem:((ge=l.machine)==null?void 0:ge.freeMem)||0,availableMem:(Y=l.machine)==null?void 0:Y.availableMem,loadavg:((se=l.machine)==null?void 0:se.loadavg)||[],uptime:((Q=l.machine)==null?void 0:Q.uptime)||0,release:((xe=l.machine)==null?void 0:xe.release)||"",cdpConnected:!!l.cdpConnected,machineNickname:l.machineNickname||null,p2p:l.p2p?{screenshotActive:!1,...l.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:l.detectedIdes||[],workspaces:l.workspaces||[],defaultWorkspaceId:l.defaultWorkspaceId??l.activeWorkspaceId??null,defaultWorkspacePath:l.defaultWorkspacePath??l.activeWorkspacePath??null}:null,_=c.filter(M=>M.daemonId===s&&!M.daemonMode).filter(M=>!Ns(M)&&!is(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,version:M.version||"",instanceId:M.instanceId||"",status:M.status,workspace:M.workspace||null,terminals:M.terminals||0,aiAgents:qo(M.aiAgents||(M.agents||[]).map(ee=>({id:ee.name,name:ee.name,status:ee.status,version:ee.version}))),activeChat:M.activeChat||null,chats:M.chats||[],childSessions:M.childSessions||[],cdpConnected:M.cdpConnected||!1,daemonId:s})),P=c.filter(M=>M.daemonId===s&&Ns(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,cliName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,mode:M.mode,runtimeKey:M.runtimeKey,runtimeDisplayName:M.runtimeDisplayName,runtimeWorkspaceLabel:M.runtimeWorkspaceLabel,runtimeWriteOwner:M.runtimeWriteOwner||null,runtimeAttachedClients:M.runtimeAttachedClients||[],daemonId:s})),T=c.filter(M=>M.daemonId===s&&is(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,acpName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,currentModel:M.currentModel,currentPlan:M.currentPlan,daemonId:s})),L=l?lt(l,{fallbackId:s}):"",B="workspace",J=n.state,K=J==null?void 0:J.initialMachineTab,$=J==null?void 0:J.initialWorkspaceCategory,W=J==null?void 0:J.initialWorkspaceId,V=J==null?void 0:J.initialWorkspacePath,H=K==="ides"||K==="clis"||K==="acps"?"workspace":K||B,te=K==="ides"?"ide":K==="clis"?"cli":K==="acps"?"acp":$,ke=[..._.map(M=>{var ee,ye,A,q,F;return{id:`ide:${M.type}:${M.workspace||""}`,label:((ee=M.activeChat)==null?void 0:ee.title)||M.type,kind:"ide",providerType:M.type,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,timestamp:((F=(q=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:q.call(A,-1))==null?void 0:F.timestamp)||0}}),...P.map(M=>{var ee,ye,A,q,F;return{id:`cli:${M.type}:${M.workspace||""}`,label:((ee=M.activeChat)==null?void 0:ee.title)||M.cliName,kind:"cli",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,timestamp:((F=(q=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:q.call(A,-1))==null?void 0:F.timestamp)||0}}),...T.map(M=>{var ee,ye,A,q,F;return{id:`acp:${M.type}:${M.workspace||""}`,label:((ee=M.activeChat)==null?void 0:ee.title)||M.acpName,kind:"acp",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.currentModel||M.workspace||void 0,workspace:M.workspace||void 0,currentModel:M.currentModel,timestamp:((F=(q=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:q.call(A,-1))==null?void 0:F.timestamp)||0}})].sort((M,ee)=>ee.timestamp-M.timestamp).map(({timestamp:M,...ee})=>ee),X=((l==null?void 0:l.recentLaunches)||[]).length>0?((l==null?void 0:l.recentLaunches)||[]).map(M=>({id:M.id,label:M.title||M.providerName||M.providerType,kind:M.kind,providerType:M.providerType,providerSessionId:M.providerSessionId,subtitle:M.currentModel||M.workspace||void 0,workspace:M.workspace,currentModel:M.currentModel})):ke,Z=a.useMemo(()=>{var ee;const M=((ee=o.connectionStates)==null?void 0:ee[s||""])||void 0;return c.filter(ye=>ye.daemonId===s&&!ye.daemonMode).flatMap(ye=>Hr(ye,{},{connectionStates:s&&M?{[s]:M}:void 0,defaultConnectionState:M})).filter(ye=>!(ye.transport==="pty"&&ye.mode==="terminal")).sort((ye,A)=>Pr(A)-Pr(ye))},[c,o.connectionStates,s]),G=a.useCallback(M=>{const ee=M.sessionId||M.tabKey;ee&&r(`/dashboard?activeTab=${encodeURIComponent(ee)}`)},[r]),fe=a.useCallback(()=>{w.current&&(N(!0),w.current().finally(()=>{w.current=null,N(!1),k(null)}))},[]),re=a.useCallback(M=>{if(!O)return;const{options:ee,selectedKey:ye}=qt({machine:O,currentWorkspacePath:M.workspace}),A=async()=>{x(M.kind),f("workspace")};w.current=async()=>{const q=ee.find(de=>de.key===g.current),F=(q==null?void 0:q.workspacePath)??null,ae=(q==null?void 0:q.workspaceId)??null;if(M.kind==="ide"&&M.providerType){await j.handleLaunchIde(M.providerType,F?{workspace:F}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await j.runLaunchCliCore({cliType:M.providerType,dir:ae?void 0:F||"",workspaceId:ae||void 0,model:M.kind==="acp"?M.currentModel:void 0,resumeSessionId:M.providerSessionId});return}await A()},g.current=ye,C(ye),k({title:`Launch ${M.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ee,details:[{label:"Mode",value:M.kind.toUpperCase()},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]})},[j,O]);if(a.useEffect(()=>{f(H)},[B,H,s]),a.useEffect(()=>{te&&x(te)},[te,s]),!O)return d?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:y,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 he=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ct,{size:14})," Workspace"]}),count:_.length+P.length+T.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(er,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(co,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ao,{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:y,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:j.nicknameInput,onChange:M=>j.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&j.handleSaveNickname(),M.key==="Escape"&&j.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),e.jsx("button",{onClick:j.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),e.jsx("button",{onClick:()=>j.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{j.setEditingNickname(!0),j.setNicknameInput(O.machineNickname||"")},title:"Click to set nickname",children:L}),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:[O.platform," · ",O.arch]}),e.jsxs("span",{children:[O.cpus," cores"]}),(l==null?void 0:l.version)&&e.jsxs("span",{children:["v",l.version]}),O.p2p.available&&e.jsxs("span",{children:["P2P ",O.p2p.state==="connected"?"connected":O.p2p.state]}),O.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:O.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:he.map(M=>e.jsxs("button",{onClick:()=>f(M.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===M.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[M.label,M.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===M.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:M.count})]},M.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:[m==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Tu,{machineEntry:l,providers:S,recentLaunches:X,currentConversations:Z,onUpgradeDaemon:async()=>{try{await i(s,"daemon_upgrade",{})}catch{}},onOpenRecent:re,onOpenConversation:G}),e.jsx(Lu,{machine:O,machineId:s,providers:S,ideSessions:_,cliSessions:P,acpSessions:T,actions:j,getIcon:D,initialCategory:v,initialWorkspaceId:W,initialWorkspacePath:V,sendDaemonCommand:i})]}),m==="providers"&&e.jsx(wu,{machineId:s,providers:S,sendDaemonCommand:i}),m==="overview"&&e.jsx(fu,{machineId:s,machine:O,ideSessions:_,cliSessions:P,acpSessions:T,actions:j,sendDaemonCommand:i}),m==="session-host"&&e.jsx(Iu,{machineId:s,cliSessions:P,sendDaemonCommand:i}),m==="logs"&&e.jsx(ju,{machineId:s,sendDaemonCommand:i})]})})}),j.launchPick&&O&&e.jsx(_u,{machine:O,launchPick:j.launchPick,actions:j}),u&&e.jsx(Zr,{title:u.title,description:u.description,details:u.details,workspaceOptions:u.workspaceOptions,selectedWorkspaceKey:b,onWorkspaceChange:M=>{g.current=M,C(M)},confirmLabel:u.confirmLabel,busy:I,onConfirm:fe,onCancel:()=>{w.current=null,k(null)}}),e.jsx(La,{toasts:o.toasts||[],onDismiss:M=>o.setToasts(ee=>ee.filter(ye=>ye.id!==M)),onClickToast:M=>{M.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(M.targetKey)}`)}}),e.jsx("style",{children:`
54
- @keyframes toast-in {
55
- from { opacity: 0; transform: translateX(40px); }
56
- to { opacity: 1; transform: translateX(0); }
57
- }
58
- `})]})}function Eu(){const[t,s]=a.useState({ide:[],cli:[],ext:[],acp:[]}),[r,n]=a.useState(!0);a.useEffect(()=>{const l=new AbortController,p=setTimeout(()=>l.abort(),1e4);return fetch("https://raw.githubusercontent.com/vilmire/adhdev-providers/main/registry.json",{signal:l.signal}).then(m=>m.json()).then(m=>{const f=[],v=[],x=[],w=[];Object.entries(m.providers||{}).forEach(([k,g])=>{const b=Mc(k),C={id:k,name:g.name||"Unknown",verification:b,registryStatus:g.status||"Stable",details:g.details||"Community Provider"};g.category==="ide"?f.push(C):g.category==="cli"?v.push(C):g.category==="extension"?x.push(C):g.category==="acp"&&w.push(C)});const u=(k,g)=>{const b={verified:1,partial:2,unverified:3},C=b[k.verification.status]||99,I=b[g.verification.status]||99;return C!==I?C-I:k.name.localeCompare(g.name)};s({ide:f.sort(u),cli:v.sort(u),ext:x.sort(u),acp:w.sort(u)})}).catch(m=>{m.name!=="AbortError"&&console.error("Failed to load capabilities:",m)}).finally(()=>{clearTimeout(p),n(!1)}),()=>{clearTimeout(p),l.abort()}},[]);const i=l=>l.status==="verified"?e.jsxs("div",{className:"flex items-center gap-1.5 text-success",children:[e.jsx(ma,{className:"w-4 h-4"})," ",e.jsx("span",{children:"Verified"})]}):l.status==="partial"?e.jsxs("div",{className:"flex items-center gap-1.5 text-warning",children:[e.jsx(Lt,{className:"w-4 h-4"})," ",e.jsx("span",{children:"Partial"})]}):e.jsxs("div",{className:"flex items-center gap-1.5 text-text-muted",children:[e.jsx(Br,{className:"w-4 h-4"})," ",e.jsx("span",{children:"Unverified"})]}),o=l=>l.status==="unverified"&&l.validatedFlows.length===0&&l.testedOn.length===0&&l.testedVersions.length===0&&!l.notes?e.jsx("div",{children:"No recorded validation evidence yet."}):e.jsxs("div",{className:"space-y-1",children:[l.notes?e.jsx("div",{children:l.notes}):null,l.testedOn.length>0?e.jsxs("div",{className:"text-[11px] text-text-muted/80",children:["Tested on: ",l.testedOn.join(", ")]}):null,l.testedVersions.length>0?e.jsxs("div",{className:"text-[11px] text-text-muted/80",children:["Versions: ",l.testedVersions.join(", ")]}):null,l.validatedFlows.length>0?e.jsxs("div",{className:"text-[11px] text-text-muted/80",children:["Flows: ",l.validatedFlows.join(", ")]}):null,l.lastValidated?e.jsxs("div",{className:"text-[11px] text-text-muted/80",children:["Last validated: ",l.lastValidated]}):null,l.evidence?e.jsxs("div",{className:"text-[11px] text-text-muted/80",children:["Evidence: ",l.evidence]}):null]}),c=Object.values(t).flat().reduce((l,p)=>(l[p.verification.status]+=1,l),{verified:0,partial:0,unverified:0}),d=l=>e.jsx("div",{className:"bg-bg-card border border-border-subtle rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary border-b border-border-subtle text-xs uppercase text-text-muted font-medium tracking-wider",children:[e.jsx("th",{className:"py-3 px-4 w-1/3",children:"Target"}),e.jsx("th",{className:"py-3 px-4 w-1/4",children:"Verification"}),e.jsx("th",{className:"py-3 px-4",children:"Details"})]})}),e.jsx("tbody",{className:"divide-y divide-border-subtle text-sm",children:l.map((p,m)=>e.jsxs("tr",{className:"hover:bg-bg-subtle/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 font-medium text-text-main",children:p.name}),e.jsx("td",{className:"py-3 px-4",children:i(p.verification)}),e.jsxs("td",{className:"py-3 px-4 text-text-muted",children:[e.jsx("div",{children:p.details}),e.jsx("div",{className:"mt-1",children:o(p.verification)}),e.jsxs("div",{className:"text-[11px] text-text-muted/70 mt-1",children:["Registry lifecycle: ",p.registryStatus]})]})]},m))})]})});return r?e.jsx(Js,{title:"Capabilities",subtitle:"Built-in provider inventory with verification status",icon:e.jsx(Xs,{}),widthClassName:"max-w-5xl",children:e.jsx(Gr,{icon:e.jsx("div",{className:"w-8 h-8 border-4 border-accent border-t-transparent rounded-full animate-spin mx-auto"}),title:"Loading provider registry",description:"Fetching the latest provider inventory and local verification policy."})}):e.jsxs(Js,{title:"Capabilities",subtitle:"Built-in provider inventory with conservative verification defaults",icon:e.jsx(Xs,{}),widthClassName:"max-w-5xl",contentClassName:"animate-fade-in",children:[e.jsx(et,{title:"Verification Policy",description:"Built-in does not mean supported. Providers are unverified by default until they are explicitly tested and promoted.",children:e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-secondary leading-relaxed",children:["ADHDev ships a broad provider inventory, but this page treats every provider as ",e.jsx("strong",{className:"text-text-primary",children:"unverified"})," unless it has been manually validated with recorded evidence. The upstream registry lifecycle field is shown for reference only."]})}),e.jsx(et,{title:"Verification Summary",description:"Promotion requires an evidence record, not just registry presence or a successful launch once.",children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"Verified"}),e.jsx("div",{className:"text-2xl font-semibold text-success",children:c.verified})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"Partial"}),e.jsx("div",{className:"text-2xl font-semibold text-warning",children:c.partial})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"Unverified"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:c.unverified})]})]})}),e.jsx(et,{title:"Registry overview",description:"Inventory counts loaded from the shared provider registry used across OSS and cloud surfaces.",children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"IDEs"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.ide.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"CLI"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.cli.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"Extensions"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.ext.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"ACP"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.acp.length})]})]})}),e.jsx(et,{title:"IDE inventory",icon:e.jsx(ct,{className:"w-4 h-4"}),description:"Desktop editors and IDE surfaces with registry-backed providers.",children:d(t.ide)}),e.jsx(et,{title:"CLI inventory",icon:e.jsx(Is,{className:"w-4 h-4"}),description:"CLI-first agents that can participate in the standalone dashboard.",children:d(t.cli)}),e.jsx(et,{title:"Extension inventory",icon:e.jsx(Yt,{className:"w-4 h-4"}),description:"IDE extensions and companion integrations available in the registry.",children:d(t.ext)}),e.jsx(et,{title:`ACP inventory (${t.acp.length} loaded)`,icon:e.jsx(Yt,{className:"w-4 h-4"}),description:"ACP-backed providers discovered through the same shared registry.",children:d(t.acp)})]})}class $u{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(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,i){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,i=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:i})}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 i=this.runtimeListeners.get(s);i&&(i.delete(r),i.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 i=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(i=>i(r))}}const Ct=new $u;function Du(){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 Qn=Du(),ea=3e3,Bu=3e4;let It=null,Ku=0;const Qs=new Map;let Ot=null,ws=null;function ta(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Wu(t){return t==="connected"?"connected":t}async function Gs(t,s,r){const n=_c(t,r||{}),i=It;if(i&&i.readyState===WebSocket.OPEN){const o=`req_${++Ku}_${Date.now()}`;return new Promise((c,d)=>{const l=setTimeout(()=>{Qs.delete(o),d(new Error(`WS command timeout: ${s}`))},3e4);Qs.set(o,{resolve:p=>{clearTimeout(l),c(p)},reject:p=>{clearTimeout(l),d(p)}}),i.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}class Ou{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(It==null?void 0:It.readyState)===WebSocket.OPEN}get connectionState(){return(It==null?void 0:It.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Gs(this.daemonId,s,r)}async sendInput(s,r){return Gs(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Ot&&(clearInterval(Ot),Ot=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Gs(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const i=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Ct.emitScreenshot(this.daemonId,i)}}catch{}};r(),Ot=setInterval(r,2e3)}stopScreenshots(s){Ot&&(clearInterval(Ot),Ot=null)}}let pt=null;function Fu(t){return(!pt||pt.daemonId!==t)&&(pt=new Ou(t)),pt}function Uu({children:t}){const s=a.useRef(ln()),r=ln();s.current=r;const{setUserName:n}=Gt(),i=a.useRef(n);i.current=n;const[,o]=a.useState("disconnected"),c=a.useCallback((v,x)=>{o(v),ws==null||ws(v,x)},[]),d=a.useRef(null),l=a.useRef(),p=a.useRef(ea),m=a.useRef(!0),f=a.useRef(!1);return a.useEffect(()=>{m.current=!0,f.current=!1;function v(){var u,k;if(!m.current||((u=d.current)==null?void 0:u.readyState)===WebSocket.OPEN||((k=d.current)==null?void 0:k.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${Qn}...`);let w;try{w=new WebSocket(Qn)}catch(g){console.error("[Standalone WS] Failed to create WebSocket:",g),x();return}d.current=w,w.onopen=()=>{if(!m.current){w.close();return}c("connected"),p.current=ea,console.log("[Standalone WS] Connected")},It=w,w.onmessage=g=>{var b;try{const C=JSON.parse(g.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const I=Qs.get(C.requestId);I&&(Qs.delete(C.requestId),C.type==="error"?I.reject(new Error(((b=C.data)==null?void 0:b.message)||"Command failed")):I.resolve(C.data));return}if(C.type==="session_output"){const I=C.sessionId||C.cliId||C.cliType;I&&Ct.emitSessionOutput(I,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Ct.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated);return}if(C.type==="status"||C.type==="initial_state"){const I=C.data;if(!I)return;const{injectEntries:N,markLoaded:h}=s.current,y=I.id||"standalone",j=Fu(y);Ct.register(y,j),Ct.setState(y,"connected"),c("connected",y),Ct.emitStatus(y,I);const S=Cc(I,{daemonId:y});ta("ws_status",{type:C.type,daemonId:y,sessions:(I.sessions||[]).map(E=>({id:E.id,parentId:E.parentId,providerType:E.providerType,kind:E.kind,transport:E.transport,unread:E.unread,inboxBucket:E.inboxBucket,lastSeenAt:E.lastSeenAt,lastUpdated:E.lastUpdated,title:E.title})),recentLaunches:(I.recentLaunches||[]).map(E=>({id:E.id,providerType:E.providerType,kind:E.kind,workspace:E.workspace,lastLaunchedAt:E.lastLaunchedAt}))}),ta("entries",{daemonId:y,entries:S.filter(E=>E.type!=="adhdev-daemon").map(E=>({id:E.id,type:E.type,unread:E.unread,inboxBucket:E.inboxBucket,lastSeenAt:E.lastSeenAt,lastUpdated:E.lastUpdated,sessionId:E.sessionId}))}),S.length>0&&N(S,{authoritativeDaemonIds:[y]}),h(),I.userName&&i.current&&i.current(I.userName)}}catch(C){console.error("[Standalone WS] Parse error:",C)}},w.onclose=()=>{m.current&&(pt==null||pt.stopScreenshots(),pt&&Ct.setState(pt.daemonId,"disconnected"),c("disconnected"),d.current=null,x())},w.onerror=g=>{f.current||!m.current||console.warn("[Standalone WS] Error, will reconnect:",g)}}function x(){if(!m.current)return;clearTimeout(l.current);const w=p.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),l.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,Bu),v()},w)}return v(),()=>{m.current=!1,f.current=!0,clearTimeout(l.current),d.current&&(d.current.onerror=null,d.current.onclose=null,d.current.close(),d.current=null,It=null),pt&&(pt.stopScreenshots(),Ct.unregister(pt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function zu({children:t}){const[s,r]=a.useState("disconnected"),[n,i]=a.useState(null);a.useEffect(()=>(ws=(c,d)=>{r(c),d&&i(d)},()=>{ws=null}),[]);const o=a.useMemo(()=>{const c=s==="connected",d=Wu(s),l={};return n&&(l[n]=d),l.standalone=d,{wsStatus:s,isConnected:c,connectionStates:l}},[s,n]);return e.jsx(Ji,{connectionOverrides:o,children:e.jsx(Uu,{children:t})})}const Vu=[{id:"dashboard",path:"/dashboard",icon:e.jsx(da,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Pt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(er,{}),label:"Settings"}];function Hu({children:t}){const s=us(),r=Rr(),[n,i]=a.useState(!1),[o,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=m=>{s(m),i(!1)},l=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${o?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${o?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>i(!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:()=>i(!1),onKeyDown:m=>m.key==="Escape"&&i(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${o?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>i(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:Vu.map(m=>e.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>d(m.path),title:o?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!o&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:o?"Docs":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(Xs,{})}),!o&&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":""} ${o?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:o?"About":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(ua,{})}),!o&&"About"]}),!o&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.33"]}),e.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[e.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&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 qu=[{icon:e.jsx(Pt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Tt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(pa,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Yt,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Xs,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Gu=[{icon:e.jsx(xa,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(da,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(tr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(no,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx($r,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(ma,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Yu=[{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 Xu(){return e.jsxs(Js,{icon:e.jsx(ua,{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.33"]}),children:[e.jsx(et,{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(et,{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:qu.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(et,{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:$a.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Ba.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Da.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(et,{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:Gu.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(et,{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:Yu.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(Gr,{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(go,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ju(){const{ides:t}=Gt(),s=t.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=$t(),{userName:i}=Gt(),[o,c]=a.useState(i||"");a.useEffect(()=>{i!==void 0&&c(i)},[i]);const d=f=>{const v=f.target.value.trim();s!=null&&s.id&&v!==i&&n(s.id,"set_user_name",{userName:v}).catch(console.error)},[l,p]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return e.jsxs(Js,{icon:e.jsx(er,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(rl,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(et,{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.33"]}),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(et,{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(f=>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 ${f.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:f.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),e.jsx(et,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(ul,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(et,{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(fl,{})]}),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(kl,{})]}),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(Sl,{})]})]})}),e.jsx(et,{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(ll,{}),e.jsx(Ft,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(bo,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:l,onChange:m})]})}),e.jsx(et,{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(ro,{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:o,onChange:f=>c(f.target.value),onBlur:d,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}cl();wl();const Zu=ca({baseUrl:""});function sa(){const{ides:t,initialLoaded:s}=Gt();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(Cr,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Cr,{to:"/dashboard",replace:!0})}function Qu(){return e.jsx(Vi,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(eo,{client:Zu,children:e.jsx(zu,{children:e.jsx(so,{value:{sendCommand:Gs,sendData:()=>!1},children:e.jsx(Hu,{children:e.jsxs(Hi,{children:[e.jsx(Mt,{path:"/dashboard",element:e.jsx(pu,{})}),e.jsx(Mt,{path:"/machine",element:e.jsx(sa,{})}),e.jsx(Mt,{path:"/machines/:id",element:e.jsx(Ru,{})}),e.jsx(Mt,{path:"/machines",element:e.jsx(sa,{})}),e.jsx(Mt,{path:"/capabilities",element:e.jsx(Eu,{})}),e.jsx(Mt,{path:"/about",element:e.jsx(Xu,{})}),e.jsx(Mt,{path:"/settings",element:e.jsx(Ju,{})}),e.jsx(Mt,{path:"*",element:e.jsx(Cr,{to:"/dashboard",replace:!0})})]})})})})})})}dc({connectionManager:Ct});qi(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(Qu,{})}));