@adhdev/daemon-standalone 0.8.35 → 0.8.37

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 Bi=Object.defineProperty;var Ki=(t,s,r)=>s in t?Bi(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var Ye=(t,s,r)=>Ki(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as na,a as aa,b as Wi,c as Oi,u as ds,R as Ve,d as ia,t as zi,e as Ui,D as Hi,f as Fi,g as Vi,h as Pr,i as Gi,k as qi,B as Yi,l as Xi,m as Bt,N as Sr,n as Ji}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 oa=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}),ca=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 lr(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 qs(t){return Array.isArray(t)?t.map(qs):!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,qs(r)]))}function Zi(t,s){try{return JSON.stringify(qs(t))===JSON.stringify(qs(s))}catch{return!1}}function Ms(t,s,r){return Zi(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function Qi(t,s,r){var l,p,u,x,v,f,w;const n=Date.now(),i=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(m=>({...m,_lastUpdate:n}));const o=new Map;for(const m of s)o.set(m.id,m);for(const m of t){const C=o.get(m.id);if(!C){o.set(m.id,{...m,_lastUpdate:n});continue}const g=cn(m),y=cn(C);if(g>y){const k=(l=m.chats)!=null&&l.length?m.chats:C.chats,I=lr(C,m,{...C,...m,chats:k,_lastUpdate:n});o.set(m.id,Ms(C,I,n))}else if(g<y){const k={};if(m.status&&m.status!==C.status&&(k.status=m.status),m.cdpConnected!==void 0&&(k.cdpConnected=m.cdpConnected),(p=m.chats)!=null&&p.length&&!((u=C.chats)!=null&&u.length)&&(k.chats=m.chats),m.machineNickname!==void 0&&m.machineNickname!==C.machineNickname&&(k.machineNickname=m.machineNickname),m.version!==void 0&&(k.version=m.version),m.serverVersion!==void 0&&(k.serverVersion=m.serverVersion),m.versionMismatch===!0&&(k.versionMismatch=!0),Object.keys(k).length>0){const I=lr(C,m,{...C,...k,_lastUpdate:C._lastUpdate});o.set(m.id,Ms(C,I,n))}else Ms(C,{...C,_lastUpdate:C._lastUpdate},n)}else{const k=m.timestamp||n,I=C._lastUpdate||C.timestamp||0;if(k>=I){const j=(x=m.chats)!=null&&x.length?m.chats:C.chats,h=lr(C,m,{...C,...m,chats:j,_lastUpdate:n});o.set(m.id,Ms(C,h,n))}else(v=m.chats)!=null&&v.length&&!((f=C.chats)!=null&&f.length)&&o.set(m.id,{...C,chats:m.chats})}}const c=new Set(t.map(m=>m.id)),d=new Set;for(const m of t){const C=m.daemonId||((w=m.id)==null?void 0:w.split(":")[0]);C&&d.add(C)}for(const[m,C]of o){const g=C.daemonId||m.split(":")[0];if(!d.has(g))continue;if(i.has(g)&&!c.has(m)){o.delete(m);continue}const y=n-(C._lastUpdate||C.timestamp||0);(C.transport==="pty"&&!c.has(m)&&y>1e4||C.transport==="acp"&&!c.has(m)&&y>1e4||C.transport==="cdp-page"&&!c.has(m)&&y>3e4)&&o.delete(m)}for(const[m,C]of o)n-(C._lastUpdate||C.timestamp||0)>3e5&&C.status!=="online"&&o.delete(m);return Array.from(o.values())}function eo(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 to({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[i,o]=a.useState(!1),[c,d]=a.useState([]),[l,p]=a.useState(void 0),u=a.useRef(r);a.useEffect(()=>{u.current=r},[r]);const x=a.useCallback((g,y)=>{n(k=>{let I=!1;const j=k.map(h=>h.id!==g||h.chats===y?h:(I=!0,{...h,chats:y}));return I?j:k})},[]),v=a.useCallback((g,y)=>{n(k=>{const I=k.length===0?g:Qi(g,k,y);return eo(k,I)?k:I})},[]),f=a.useCallback(()=>o(!0),[]),w=a.useMemo(()=>({injectEntries:v,markLoaded:f,getIdes:()=>u.current}),[v,f]),m=s,C=a.useMemo(()=>({ides:r,updateIdeChats:x,initialLoaded:i,toasts:c,setToasts:d,wsStatus:(m==null?void 0:m.wsStatus)??"connected",isConnected:(m==null?void 0:m.isConnected)??!0,connectionStates:(m==null?void 0:m.connectionStates)??{},connectionTransports:(m==null?void 0:m.connectionTransports)??{},showReconnected:(m==null?void 0:m.showReconnected)??!1,retryConnection:m==null?void 0:m.retryConnection,isP2PActive:(m==null?void 0:m.isP2PActive)??!1,p2pStates:(m==null?void 0:m.p2pStates)??{},userRole:m==null?void 0:m.userRole,userName:l,setUserName:p}),[r,x,i,c,m==null?void 0:m.wsStatus,m==null?void 0:m.isConnected,m==null?void 0:m.connectionStates,m==null?void 0:m.connectionTransports,m==null?void 0:m.showReconnected,m==null?void 0:m.retryConnection,m==null?void 0:m.isP2PActive,m==null?void 0:m.p2pStates,m==null?void 0:m.userRole,l]);return e.jsx(ca.Provider,{value:w,children:e.jsx(oa.Provider,{value:C,children:t})})}function Gt(){return a.useContext(oa)}function ln(){return a.useContext(ca)}function la(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),u=d.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return l&&u.searchParams.set("token",l),!d.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(d,l={}){const p={"Content-Type":"application/json",...l.headers||{}},u=r==null?void 0:r();u&&(p.Authorization=`Bearer ${u}`);const x=i(d),v=new AbortController,f=setTimeout(()=>v.abort(),15e3);try{const w=await fetch(x,{...l,headers:p,signal:v.signal});if(w.status===401)throw n==null||n(),new Error("Unauthorized");if(!w.ok){const m=await w.json().catch(()=>({error:w.statusText}));throw new Error(m.error||`API Error: ${w.status}`)}return w.json()}finally{clearTimeout(f)}}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 so=la({baseUrl:"http://localhost:3847"}),ro=a.createContext(so);function no({client:t,children:s}){return e.jsx(ro.Provider,{value:t,children:s})}const ao={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},da=a.createContext(ao);function io({value:t,children:s}){return e.jsx(da.Provider,{value:t,children:s})}function Rt(){return a.useContext(da)}const Me={size:18};function ua({size:t=Me.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 Rr({size:t=Me.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 Lt({size:t=Me.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 Er({size:t=Me.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 oo({size:t=Me.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 co({size:t=Me.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 ma({size:t=Me.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 lo({size:t=Me.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 Js({size:t=Me.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 pa({size:t=Me.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 uo({size:t=Me.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 At({size:t=Me.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=Me.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 $r({size:t=Me.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 mo({size:t=Me.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function cs({size:t=Me.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function us({size:t=Me.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 qt({size:t=Me.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 js({size:t=Me.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 fa({size:t=Me.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 po({size:t=Me.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 xa({size:t=Me.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 fo({size:t=Me.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 Zs({size:t=Me.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 xo({size:t=Me.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 Dr({size:t=Me.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 ho({size:t=Me.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 ft({size:t=Me.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 ha({size:t=Me.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 bo({size:t=Me.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 go({size:t=Me.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 yo({size:t=Me.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 Qs({size:t=Me.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 vo({size:t=Me.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"5"}),e.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),e.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),e.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),e.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),e.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),e.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),e.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),e.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function wo({size:t=Me.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function jo({size:t=Me.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ko({size:t=Me.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 No({size:t=Me.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 So({size:t=Me.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 Co({size:t=Me.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 Br(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 Yt(t){return Br(t,{normalizeWhitespace:!0})}function ba(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Io(t,s,r){return Number(t.receivedAt||r[ns(t,s)]||0)||0}function To(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ns(t,s){const r=t,n=Br(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,_o=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(na,{remarkPlugins:[aa],children:s.text}),e.jsx("span",{className:"action-time",children:ba(s.timestamp)})]})},(t,s)=>t.log===s.log),Ao=a.memo(function({message:s,receivedAt:r,agentName:n,userName:i,isCliMode:o,isTextExpanded:c,onToggleTextExpanded:d}){var I,j,h;const l=(s.role||"").toLowerCase(),p=l==="user"||l==="human",u=s.kind||(l==="tool"?"tool":"standard"),x=Br(s.content,{joiner:`
4
- `});if(u==="thought"){const b=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(go,{size:13}),e.jsx("span",{children:b})]}),e.jsx("div",{className:"chat-msg-body",children:x})]})}if(u==="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:x.split(`
5
- `)[0].slice(0,80)})]});if(u==="terminal"){const b=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",S=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:b}),e.jsx("span",{children:S})]}),e.jsx("pre",{className:"chat-msg-body",children:x})]})}if(u==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:x.slice(0,100)});const v=s.meta,w=(typeof(v==null?void 0:v.renderMode)=="string"?v.renderMode.trim():"")==="preformatted",m=x,C=o&&!p&&!w&&m.length>un,g=C&&!c?m.slice(0,un):m,y=w,k=!y&&To(g);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(m||p)&&e.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${m?"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:ba(r)})]}),m&&e.jsx("div",{className:"chat-markdown",children:y?e.jsx("pre",{className:"chat-preformatted",children:g}):k?e.jsx(na,{remarkPlugins:[aa,Wi,Oi],children:g}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:g})}),C&&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(m.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),Mo=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:u,isLoadingMore:x,hasMoreHistory:v,hiddenLiveCount:f=0,loadError:w,scrollToBottomRequestNonce:m},C){var ke;const g=a.useRef(null),y=a.useRef(null),k=a.useRef(null),I=a.useRef(0),j=a.useRef(""),h=a.useRef(!1),b=a.useRef(null),S=a.useRef(!1),N=a.useRef(null),E=a.useRef(!1),[D,O]=a.useState(new Set),T=a.useRef(!1),L=()=>{const J=g.current;return J?J.scrollHeight-J.scrollTop-J.clientHeight<200:!0},_=a.useCallback((J="auto")=>{const Z=g.current;Z&&Z.scrollTo({top:Z.scrollHeight,behavior:J})},[]),R=a.useCallback(()=>{var re;const J=g.current,Z=(re=window.getSelection)==null?void 0:re.call(window);if(!J||!Z||Z.rangeCount===0||Z.isCollapsed){E.current=!1;return}const q=Z.anchorNode,xe=Z.focusNode;E.current=!!(q&&xe&&J.contains(q)&&J.contains(xe))},[]),B=a.useCallback((J="auto")=>{b.current!=null&&cancelAnimationFrame(b.current),b.current=requestAnimationFrame(()=>{b.current=null,_(J)})},[_]),Y=s.length>0?`${s.length}:${(((ke=s[s.length-1])==null?void 0:ke.content)||"").length}`:"0:0";a.useEffect(()=>{const J=!h.current,Z=j.current!==d;if(j.current=d,J||Z){h.current=!0,T.current=!1,S.current=!0,E.current||B("auto"),I.current=s.length;return}s.length>I.current?!T.current&&!E.current&&B("auto"):L()&&!T.current&&!E.current&&B("auto"),I.current=s.length},[Y,d,c,s.length,B]),a.useEffect(()=>{m&&(T.current=!1,S.current=!0,N.current!=null&&window.clearTimeout(N.current),N.current=window.setTimeout(()=>{S.current=!1,N.current=null},180),E.current||B("auto"))},[B,m]),a.useEffect(()=>()=>{b.current!=null&&cancelAnimationFrame(b.current),N.current!=null&&window.clearTimeout(N.current)},[]),a.useEffect(()=>{const J=y.current;if(!J)return;const Z=()=>{N.current!=null&&window.clearTimeout(N.current),N.current=window.setTimeout(()=>{S.current=!1,N.current=null},180)},q=new ResizeObserver(()=>{S.current&&(E.current||(B("auto"),Z()))});return q.observe(J),()=>{q.disconnect(),N.current!=null&&(window.clearTimeout(N.current),N.current=null)}},[B,d]),a.useImperativeHandle(C,()=>({scrollToBottom:(J="smooth")=>{_(J)}}),[_]),a.useEffect(()=>{const J=g.current;if(!J)return;let Z;const q=()=>{clearTimeout(Z),Z=setTimeout(()=>{T.current=!L()},50)};return J.addEventListener("scroll",q,{passive:!0}),()=>{J.removeEventListener("scroll",q),clearTimeout(Z)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",R),()=>document.removeEventListener("selectionchange",R)),[R]);const K=a.useRef(0),$=a.useRef(!1);a.useEffect(()=>{const J=g.current;if(!J||!$.current||K.current===0)return;const Z=J.scrollHeight-K.current;Z>0&&(J.scrollTop=Z),K.current=0,$.current=!1},[s.length]);const W=()=>{const J=g.current;J&&(K.current=J.scrollHeight),$.current=!0,u==null||u()},F=a.useMemo(()=>{const J=s.map((re,he)=>({type:"message",data:re,index:he,ts:Io(re,he,l)}));if(!r||r.length===0)return J;const Z=[...r].sort((re,he)=>re.timestamp-he.timestamp).map((re,he)=>({type:"action",data:re,index:he,ts:re.timestamp})),q=[];let xe=0;for(const re of J){for(;xe<Z.length&&re.ts>0&&Z[xe].ts<re.ts;)q.push(Z[xe++]);q.push(re)}for(;xe<Z.length;)q.push(Z[xe++]);return q},[s,r,l]),V=f>0||!!v,te=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:w?`↻ ${w}`:"↑ Load older messages";return e.jsx("div",{ref:g,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:y,className:"chat-container-content",children:[x&&e.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),V&&!x&&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&&f===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})}),F.length===0&&!V&&(p||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),F.map(J=>{if(J.type==="action"){const ie=J.data;return e.jsx(_o,{log:ie},`action-${J.index}`)}const Z=J.data,q=J.index,xe=ns(Z,q),re=Z.receivedAt||l[xe],he=`${d}-${xe}`,ve=D.has(he);return e.jsx(Ao,{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-${xe}`)}),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:k})]})})}),Lo=a.memo(Mo,(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),Po="modulepreload",Ro=function(t){return"/"+t},mn={},Eo=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=Ro(l),l in mn)return;mn[l]=!0;const p=l.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const x=document.createElement("link");if(x.rel=p?"stylesheet":Po,p||(x.as="script"),x.crossOrigin="",x.href=l,d&&x.setAttribute("nonce",d),document.head.appendChild(x),p)return new Promise((v,f)=>{x.addEventListener("load",v),x.addEventListener("error",()=>f(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 ga=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),u=a.useRef(!1),x=a.useRef(!1),v=()=>{const f=o.current;if(f){p.current&&(f.clear(),p.current=!1);for(const w of l.current)f.write(w);l.current=[],u.current&&(f.fit(),u.current=!1),x.current&&(f.bumpResize(),x.current=!1)}};return a.useImperativeHandle(i,()=>({write:f=>{o.current?o.current.write(f):l.current.push(f)},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:(f,w)=>{o.current&&typeof o.current.resize=="function"&&o.current.resize(f,w)},fit:()=>{o.current?o.current.fit():u.current=!0},bumpResize:()=>{o.current?o.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const f=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(f)},[c]),a.useEffect(()=>{let f=!1;return Eo(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(w=>{pn||(pn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),f||d(()=>w.GhosttyTerminalView)}).catch(w=>{console.error("[CliTerminal] failed to load terminal renderer",w)}),()=>{f=!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"}})});ga.displayName="CliTerminal";function Ls({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 fn({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 y;if(!t||!r.current)return null;const n=r.current,i=n.getBoundingClientRect(),o=(y=s.current)==null?void 0:y.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 u,x,v,f;l>p?(u=i.width,x=i.width/l,v=0,f=(i.height-x)/2):(x=i.height,u=i.height*l,v=(i.width-u)/2,f=0);const w=i.left-o.left+v+u*t.nx,m=i.top-o.top+f+x*t.ny,C=Math.max(8,Math.min(o.width-8,w)),g=Math.max(8,Math.min(o.height-8,m));return e.jsxs("div",{style:{position:"absolute",left:C-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 Do({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:i,setIsMenuOpen:o,imeText:c,setImeText:d,handleImeSubmit:l,isConnActive:p,zoom:u,isMobile:x,mobileFillZoom:v,onZoomOut:f,onZoomReset:w,onZoomIn:m,transportType:C,screenshotUsage:g,lastActionStatus:y}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:k=>k.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(k=>!k),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:k=>k.stopPropagation(),onChange:k=>d(k.target.value),onKeyDown:k=>{l(k)},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(k=>!k),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"})]}),u>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),C==="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"}),C==="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`}),y&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),i&&e.jsxs("div",{onTouchStart:k=>k.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: ",u<=(x?v:1)+.01?x?"FILL":"FIT":`${Math.round(u*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:k=>{k.stopPropagation(),f()},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:k=>{k.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:x?"FILL":"FIT"}),e.jsx("button",{onClick:k=>{k.stopPropagation(),m()},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 Bo({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 Ko(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function xn(t){return t==null||typeof t=="number"||typeof t=="boolean"?t:typeof t=="string"?t.length>64?`${t.slice(0,61)}...`:t:Array.isArray(t)?`Array(${t.length})`:typeof t=="object"?"Object":typeof t}function Ts(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!Ko())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,xn(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,xn(s[c])]))}),r.current=s})}function Wo({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:i,minZoom:o,zoomRef:c,panXRef:d,panYRef:l,setPanX:p,setPanY:u,setZoom:x,lastWheelTimeRef:v,onAction:f,setLastActionStatus:w,spawnRippleFromNormalized:m,clampPan:C,isMobile:g,mobileFillZoom:y}){const[k,I]=a.useState(null),j=a.useRef(null),h=a.useRef(null),b=a.useRef(null),S=a.useRef(!1),N=a.useRef(null),E=a.useRef(0),D=a.useRef(null),O=a.useRef(1),T=a.useRef({x:0,y:0}),L=a.useRef(!1),_=a.useRef(n),R=a.useRef(f),B=30,Y=550,K=18,$=60,W=400,F=12,V=()=>{if(j.current)return;const J={nx:.5,ny:.5};j.current=J,I(J)};return a.useEffect(()=>{_.current=n,n==="mouse"&&V()},[n]),a.useEffect(()=>{R.current=f},[f]),a.useEffect(()=>{const J=t.current;if(!J)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))}},q=(ie,pe)=>{if(!r.current)return{dnx:0,dny:0};const oe=r.current,ge=oe.getBoundingClientRect(),X=oe.naturalWidth||ge.width,se=oe.naturalHeight||ge.height,Q=X/se,fe=ge.width/ge.height;let M,ee;return Q>fe?(M=ge.width,ee=ge.width/Q):(ee=ge.height,M=ge.height*Q),{dnx:ie/M,dny:pe/ee}},xe=(ie,pe,oe)=>{if(oe<=1.05)return;const ge=-(ie-.5)*100,X=-(pe-.5)*100,se=C(ge,X,oe);(Math.abs(se.x-d.current)>.1||Math.abs(se.y-l.current)>.1)&&(p(se.x),u(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()},b.current={x:oe.clientX,y:oe.clientY},L.current||(S.current=!1),N.current=setTimeout(()=>{if(!S.current&&!L.current)if(S.current=!0,_.current==="mouse"){const ge=j.current||{nx:.5,ny:.5};w("Right Click"),m(ge.nx,ge.ny,"right"),R.current("input_click",{...ge,button:"right"}).catch(()=>{})}else{const ge=Z(oe);ge&&(w("Right Click"),m(ge.nx,ge.ny,"right"),R.current("input_click",{...ge,button:"right"}).catch(()=>{}))}},500);return}if(ie.touches.length===2){N.current&&clearTimeout(N.current),S.current=!0,L.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,T.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&&b.current){const oe=ie.touches[0],ge=oe.clientX-b.current.x,X=oe.clientY-b.current.y;if(!S.current&&h.current){const se=oe.clientX-h.current.x,Q=oe.clientY-h.current.y;Math.sqrt(se*se+Q*Q)>8&&(S.current=!0,N.current&&clearTimeout(N.current))}if(S.current)if(_.current==="mouse"){const se=q(ge,X),Q=j.current||{nx:.5,ny:.5},fe=Math.max(0,Math.min(1,Q.nx+se.dnx)),M=Math.max(0,Math.min(1,Q.ny+se.dny));j.current={nx:fe,ny:M},I({nx:fe,ny:M}),w(`Cursor: ${Math.round(fe*100)}%, ${Math.round(M*100)}%`),xe(fe,M,c.current);const ee=Date.now();ee-v.current>=30&&(v.current=ee,R.current("input_mouseMoved",{nx:fe,ny:M}).catch(()=>{}))}else if(c.current>1){const se=s.current;if(se){const Q=se.clientWidth,fe=se.clientHeight,M=d.current+ge/Q*100,ee=l.current+X/fe*100,ye=C(M,ee,c.current);p(ye.x),u(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"),R.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-ge*2.5),deltaY:Math.round(-X*2.5)}).catch(()=>{}))}}b.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,fe=(ie.touches[0].clientY+ie.touches[1].clientY)/2,M=Q-T.current.x,ee=fe-T.current.y,ye=Math.abs(se-1)>.03;if(_.current==="mouse"){if(ye){const A=Math.max(o,Math.min(5,O.current*se));x(A),c.current=A}else if(Math.abs(M)>2||Math.abs(ee)>2){const A=j.current||{nx:.5,ny:.5},G=Date.now();G-v.current>=30&&(v.current=G,w("Scroll"),R.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));x(A),c.current=A;const G=s.current;if(G&&A>1){const z=G.clientWidth,ae=G.clientHeight,de=d.current+M/z*100,Ce=l.current+ee/ae*100,Ee=C(de,Ce,A);p(Ee.x),u(Ee.y),d.current=Ee.x,l.current=Ee.y}}T.current={x:Q,y:fe}}},ve=ie=>{var pe;if(N.current&&clearTimeout(N.current),D.current=null,ie.touches.length===1&&L.current){const oe=ie.touches[0];h.current={x:oe.clientX,y:oe.clientY,time:Date.now()},b.current={x:oe.clientX,y:oe.clientY},S.current=!0;return}if(ie.touches.length===0){if(L.current){L.current=!1,S.current=!1;return}if(ie.changedTouches.length===1){const oe=ie.changedTouches[0],ge=Date.now(),X=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,fe=Math.sqrt(se*se+Q*Q);if(_.current==="mouse"){if(X<B||X>Y||fe>K){S.current=!1;return}const M=j.current||Z(oe);M&&(w(`Click: ${Math.round(M.nx*100)}%, ${Math.round(M.ny*100)}%`),m(M.nx,M.ny,"left"),R.current("input_click",{...M}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(X<$||X>W||fe>F){S.current=!1;return}const M=Z(oe);if(!M)return;ge-E.current<300?(w("Double tap"),m(M.nx,M.ny,"double"),R.current("input_click",{...M,clickCount:2}).catch(()=>{}),E.current=0):(w(`Tap: ${Math.round(M.nx*100)}%, ${Math.round(M.ny*100)}%`),m(M.nx,M.ny,"left"),R.current("input_click",{...M}).catch(()=>{}),E.current=ge)}}S.current=!1}};return J.addEventListener("touchstart",re,{passive:!1}),J.addEventListener("touchmove",he,{passive:!1}),J.addEventListener("touchend",ve,{passive:!1}),()=>{J.removeEventListener("touchstart",re),J.removeEventListener("touchmove",he),J.removeEventListener("touchend",ve),N.current&&clearTimeout(N.current)}},[t,s,r,o,c,d,l,p,u,x,v,w,m,C]),{cursorPos:k,cursorPosRef:j,handleToggleInputMode:()=>{i(J=>{const Z=J==="touch"?"mouse":"touch";return Z==="mouse"&&V(),Z})},handleZoomReset:()=>{const J=g?y:1;x(J),c.current=J,p(0),u(0),d.current=0,l.current=0}}}function ya({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,u]=a.useState(null),[x,v]=a.useState(""),[,f]=a.useState(!1),[w,m]=a.useState([]),C=a.useRef(0),[g,y]=a.useState(!1),[k,I]=a.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[h,b]=a.useState(j?"mouse":"touch"),[S,N]=a.useState(1),E=a.useRef(!1),[D,O]=a.useState(1),[T,L]=a.useState(0),[_,R]=a.useState(0);Ts("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:h,zoom:D,panX:T,panY:_,isMenuOpen:g,isImeOpen:k});const B=a.useRef(0),Y=a.useRef(D),K=a.useRef(T),$=a.useRef(_);a.useEffect(()=>{Y.current=D},[D]),a.useEffect(()=>{K.current=T},[T]),a.useEffect(()=>{$.current=_},[_]),a.useEffect(()=>{var X;(X=c.current)==null||X.focus()},[]);const W=r==="connected",F=n,V=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(!j||E.current||!F)return;const X=l.current,se=d.current;if(!X||!se)return;const Q=()=>{const fe=se.clientWidth,M=se.clientHeight,ee=X.naturalWidth,ye=X.naturalHeight;if(!ee||!ye||!fe||!M)return;const A=Math.min(fe/ee,M/ye),z=Math.max(fe/ee,M/ye)/A;z>1.01&&(N(z),O(z),Y.current=z),E.current=!0};X.complete&&X.naturalWidth?Q():X.addEventListener("load",Q,{once:!0})},[F,j]);const ke=.5;a.useEffect(()=>{D<=ke&&(L(0),R(0))},[D,ke]);const J=(X,se,Q)=>{if(Q<=ke)return{x:0,y:0};const fe=(Q-1)/(2*Q)*100,M=(Q-1)/(2*Q)*100;return{x:Math.max(-fe,Math.min(fe,X)),y:Math.max(-M,Math.min(M,se))}},Z=(X,se)=>{if(!l.current)return null;const Q=l.current.getBoundingClientRect();return!Q.width||!Q.height?null:{nx:Math.max(0,Math.min(1,(X-Q.left)/Q.width)),ny:Math.max(0,Math.min(1,(se-Q.top)/Q.height))}},q=(X,se,Q)=>{const fe=d.current;if(!fe)return;const M=fe.getBoundingClientRect(),ee=++C.current;m(ye=>[...ye,{id:ee,x:X-M.left,y:se-M.top,type:Q}]),setTimeout(()=>m(ye=>ye.filter(A=>A.id!==ee)),600)},xe=(X,se,Q)=>{const fe=l.current,M=d.current;if(!fe||!M)return;const ee=fe.getBoundingClientRect(),ye=M.getBoundingClientRect(),A=fe.naturalWidth||ee.width,G=fe.naturalHeight||ee.height,z=A/G,ae=ee.width/ee.height;let de,Ce,Ee,Le;z>ae?(de=ee.width,Ce=ee.width/z,Ee=0,Le=(ee.height-Ce)/2):(Ce=ee.height,de=ee.height*z,Ee=(ee.width-de)/2,Le=0);const ze=ee.left-ye.left+Ee+de*X,lt=ee.top-ye.top+Le+Ce*se,Xe=++C.current;m(We=>[...We,{id:Xe,x:ze,y:lt,type:Q}]),setTimeout(()=>m(We=>We.filter(at=>at.id!==Xe)),600)},re=async X=>{var Q;const se=Z(X.clientX,X.clientY);if(se){u(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),q(X.clientX,X.clientY,"left"),(Q=c.current)==null||Q.focus();try{const fe=await t("input_click",{nx:se.nx,ny:se.ny});fe!=null&&fe.success||s(`❌ Click failed: ${fe==null?void 0:fe.error}`)}catch(fe){s(`❌ Click error: ${fe.message||fe}`)}}},he=async(X,se,Q,fe=0)=>{try{await t("input_key",{type:Q?"char":"keyDown",key:X,code:se,text:Q?X:void 0,unmodifiedText:Q?X:void 0,modifiers:fe})}catch(M){s(`❌ Key error: ${M.message||M}`)}},ve=async X=>{if(X.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(X.key)&&X.preventDefault();let Q=0;X.altKey&&(Q|=1),X.ctrlKey&&(Q|=2),X.metaKey&&(Q|=4),X.shiftKey&&(Q|=8),u(`Key: ${X.key}`),await he(X.key,X.code,X.key.length===1,Q)},ie=async X=>{if(X.key==="Enter"){if(X.nativeEvent.isComposing)return;if(x){const se=x;v(""),u(`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 u("Key: Enter"),await he("Enter","Enter",!1)}};a.useEffect(()=>{const X=c.current;if(!X)return;const se=Q=>{var fe;if((fe=l.current)!=null&&fe.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;u(`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 X.addEventListener("wheel",se,{passive:!1}),()=>X.removeEventListener("wheel",se)},[t]);const{cursorPos:pe,handleToggleInputMode:oe,handleZoomReset:ge}=Wo({containerRef:c,viewportRef:d,imgRef:l,inputMode:h,setInputMode:b,minZoom:ke,zoomRef:Y,panXRef:K,panYRef:$,setPanX:L,setPanY:R,setZoom:O,lastWheelTimeRef:B,onAction:t,setLastActionStatus:u,spawnRippleFromNormalized:xe,clampPan:J,isMobile:j,mobileFillZoom:S});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ve,onContextMenu:X=>X.preventDefault(),onFocus:()=>f(!0),onBlur:()=>f(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?e.jsx("img",{ref:l,src:F,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:X=>X.preventDefault(),onDragStart:X=>X.preventDefault()}):e.jsx(Bo,{waitingLabel:V,waitingHint:te,transportType:o}),h==="mouse"&&F&&e.jsx($o,{cursorPos:pe,viewportRef:d,imgRef:l}),w.map(X=>{const Q={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[X.type];return e.jsxs("div",{style:{position:"absolute",left:X.x,top:X.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}})]},X.id)})]}),e.jsx(Do,{inputMode:h,onToggleInputMode:oe,isImeOpen:k,setIsImeOpen:I,isMenuOpen:g,setIsMenuOpen:y,imeText:x,setImeText:v,handleImeSubmit:ie,isConnActive:W,zoom:D,isMobile:j,mobileFillZoom:S,onZoomOut:()=>O(X=>Math.max(.5,X-.25)),onZoomReset:ge,onZoomIn:()=>O(X=>Math.min(5,X+.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 va(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 wa=t=>va(t);function Oo(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ms(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",i=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:i}}function _s(t){const s=new Map,r=(n,i)=>{n&&s.set(n,{sessionId:n,...Oo(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 ks(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 Ns(t,s,r){const n=ks(t,s),i=ms(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,u=n.inboxBucket==="working"||d,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:p,isWorking:u,isReconnecting:o,isConnecting:c,isGenerating:d,isWaiting:l,inboxBucket:p?"needs_attention":u?"working":x?"task_complete":"idle"}}function zo(t,s,r){return Ns(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Uo(t,s,r){return ks(t,r||new Map).surfaceHidden}function ja({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ms(t).isWaiting||!t.modalButtons)return null;const 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(qt,{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(),u=/^(run|approve|accept|yes|allow|always)/.test(p),x=/^(reject|deny|delete|remove|abort)/.test(p),v=r===d,f=r!==null;return e.jsx("button",{onClick:()=>o(d),disabled:f,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"bg-white font-extrabold":x?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${f&&!v?"opacity-40":"opacity-100"} ${f?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)"}:void 0,children:v?"⏳ ...":c(d)},l)})})]})]})}const hn=new Map,Ho={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",antigravity:"#f97316",windsurf:"#34d399"};function Fo({ideId:t,sessionId:s,ideType:r,providerType:n,displayLabel:i,controls:o,controlValues:c,serverModel:d,serverMode:l}){const{sendCommand:p}=Rt(),u=`${t}:${s||n}`,x=Ho[n]||"#94a3b8",[v,f]=a.useState({}),w=a.useRef(0),m={...d?{model:d}:{},...l?{mode:l}:{},...c||{},...Date.now()<w.current?v:{}};a.useEffect(()=>{c&&Date.now()>w.current&&f({})},[c]);const[C,g]=a.useState(hn.get(u)||{}),[y,k]=a.useState(null),[I,j]=a.useState(null),h=a.useCallback(async(L,_={})=>{const R={..._,...s&&{targetSessionId:s}};return await p(t,L,R)},[t,s,p]),b=a.useCallback(async(L,_={},R)=>{try{const B=await h("invoke_provider_script",{agentType:n,ideType:r,scriptName:L,..._});return(B==null?void 0:B.success)===!1&&R?await h(R,{agentType:n,ideType:r,..._}):B}catch(B){if(!R)throw B;return await h(R,{agentType:n,ideType:r,..._})}},[h,n,r]);if(!o||o.length===0)return null;const S=o.filter(L=>L.placement==="bar").sort((L,_)=>(L.order??50)-(_.order??50));if(S.length===0)return null;const N=async L=>{var R,B,Y;if(y===L.id){k(null);return}if((((R=L.options)==null?void 0:R.map(K=>K.value))||C[L.id]||[]).length>0){k(L.id);return}if(L.dynamic&&L.listScript){j(L.id);try{const K=Ps(L.listScript),$=await b(L.listScript,{},K),F=(($==null?void 0:$.models)||($==null?void 0:$.modes)||((B=$==null?void 0:$.result)==null?void 0:B.models)||((Y=$==null?void 0:$.result)==null?void 0:Y.modes)||($==null?void 0:$.options)||[]).map(V=>typeof V=="string"?V:(V==null?void 0:V.name)||(V==null?void 0:V.id)||(V==null?void 0:V.value)||String(V));g(V=>{const te={...V,[L.id]:F};return hn.set(u,te),te}),k(L.id)}catch{}finally{j(null)}}},E=async(L,_)=>{k(null),f(R=>({...R,[L.id]:_})),w.current=Date.now()+5e3;try{if(!L.setScript)return;await b(L.setScript,{model:L.id==="model"?_:void 0,mode:L.id==="mode"?_:void 0,value:_},Ps(L.setScript))}catch{}},D=async L=>{var $;const _=(($=L.options)==null?void 0:$.map(W=>W.value))||C[L.id]||[];if(_.length===0)return;const R=String(m[L.id]||""),Y=(_.indexOf(R)+1)%_.length,K=_[Y];if(typeof K=="string"){f(W=>({...W,[L.id]:K})),w.current=Date.now()+5e3;try{if(!L.setScript)return;await b(L.setScript,{value:K},Ps(L.setScript))}catch{}}},O=async L=>{const R=!m[L.id];f(B=>({...B,[L.id]:R})),w.current=Date.now()+5e3;try{if(!L.setScript)return;await b(L.setScript,{value:R},Ps(L.setScript))}catch{}},T=async L=>{if(L.invokeScript)try{await b(L.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:x},children:i}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),S.map(L=>{var K;const _=String(m[L.id]||""),R=y===L.id,B=I===L.id,Y=((K=L.options)==null?void 0:K.map($=>$.value))||C[L.id]||[];switch(L.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:R?`${x}55`:"transparent",border:"1px solid",color:_?"var(--text-primary)":"var(--text-muted)"},onClick:()=>N(L),children:[L.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:L.icon}),B?"...":_||L.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),R&&Y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>k(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:L.label.toUpperCase()}),Y.map($=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:$===_?`${x}18`:"transparent",color:$===_?x:"var(--text-secondary)",fontWeight:$===_?600:400,borderLeft:$===_?`2px solid ${x}`:"2px solid transparent"},onMouseEnter:W=>{W.currentTarget.style.background=`${x}12`},onMouseLeave:W=>{W.currentTarget.style.background=$===_?`${x}18`:"transparent"},onClick:()=>E(L,$),children:$},$))]})]})]},L.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:_?"var(--text-primary)":"var(--text-muted)"},onClick:()=>D(L),title:`Click to cycle: ${Y.join(" → ")}`,children:[L.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:L.icon}),_||L.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},L.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:_?`${x}44`:"transparent",background:_?`${x}14`:"var(--surface-tertiary)",color:_?x:"var(--text-muted)"},onClick:()=>O(L),children:[L.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:L.icon}),L.label]},L.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:()=>T(L),children:[L.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:L.icon}),L.resultDisplay==="inline"&&_?`${L.label}: ${_}`:L.label]},L.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:_?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:L.icon}),_?`${L.label}: ${_}`:L.label]},L.id);default:return null}})]})}function Ps(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const Vo=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 u;o&&((u=c.current)==null||u.focus())},[s,o]);const p=()=>{const u=d.trim();!u||n||(l(""),i(u))};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:u=>l(u.target.value),onPaste:u=>{const x=u.clipboardData.getData("text");x&&l(v=>v+x),u.preventDefault()},onKeyDown:u=>{if(u.key==="Enter"){if(u.nativeEvent.isComposing){u.preventDefault();return}u.preventDefault(),p()}},onBlur:u=>{if(window.innerWidth<768){const x=u.relatedTarget;if((x==null?void 0:x.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),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 Go=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function qo(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function rt(t,s){if(qo(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Go.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 ka(t){return rt(t)==="generating"}function Oe(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Yo(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 er(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 Xo(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 Jo(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Zo(t){return Xo(t.trim().replace(/\.local$/i,""))}function Qo(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function Na(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&&!Jo(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 ot(t,s={}){return Qo(t)||Na(t,s)}function Ss(t){return t.transport==="pty"}function as(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 ec(t){return rt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function tc(t){if(!Array.isArray(t)||t.length<=1)return t;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of t){const i=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=s.get(i),c=rt(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 sc(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function rc(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&sc(s.receivedAt)||0}function nc(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Cr(t){return Math.max(nc(t),rc(t.activeChat))}function ac(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 Kr(t,s){return ac(Cr(t),Cr(s),ot(t,{fallbackId:t.id}),ot(s,{fallbackId:s.id}),t.id,s.id)}const Be=t=>t.transport==="pty",ls=(t,s)=>Be(t)?t.mode||"terminal":"chat",Sa=(t,s)=>Be(t)&&ls(t)==="terminal",De=t=>t.transport==="acp";function jt(t){return t.streamSource!=="agent-stream"}function Pt(t){var s;return t.daemonId||((s=t.ideId)==null?void 0:s.split(":")[0])||t.ideId||""}function Ca(t){return t.machineName||""}function Wr(t){return Pt(t)}function Xt(t){return jt(t)?t.ideType||t.agentType||"":t.agentType||t.ideType||""}function tr(t){return t.displayPrimary||t.agentName||"Agent"}function Or(t){return[t.displaySecondary,Ca(t)].filter(Boolean)}function As(t){return t.agentName||Oe(Xt(t))}function ic(t){var s,r;if(!jt(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 oc(t){return jt(t)?t.sessionId:t.nativeSessionId}function vn(t){return jt(t)?"native":t.tabKey}function cc(t){return t.sessionId}function lc(t,s){if(s)return jt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function dc(t,s){const r=Xt(t),n=jt(t)?s!=null&&s.type?Oe(s.type):Oe(t.ideType||""):As(t);return{isNativeConversation:jt(t),isCli:Be(t),isAcp:De(t),isCliTerminal:Sa(t),providerType:r,displayLabel:n,targetEntry:lc(t,s)}}function Ia({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:i=!0}){const o=ds(),c=Pt(t),d=Ca(t),l=t.transport==="cdp-page"||t.transport==="cdp-webview",p=t.streamSource==="agent-stream"&&!!t.agentName,u=!p&&(t.transport==="pty"||t.transport==="acp"),x=As(t),v=ic(t),f=a.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),w=a.useCallback(()=>{if(r){r();return}const m=oc(t);m&&o(`/dashboard?activeTab=${encodeURIComponent(m)}`)},[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:x,children:[e.jsx(js,{size:12}),e.jsx("span",{children:x})]}),u&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[e.jsx(js,{size:12}),e.jsx("span",{children:x})]}),d&&(i?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:d,children:[e.jsx(Lt,{size:12}),e.jsx("span",{children:d})]}):e.jsxs("span",{className:"conversation-meta-chip",title:d,children:[e.jsx(Lt,{size:12}),e.jsx("span",{children:d})]}))]})}function Jt(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function Ta(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=Yt(t.content),o=Yt(s.content);if(!i||i!==o)return!1;const c=Jt(t),d=Jt(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),Jt(t)&&(s+=1),s}function uc(t,s){const r=wn(t),n=wn(s);return n!==r?n>r?s:t:Yt(s.content).length>=Yt(t.content).length?s:t}function jn(t){const s=[];for(const r of t){const n=s.findIndex(i=>Ta(i,r));if(n>=0){s.splice(n,1,uc(s[n],r));continue}s.push(r)}return s}function kn(t){return[...t].sort((s,r)=>{const n=Jt(s),i=Jt(r);return n&&i&&n!==i?n-i:0})}function Nn(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${Yt(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=>Ta(o,n));return i>=0?(r.splice(i,1),!1):!0})}function mc(t,s){const r=new Set(s.map(n=>Nn(n)));return t.filter(n=>!r.has(Nn(n)))}function pc(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}const fc=60,xc=60;function Ir({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:i,isFocusingAgent:o,actionLogs:c,userName:d,showMetaChips:l=!1,scrollToBottomRequestNonce:p,isInputActive:u=!0}){const x=a.useRef(new Map),{sendCommand:v}=Rt();Ts("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const f=Ve.useMemo(()=>ms(t),[t.status,t.connectionState]),w=a.useRef(new Map),m=a.useCallback(B=>(w.current.has(B)||w.current.set(B,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:fc}),w.current.get(B)),[]),C=a.useCallback((B,Y)=>{const K=m(B);w.current.set(B,{...K,...Y}),g($=>$+1)},[m]),[,g]=a.useState(0),y=t.tabKey,k=m(y),I=k.messages,j=k.hasMore,h=k.error,b=Math.max(0,t.messages.length-k.visibleLiveCount),[S,N]=a.useState(!1),E=a.useCallback(async()=>{if(S)return;const B=t.tabKey,Y=m(B);if(t.messages.length>Y.visibleLiveCount){C(B,{visibleLiveCount:Math.min(t.messages.length,Y.visibleLiveCount+xc),error:null});return}N(!0),C(B,{error:null});try{const K=Wr(t);if(!K){C(B,{hasMore:!1});return}const $=Xt(t),W=await v(K,"chat_history",{agentType:$,offset:Y.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),F=pc(W),V=F.messages||[];if(V.length>0){const te=m(B);C(B,{messages:[...V,...te.messages],offset:te.offset+V.length,hasMore:!!F.hasMore})}else C(B,{hasMore:!!F.hasMore})}catch(K){const $=(K==null?void 0:K.message)||"";$.includes("P2P not available")||$.includes("channel not open")||$.includes("P2P not connected")||$.includes("timeout")?C(B,{error:"Connection not ready — tap to retry"}):C(B,{hasMore:!1,error:"Failed to load history"})}finally{N(!1)}},[S,s,t,v,m,C]),{allMessages:D,receivedAtMap:O}=a.useMemo(()=>{const B=b>0?t.messages.slice(-k.visibleLiveCount):t.messages;if(I.length===0){const W=kn(jn(B)),F={};return W.forEach((V,te)=>{const ke=`${t.tabKey}:${ns(V,te)}`;let J=Jt(V)||x.current.get(ke)||0;J||(J=Date.now(),x.current.set(ke,J)),F[ns(V,te)]=J}),{allMessages:W,receivedAtMap:F}}const Y=mc(I,B),K=kn(jn([...Y,...B])),$={};return K.forEach((W,F)=>{const V=`${t.tabKey}:${ns(W,F)}`;let te=Jt(W)||x.current.get(V)||0;te||(te=Date.now(),x.current.set(V,te)),$[ns(W,F)]=te}),{allMessages:K,receivedAtMap:$}},[t.messages,t.tabKey,b,I,k.visibleLiveCount]),T=a.useMemo(()=>c.filter(B=>B.ideId===t.tabKey).sort((B,Y)=>B.timestamp-Y.timestamp),[c,t.tabKey]),L=tr(t),_=a.useMemo(()=>dc(t,s),[t,s]),R=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((f.isGenerating||t.status==="streaming")&&N(!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(js,{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(cs,{size:14})," Open ",L," 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(fa,{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(cs,{size:14})," Open ",L," 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"&&!S)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,S,L,f.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[l&&e.jsx(Ia,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(Lo,{messages:D,actionLogs:T,agentName:As(t)||L||"Agent",userName:d,isCliMode:_.isCli||_.isAcp,isWorking:f.isGenerating,contextKey:t.tabKey,receivedAtMap:O,onLoadMore:E,isLoadingMore:S,hasMoreHistory:j,hiddenLiveCount:b,loadError:h??void 0,emptyState:R,scrollToBottomRequestNonce:p}),u&&!_.isCliTerminal&&(()=>{var B,Y,K,$,W,F;return e.jsx(Fo,{ideId:t.ideId,sessionId:t.sessionId,ideType:t.ideType,providerType:_.providerType,displayLabel:_.displayLabel,controls:(B=_.targetEntry)==null?void 0:B.providerControls,controlValues:(Y=_.targetEntry)==null?void 0:Y.controlValues,serverModel:((K=_.targetEntry)==null?void 0:K.currentModel)||void 0,serverMode:(($=_.targetEntry)==null?void 0:$.currentPlan)||void 0,acpConfigOptions:_.isAcp?(W=_.targetEntry)==null?void 0:W.acpConfigOptions:void 0,acpModes:_.isAcp?(F=_.targetEntry)==null?void 0:F.acpModes:void 0})})(),!_.isCliTerminal&&e.jsx(Vo,{contextKey:t.tabKey,panelLabel:L,isSending:n,onSend:r,isActive:u})]})}let _a=Gt;function Aa(){return _a()}class hc{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 Ma=new hc;class bc{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 He=new bc;function gc(t){t.dashboardWS&&(Ma=t.dashboardWS),t.connectionManager&&(He=t.connectionManager),t.useDaemonsHook&&(_a=t.useDaemonsHook)}function Fe(t){return tr(t)}function Zt(t){return Or(t).join(" · ")}function La(t){const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=Yt(s==null?void 0:s.content);return r||(t.title?t.title:Zt(t)||"No messages yet")}function Pa(t,s){const{isReconnecting:r,isConnecting:n}=ms(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function yc(t,s){const r=["Chat",...Or(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function is(t){return Pa(t)||Zt(t)}function vc(t){return`${Fe(t)} · ${La(t)}`}function wc(t){return`${Fe(t)} — ${Oe(t.ideType)}`}function jc(t){return As(t)||"CLI"}function Ra(t){return t.title||As(t)||t.ideId}function kc(t){return t?`Remote · ${Fe(t)||t.workspaceName||"Session"}`:"Remote"}function Nc({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}=Rt(),[u,x]=a.useState(""),[v,f]=a.useState(!1),[w,m]=a.useState(1),C=a.useRef(!1),g=a.useRef(0),y=a.useRef(!1),k=a.useRef(""),I=a.useRef(null),j=a.useRef(!1),h=a.useRef(null),b=t.tabKey,S=t.sessionId||"",N=t.daemonId||(($=t.ideId)==null?void 0:$.split(":")[0])||t.ideId||"",E=c.find(W=>W.id===N&&W.daemonMode),D=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",O=.6,T=1.15,L=()=>{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},_=()=>{var W,F;g.current=0,y.current=!1,k.current="",I.current=null,j.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f(!1),(F=(W=r.current)==null?void 0:W.reset)==null||F.call(W)},R=()=>{var W,F;g.current=0,y.current=!1,k.current="",I.current=null,j.current=!1,h.current!==null&&(cancelAnimationFrame(h.current),h.current=null),f(!0),(F=(W=r.current)==null?void 0:W.reset)==null||F.call(W)},B=()=>{var F;if(h.current=null,!o)return;const W=k.current;W&&(k.current="",(F=r.current)==null||F.write(W))},Y=W=>{W&&(k.current+=W,o&&h.current===null&&(h.current=requestAnimationFrame(B)))},K=(W,F=0,V,te)=>{var ke,J,Z,q,xe;F>0&&g.current>=F||F===0&&y.current||(g.current=F,f(!0),typeof V=="number"&&typeof te=="number"&&V>0&&te>0&&((J=(ke=r.current)==null?void 0:ke.resize)==null||J.call(ke,V,te)),(q=(Z=r.current)==null?void 0:Z.reset)==null||q.call(Z),W&&((xe=r.current)==null||xe.write(W)))};return a.useEffect(()=>{_()},[S]),a.useEffect(()=>{var F;if(!S)return;const W=((F=He.onRuntimeEvent)==null?void 0:F.call(He,S,V=>{if(!(!V||V.sessionId!==S)){if(V.type==="runtime_snapshot"){if(!o){I.current={text:V.text||"",seq:V.seq||0,cols:V.cols,rows:V.rows};return}K(V.text||"",V.seq||0,V.cols,V.rows);return}if(V.type==="session_output"){y.current=!0,typeof V.seq=="number"&&(g.current=Math.max(g.current,V.seq)),v||f(!0),typeof V.data=="string"&&Y(V.data);return}if(V.type==="session_cleared"){if(!o){j.current=!0,k.current="",I.current=null;return}R()}}}))||(()=>{});return()=>{W()}},[N,S,r,o,v]),a.useEffect(()=>{var F,V,te;if(!S)return;N&&((F=He.getState)==null?void 0:F.call(He,N))==="connected"&&(f(!0),(V=He.requestRuntimeSnapshot)==null||V.call(He,N,S).catch(()=>{}));const W=(te=He.onStateChange)==null?void 0:te.call(He,(ke,J)=>{var Z;ke!==N||J!=="connected"||(f(!0),(Z=He.requestRuntimeSnapshot)==null||Z.call(He,N,S).catch(()=>{}))});return()=>{W==null||W()}},[N,S,r]),a.useEffect(()=>{s&&_()},[s,b,r]),a.useEffect(()=>{x("")},[t.tabKey]),a.useEffect(()=>{const W=()=>{C.current||m(L())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),a.useEffect(()=>{var F;if(!o){(F=d.current)==null||F.blur();return}j.current&&(j.current=!1,R());const W=I.current;W&&(I.current=null,K(W.text,W.seq,W.cols,W.rows)),k.current&&h.current===null&&(h.current=requestAnimationFrame(B)),requestAnimationFrame(()=>{var V;(V=r.current)==null||V.bumpResize()})},[o]),a.useEffect(()=>()=>{h.current!==null&&(cancelAnimationFrame(h.current),h.current=null)},[]),a.useEffect(()=>{const W=F=>{var te;const V=F.detail;V!=null&&V.sessionId&&V.sessionId!==S||v&&((te=r.current)==null||te.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[v,S,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:()=>{C.current=!0,m(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:()=>{C.current=!0,m(W=>Math.min(T,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(ga,{ref:r,readOnly:!v||!o,sizingMode:D,onInput:W=>{v&&(p!=null&&p(N,{type:"pty_input",targetSessionId:S,data:W})||l(N,"pty_input",{targetSessionId:S,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 ${Fe(t)}...`,value:u,disabled:!v||!o||i,onChange:W=>x(W.target.value),onPaste:W=>{const F=W.clipboardData.getData("text");F&&x(V=>V+F),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const F=u.trim();!v||!F||i||(x(""),n(F))},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=u.trim();!v||!W||i||(x(""),n(W))},disabled:!v||!o||!u.trim()||i,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!i?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.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:u.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function Sc({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 Cc({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(Zs,{size:n}):e.jsx(At,{size:n})})}function Cn({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const i=Or(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:tr(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 Ic({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:i,onOpenHistory:o,onOpenRemote:c,onStopCli:d,activeCliViewMode:l,onSetCliViewMode:p,onOpenConversation:u,onHideConversation:x,hiddenConversations:v=[],onShowConversation:f,onShowAllHidden:w,inboxOpen:m,onInboxOpenChange:C,hiddenOpen:g,onHiddenOpenChange:y,onOpenNewSession:k}){const{ides:I,p2pStates:j={}}=Gt(),h=!!t&&Be(t)&&!De(t),b=!!t&&De(t),S=l||(t?Sa(t)?"terminal":"chat":null),[N,E]=a.useState(!1),D=a.useRef(null),O=a.useRef(null),T=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",L=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",_=I.filter(q=>q.type==="adhdev-daemon"),R=a.useMemo(()=>_s(I),[I]),B=Object.values(j),Y=B.filter(q=>q==="connected").length,K=B.filter(q=>q==="connecting"||q==="new"||q==="checking").length,W=r!=="connected"||_.length===0?null:K>0&&Y===0?"P2P connecting...":Y>0&&s===0?"Waiting for IDE...":null,F=a.useMemo(()=>i.filter(q=>!Uo(q,i,R)),[i,R]),V=a.useMemo(()=>F.filter(q=>Ns(q,R).requiresAction),[F,R]),te=a.useMemo(()=>F.filter(q=>{const xe=(t==null?void 0:t.tabKey)===q.tabKey;return Ns(q,R,{hideOpenTaskCompleteUnread:!0,isOpenConversation:xe}).unread}),[t,F,R]),ke=a.useMemo(()=>[...V,...te].slice(0,9),[V,te]),J=V.length+te.length;a.useEffect(()=>{if(!m)return;const q=xe=>{var re;(re=D.current)!=null&&re.contains(xe.target)||C(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[m,C]),a.useEffect(()=>{if(!g)return;const q=xe=>{var re;(re=O.current)!=null&&re.contains(xe.target)||y(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[g,y]),a.useEffect(()=>{if(!g&&!m)return;const q=xe=>{if(!xe.altKey)return;const re=xe.code.match(/^Digit([1-9])$/);if(!re)return;const he=Number(re[1])-1,ve=g?v[he]:void 0,ie=m?ke[he]:void 0,pe=ve||ie;if(pe){if(xe.preventDefault(),xe.stopPropagation(),ve){f==null||f(ve),y(!1);return}u==null||u(pe),C(!1)}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[v,g,m,ke,y,C,u,f]);const Z=q=>{if(!q)return;const xe=i.find(re=>re.tabKey===q);xe&&(x==null||x(xe))};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(At,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Fe(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:T,boxShadow:L}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:T,boxShadow:L}}),W&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",W]}),k&&e.jsx("button",{type:"button",onClick:k,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(ho,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(h||b||!De(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:Zt(t)||Fe(t),children:Fe(t)}),(h||b)&&d&&e.jsxs(e.Fragment,{children:[h&&p&&S&&e.jsx(zr,{mode:S,onChange:p,compact:!0}),e.jsx("button",{onClick:()=>d(t),className:"btn btn-secondary btn-sm",title:b?"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(ft,{size:14})})]}),!De(t)&&e.jsx("button",{onClick:()=>o(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx($r,{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${N?" is-drop-target":""}`,ref:O,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),E(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",E(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||E(!1)},onDrop:q=>{const xe=q.dataTransfer.getData("text/tab-key");q.preventDefault(),E(!1),Z(xe)},children:[e.jsxs("button",{type:"button",onClick:()=>y(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx(po,{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(),y(!1)},children:"Restore all"})]}),t&&x&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>x(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:Fe(t)})]}),v.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:v.map(q=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(q),y(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Fe(q)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[v.indexOf(q)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",v.indexOf(q)+1]}):null,Zt(q)]})]},q.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>C(!m),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(Qs,{size:16}),J>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:J})]}),m&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[V.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),V.map(q=>e.jsx(Cn,{conversation:q,isAttention:!0,shortcutIndex:ke.indexOf(q)>=0?ke.indexOf(q)+1:void 0,onClick:()=>{u==null||u(q),C(!1)}},q.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(q=>e.jsx(Cn,{conversation:q,shortcutIndex:ke.indexOf(q)>=0?ke.indexOf(q)+1:void 0,onClick:()=>{u==null||u(q),C(!1)}},q.tabKey))]}),J===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Tc(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 Ur({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:i=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:l,onSwitchSession:p,onRefreshHistory:u,onResumeSavedSession:x}){var g;const v=s.find(y=>y.id===t.ideId),f=(v==null?void 0:v.chats)||[],w=(g=v==null?void 0:v.activeChat)==null?void 0:g.id,m=Be(t)&&!De(t),C=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:m?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:wc(t)})]}),e.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:e.jsx(ft,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!m&&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"}),m?e.jsx(e.Fragment,{children:i.map(y=>{const k=t.providerSessionId===y.providerSessionId,I=k||!y.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{I||!x||x(y)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${k?"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 ${k?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:y.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:y.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Tc(y.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:y.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:[y.workspace||"Workspace unknown",y.currentModel?` · ${y.currentModel}`:"",y.messageCount>0?` · ${y.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:k?"ACTIVE":y.canResume?c===y.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},y.id)})}):f.map(y=>e.jsxs("div",{onClick:()=>{p(t.ideId,y.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${w===y.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===y.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:y.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:[y.id.substring(0,12),"..."]}),w===y.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},y.id)),(m&&!o&&i.length===0||!m&&f.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(yo,{size:32})}),e.jsx("div",{className:"text-[13px]",children:m?"No saved sessions found yet.":"No recent chat sessions found."})]}),m&&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:u,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(us,{size:13})," ",m?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?C:ia.createPortal(C,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 Ea({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 leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:e.jsx(ft,{size:14})}),e.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[e.jsx("div",{className:"flex items-center gap-2 pr-8",children:e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background: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 _c=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function Ac(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Mc(t){return t.sessionId||t.instanceId||t.agentType}function dr(t,s){return t||s}function Tn(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 $a(t=[]){const s={};for(const r of t)(r.type==="adhdev-daemon"||r.daemonMode)&&(s[r.id]=ot(r,{fallbackId:r.id}));return s}function Da(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 Lc(t,s,Da(t,r))}function Lc(t,s,r={}){var v,f,w,m,C,g;const n=[],i=r.machineName,o=r.connectionState,c=Ac(t),d=Oe(t.type),l=Array.isArray(t.childSessions)?t.childSessions.map(y=>{var k,I;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,agentType:y.providerType,agentName:y.providerName,status:y.status,title:y.title,messages:((k=y.activeChat)==null?void 0:k.messages)||[],activeModal:((I=y.activeChat)==null?void 0:I.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],p=_c(t),u=t.activeChat||{title:""},x=u.title&&String(u.title).trim()?String(u.title).trim():"";if(p){const y=t.sessionId||t.instanceId,k=gn(t.type),I=(v=t.activeChat)==null?void 0:v.activeModal,j=I&&Array.isArray(I.buttons)&&I.buttons.length>0,h=rt((f=t.activeChat)==null?void 0:f.status,{activeModal:(w=t.activeChat)==null?void 0:w.activeModal})||rt((C=(m=t.agents)==null?void 0:m[0])==null?void 0:C.status)||"idle",b=t.activeChat||{title:"",messages:[]};let S=b.title&&String(b.title).trim()?String(b.title).trim():"";const N=(g=t.activeChat)==null?void 0:g.id,E=t.chats;if(N&&Array.isArray(E)&&E.length>0){const R=E.find(B=>B.id===N||B.id&&String(B.id)===String(N));R!=null&&R.title&&String(R.title).trim()&&(S=String(R.title).trim())}const D=(Be(t)||De(t),t.type),O=(Be(t)||De(t))&&yn(S,k,D)?"":S,T=b.messages||[],L=Tn(s,[t.id,y]),_=Sn(T,L);n.push({ideId:t.id,sessionId:y,providerSessionId:t.providerSessionId,nativeSessionId:y,transport:t.transport,daemonId:t.daemonId||void 0,mode:Be(t)?t.mode||"terminal":"chat",agentName:k,agentType:D,status:h,title:O,messages:[...T,..._],resume:t.resume,ideType:D,workspaceName:c,displayPrimary:c||O||(Be(t)?t.mode==="chat"?k:"Terminal":k),displaySecondary:d,cdpConnected:t.cdpConnected,modalButtons:j?I.buttons:void 0,modalMessage:j?I.message:void 0,streamSource:"native",tabKey:dr(y,t.id),machineName:i,connectionState:o})}if(p&&(Be(t)||De(t)))return n;for(const y of l){const k=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,I=ec(y),j=Mc(y),h=`${t.id}:${j}`,b=y.title&&String(y.title).trim()||"",S=yn(b,y.agentName,y.agentType)?"":b,N=y.messages||[],E=Tn(s,[h,y.sessionId,y.instanceId]),D=Sn(N,E);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||N.length>0||D.length>0||k||S||!["idle","panel_hidden","disconnected","not_monitored"].includes(I))&&n.push({ideId:t.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:y.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:I,title:S,messages:[...N,...D],ideType:y.agentType,workspaceName:c,displayPrimary:c||x||S||d,displaySecondary:`${d} · ${y.agentName}`,cdpConnected:t.cdpConnected,modalButtons:k?y.activeModal.buttons:void 0,modalMessage:k?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:dr(y.sessionId||y.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:dr(t.sessionId||t.instanceId,t.id),connectionState:o}),n}function Pc(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 Rc(t,s){const r=[],{daemonId:n,existingDaemon:i,timestamp:o}=s,c=o||t.timestamp||Date.now(),d=t.sessions||[],{topLevel:l,childrenByParent:p}=Pc(d),u=l.filter(f=>f.kind==="workspace"&&f.transport==="cdp-page"),x=l.filter(f=>f.kind==="agent"&&f.transport==="pty"),v=l.filter(f=>f.kind==="agent"&&f.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:u.some(f=>!!f.cdpConnected)});for(const f of u){const w=p.get(f.id)||[];r.push({id:`${n}:ide:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId,parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,ideType:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:f.id,workspace:f.workspace,terminals:0,childSessions:w,agents:w.map(m=>({id:m.id,name:m.providerName,type:m.providerType,status:m.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,currentModel:f.currentModel,currentPlan:f.currentPlan,currentAutoApprove:f.currentAutoApprove,lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,controlValues:f.controlValues,providerControls:f.providerControls,timestamp:c})}for(const f of x)r.push({id:`${n}:cli:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId,parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,ideType:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:f.id,cliName:f.providerName,mode:f.mode||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,resume:f.resume,runtimeKey:f.runtimeKey,runtimeDisplayName:f.runtimeDisplayName,runtimeWorkspaceLabel:f.runtimeWorkspaceLabel,runtimeWriteOwner:f.runtimeWriteOwner??null,runtimeAttachedClients:f.runtimeAttachedClients??[],lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,controlValues:f.controlValues,providerControls:f.providerControls,timestamp:c,_isCli:!0});for(const f of v)r.push({id:`${n}:acp:${f.id}`,sessionId:f.id,providerSessionId:f.providerSessionId,parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,ideType:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:f.id,cliName:f.providerName,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,runtimeKey:f.runtimeKey,runtimeDisplayName:f.runtimeDisplayName,runtimeWorkspaceLabel:f.runtimeWorkspaceLabel,runtimeWriteOwner:f.runtimeWriteOwner??null,runtimeAttachedClients:f.runtimeAttachedClients??[],currentModel:f.currentModel,currentPlan:f.currentPlan,lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,surfaceHidden:f.surfaceHidden,acpConfigOptions:f.acpConfigOptions,acpModes:f.acpModes,controlValues:f.controlValues,providerControls:f.providerControls,timestamp:c,_isAcp:!0});return r}function Ec(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=Ec(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ba=[{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:"🏄"}],Ka=[{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:"🧩"}],Wa=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"}],Dc=Ba,Bc=Ka,Kc=Wa,Oa="adhdev_notification_prefs",_n={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Wc(){try{const t=localStorage.getItem(Oa);if(t){const s=JSON.parse(t);return{..._n,...s}}}catch{}return{..._n}}function Oc(t){try{localStorage.setItem(Oa,JSON.stringify(t))}catch{}}let _t=Wc(),zs=[];function zc(){zs.forEach(t=>t())}function Uc(t){_t={..._t,...t},Oc(_t),zc()}function Hc(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return zs.push(r),()=>{zs=zs.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Uc(r)},[]);return[{..._t},s]}function zt(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 Fc={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Vc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function za(){return"Notification"in window&&Notification.permission==="granted"}let Kt=null;async function Gc(){if(Kt!==null)return Kt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Kt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Kt=!!await t.pushManager.getSubscription(),Kt):(Kt=!1,!1)}catch{return Kt=!1,!1}}function Us(t,s,r){if(za())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 qc(t,s={}){const r={...Fc,...s},n=a.useRef(new Map),i=a.useRef(0),o=a.useRef(null);a.useEffect(()=>{Gc().then(d=>{o.current=d})},[]);const c=a.useCallback((d,l,p)=>{const u=Date.now();u-i.current<r.throttleMs||(i.current=u,Us(d,l,p))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!za())&&zt("browser")&&o.current!==!0){if(document.hasFocus()){for(const l of t)n.current.set(l.id,rt(l.status,{activeModal:l.activeModal}));return}for(const l of t){const p=n.current.get(l.id),u=rt(l.status,{activeModal:l.activeModal}),x=l.name||l.id;if(r.onApproval&&zt("approval")&&u==="waiting_approval"&&p!=="waiting_approval"){const v=((d=l.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,v.slice(0,120),`approval-${l.id}`)}r.onComplete&&zt("completion")&&ka(p)&&u==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${l.id}`),r.onError&&u==="error"&&p!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${l.id}`),n.current.set(l.id,u)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Yc=/^(run|approve|accept|yes|allow|always)/,Xc=/^(run|approve|accept|yes|allow|always|proceed|save)/,Jc=/^(reject|deny|delete|remove|abort|cancel|no)/;function Fr(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Zc(t){const s=Fr(t).toLowerCase();return Yc.test(s)?"primary":Jc.test(s)?"danger":"default"}function Qc(t){return Xc.test(Fr(t).toLowerCase())?"approve":"reject"}function el(t){return t.map((s,r)=>({label:Fr(s),variant:Zc(s),action:Qc(s),button:s,buttonIndex:r}))}function tl(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 sl(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function rl(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 nl{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,f,w;if(!s.ideId&&s.instanceId){for(const m of this.ides)if(m.id.endsWith(`:ide:${s.instanceId}`)||m.id.endsWith(`:cli:${s.instanceId}`)){s.ideId=m.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 m=ot(l,{fallbackId:l.id});m&&(d=s.ideType==="adhdev-daemon"?m:`${m}/${d}`)}const p=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now();let u="",x="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")u=s.message||"",x=s.level||"info";else if(s.event==="provider:notification"){const m=(v=s.channels)!=null&&v.length?s.channels:["toast"],C=s.preferenceKey,g=zt("browser")&&(!C||C==="browser"||zt(C));m.includes("bubble")&&n&&s.content&&this.emitSystemMessage(n,{role:"system",timestamp:p,content:s.content,_localId:`sys_provider_notification_${s.effectId||p}`}),m.includes("browser")&&s.title&&s.message&&g&&!document.hasFocus()&&Us(s.title,s.message,`provider-${s.effectId||p}`),m.includes("toast")&&(u=s.message||s.title||"",x=s.level||"info")}else if(s.event==="agent:generating_completed"){const m=s.duration?` (${s.duration}s)`:"";u=`✅ ${d} agent task completed${m}`,x="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(u=`⚡ ${d} approval needed`,x="warning",n&&!((f=s.modalButtons)!=null&&f.length)&&this.emitSystemMessage(n,{role:"system",timestamp:p,content:tl(s.modalMessage,s.modalButtons),_localId:`sys_approval_${p}`}),(w=s.modalButtons)!=null&&w.length&&this.resolveActionFn){const m=this.resolveActionRouteTarget(s);if(!m)return;const C=s.agentType||s.ideType||"",g=s.ideType||"",y=this.resolveActionFn,k=el(s.modalButtons).map(h=>({label:h.label,variant:h.variant,onClick:()=>{y(m,"resolve_action",{action:h.action,button:h.button,buttonIndex:h.buttonIndex,agentType:C,ideType:g,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),I=sl(d,s.modalMessage,u),j=Date.now();this.emitToast({id:j,message:I,type:x,timestamp:j,targetKey:n||m,actions:k,duration:15e3}),u=""}}else if(s.event==="monitor:long_generating"){const m=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";u=`⚠️ ${d} agent is taking a long time${m}`,x="warning",zt("browser")&&!document.hasFocus()&&Us(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${m.replace(/[()]/g,"")}`,`long-${s.ideId||s.agentType}`)}else if(s.event==="team:view_request"){const m=s.requesterName||"A team member",C=s.requestId,g=s.orgId;if(u=`👁️ ${m} wants to view your session`,x="warning",C&&g&&this.viewRequestRespondFn){const y=Date.now(),k=rl(g,C,this.viewRequestRespondFn,(I,j)=>console.error(`[EventManager] ${I} view request failed:`,j));this.emitToast({id:y,message:u,type:x,timestamp:y,actions:k,duration:3e4}),u=""}zt("browser")&&!document.hasFocus()&&Us("👁️ View Request",`${m} wants to view your session`,`view-request-${C}`)}else s.event==="team:view_request_approved"?(u="✅ View request approved",x="success"):s.event==="team:view_request_rejected"&&(u=`❌ ${s.targetName||"Team member"} declined your view request`,x="warning");if(u){const m=Date.now();this.emitToast({id:m,message:u,type:x,timestamp:m,targetKey:n||s.ideId,duration:5e3})}}}const nt=new nl;function Qt(...t){return zi(Ui(t))}function al({icon:t,title:s,subtitle:r,badge:n,actions:i,className:o}){return e.jsxs("div",{className:Qt("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 Ua({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(al,{icon:t,title:s,subtitle:r,badge:n,actions:i}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:Qt("mx-auto flex w-full flex-col gap-4",o,c),children:d})})]})}function bt({title:t,icon:s,description:r,accentColor:n,className:i,children:o}){return e.jsxs("div",{className:Qt("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 Ha({icon:t,title:s,description:r,action:n,className:i}){return e.jsxs("div",{className:Qt("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 il={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"},ol={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function cl({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:Qt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",il[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:ol[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 ll={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"},dl={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ul({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:Qt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",ll[t],r),children:[e.jsx("span",{className:Qt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",dl[t])}),n]})}function ml(){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"system"}function Hs(t){return t==="system"?ml():t}function pl(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Hs(Tr()))}function Vr(){const[t,s]=a.useState(Tr),[r,n]=a.useState(()=>Hs(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(Hs(c));try{localStorage.setItem("theme",c)}catch{}},[]),o=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark";n(Hs(d));try{localStorage.setItem("theme",d)}catch{}return d})},[]);return{theme:r,preference:t,setPreference:i,cycleTheme:o,isDark:r==="dark"}}const An={dark:"Dark",light:"Light",system:"System"};function fl({collapsed:t}){const{preference:s,cycleTheme:r}=Vr(),n=s==="dark"?e.jsx(wo,{size:16}):s==="light"?e.jsx(vo,{size:16}):e.jsx(jo,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${An[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:An[s]})]})}function Ot({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 xl({onPrefChange:t}){const[s,r]=Hc(),n=(i,o)=>{r({[i]:o}),t==null||t(i,o)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{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(Ot,{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(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ko,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:i=>n("completionAlert",i)}),e.jsx(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(No,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:i=>n("approvalAlert",i)}),e.jsx(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(js,{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 hl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function ur(t,s){return t instanceof Error?t.message:s}function bl({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(Ha,{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(yl,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i},c.id))})}function Mn({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 ia.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 gl(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Dc,...Bc,...Kc].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 yl({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i}){var T,L;const[o,c]=a.useState("idle"),[d,l]=a.useState(""),[p,u]=a.useState(null),[x,v]=a.useState("idle"),[f,w]=a.useState(""),m=t.version||null,C=((T=t.machine)==null?void 0:T.platform)||((L=t.system)==null?void 0:L.platform)||"",g=ot(t,{fallbackId:t.id}),y=C==="win32"?"🪟":C==="darwin"?"🍎":"🐧",k=s.filter(_=>_.daemonId===t.id&&_.transport==="cdp-page"),I=s.filter(_=>_.daemonId===t.id&&_.transport==="pty"),j=s.filter(_=>_.daemonId===t.id&&_.transport==="acp"),h=t.p2p,b=async()=>{if(r){c("upgrading"),l("Starting upgrade...");try{const _=hl(await r(t.id,"daemon_upgrade",{}));_.alreadyLatest?(c("done"),l(`Already on v${_.version||"latest"}.`)):_.upgraded||_.success?(c("done"),l(`Upgrade to v${_.version||"latest"} started. Daemon is restarting...`)):(c("error"),l(_.error||"Upgrade failed"))}catch(_){c("error"),l(ur(_,"Connection lost during upgrade"))}}},S=async()=>{if(u(null),!!n){v("loading");try{await n(t.id),v("done"),w("Machine disconnected.")}catch(_){v("error"),w(ur(_,"Failed to disconnect"))}}},N=async()=>{if(u(null),!!i){v("loading");try{await i(t.id),v("done"),w('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(_){v("error"),w(ur(_,"Failed to revoke token"))}}},E="0.8.35",D=!m||m!==E,O=k.length+I.length+j.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:y}),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),"…"]}),m&&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",m,!D&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&D&&e.jsx("button",{onClick:b,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:()=>u("disconnect"),disabled:x==="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:()=>u("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(ul,{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:[k.map(_=>{const R=gl(_.type),B=_.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:R.icon}),e.jsx("span",{children:R.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..."})]},_.id)}),I.map(_=>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:_.cliName||"CLI"})]},_.id)),j.map(_=>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:_.cliName||"ACP"})]},_.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||f)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||x==="error"?"text-red-400":o==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:f||d})]}),p==="disconnect"&&e.jsx(Mn,{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:S,onCancel:()=>u(null)}),p==="revoke"&&e.jsx(Mn,{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:N,onCancel:()=>u(null)})]})}const vl=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function wl(){const{preference:t,setPreference:s}=Vr();return e.jsx("div",{className:"flex gap-2",children:vl.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 jl(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 kl(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function mr(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ln(t){const{r:s,g:r,b:n}=kl(t);return .2126*mr(s)+.7152*mr(r)+.0722*mr(n)}function Pn(t,s){const r=Ln(t),n=Ln(s),i=Math.max(r,n),o=Math.min(r,n);return(i+.05)/(o+.05)}function Fa(t){const s=jl(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return Pn(s,r)>=Pn(s,n)?r:n}const _r={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},Ar={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},Nl=[{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"}}}],Va="adhdev-chat-theme",Ga="adhdev-chat-theme-custom";function Fs(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Va)||"ember"}catch{return"ember"}}function gt(t){try{const s=localStorage.getItem(Ga);if(s){const r=JSON.parse(s);return{...t==="dark"?_r:Ar,...r[t]}}}catch{}return t==="dark"?_r:Ar}function Rs(t,s){try{localStorage.setItem(Ga,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 Ys(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 Sl={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=Sl[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",Ys(r,24)),n.style.setProperty("--accent-on-primary",Fa(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Ys(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 Ut(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",Ys(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Fa(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${Ys(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 Gr(){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 Cl(t){try{localStorage.setItem(Va,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Ht()?"dark":"light";Ut(gt(s))}else Gr(),vs(t,Ht()?"dark":"light")}function Il(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=Fs();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Ht()?"dark":"light";Ut(gt(s))}else Gr(),vs(t,Ht()?"dark":"light")}function Ht(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function st({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 hs({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 Tl({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,i]=a.useState(()=>gt(r));a.useEffect(()=>{i(gt(r))},[r]);const o=a.useCallback((c,d)=>{i(l=>{const p={...l,[c]:d},x=gt(r==="dark"?"light":"dark");return r==="dark"?Rs(p,x):Rs(x,p),Ut(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(hs,{title:"App Background",children:[e.jsx(st,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),e.jsx(st,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),e.jsx(st,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),e.jsxs(hs,{title:"App Text",children:[e.jsx(st,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),e.jsx(st,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),e.jsx(st,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),e.jsxs(hs,{title:"Borders & Accent",children:[e.jsx(st,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),e.jsx(st,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),e.jsx(st,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(hs,{title:"Chat Bubbles",children:[e.jsx(st,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),e.jsx(st,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),e.jsx(st,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),e.jsx(st,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),e.jsxs(hs,{title:"Chat Layout",children:[e.jsx(st,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),e.jsx(st,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),e.jsx(st,{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?_r:Ar,l=gt(t?"light":"dark");t?Rs(c,l):Rs(l,c),i(c),Ut(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 _l(){const[t,s]=a.useState(Fs),[r,n]=a.useState(!0),[i,o]=a.useState(()=>gt("dark"));a.useEffect(()=>{n(Ht());const l=new MutationObserver(()=>{const x=Ht();n(x);const v=Fs();v==="custom"?Ut(gt(x?"dark":"light")):vs(v,x?"dark":"light")});l.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=Ht();n(x);const v=Fs();v==="custom"?Ut(gt(x?"dark":"light")):vs(v,x?"dark":"light")};return p.addEventListener("change",u),()=>{l.disconnect(),p.removeEventListener("change",u)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ut(gt(r?"dark":"light")):(Gr(),vs(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{o(gt(r?"dark":"light"))},[r]);const c=l=>{s(l),Cl(l)},d=[...Nl,{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,u=r?l.preview.dark:l.preview.light,x=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:u.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:x},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),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(Tl,{dark:r,onColorsChange:l=>o(l)})]})}const qa="adhdev_mobileDashboardMode_v1";function Ya(){try{return localStorage.getItem(qa)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Al(t){try{localStorage.setItem(qa,t)}catch{}}function Ml(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(Ya()==="chat")},[]),e.jsx(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(At,{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),Al(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}const Xa="adhdev_hiddenTabs";function Ll(){try{const t=localStorage.getItem(Xa);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ss(t){try{localStorage.setItem(Xa,JSON.stringify([...t]))}catch{}}function Pl(){const[t,s]=a.useState(Ll),r=a.useCallback(p=>{s(u=>{const x=new Set(u);return x.has(p)?x.delete(p):x.add(p),ss(x),x})},[]),n=a.useCallback(p=>{s(u=>{if(u.has(p))return u;const x=new Set(u);return x.add(p),ss(x),x})},[]),i=a.useCallback(p=>{s(u=>{if(!u.has(p))return u;const x=new Set(u);return x.delete(p),ss(x),x})},[]),o=a.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return ss(u),u})},[]),c=a.useCallback((p,u)=>{s(x=>{const v=new Set(x);for(const f of u)v.add(f);return ss(v),v})},[]),d=a.useCallback((p,u)=>{s(x=>{const v=new Set(x);for(const f of u)v.delete(f);return ss(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 Rl({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Vc()},[]);const i=a.useMemo(()=>t.map(o=>({id:o.tabKey,name:Ra(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[t]);return qc(i),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const l=Date.now(),p={};for(const[u,x]of Object.entries(d))l-x<5e3&&(p[u]=x);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 El(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 Ft(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return El(s==null?void 0:s.receivedAt)||0}function Mr(t,s=0){return Ft(t)||s||0}function Ja(t){return Ft(t)}function Za(t,s,r=Ja){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=rt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function $l(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!Lr(t)&&!t.title.trim()}function Dl(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:Za(s,r)})[0]||null}function Mt(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=Dl(i);return n?o&&$l(n)?o:n:o||r[0]||null}function Bl(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 Kl(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 Wl(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 Ol(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 zl(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Ul(t){const s=zl(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=Yt(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Hl({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=Bl(t);return Es(o.current,h)?o.current:(o.current=h,h)},[t]),u=a.useMemo(()=>$a(t),[t]),x=a.useRef(new Map),v=a.useRef(new Map),f=a.useMemo(()=>{const h=new Map,b=[];for(const D of p){const{connectionState:O="new",machineName:T}=Da(D,{machineNames:u,connectionStates:s,defaultConnectionState:"new"}),L=Wl(D,r),_=x.current.get(D.id);if(_&&_.ide===D&&_.connectionState===O&&_.machineName===T&&Ol(_.localRefs,L)){h.set(D.id,_),b.push(..._.conversations);continue}const R=Hr(D,r,{machineNames:u,connectionStates:s,defaultConnectionState:"new"}),B={ide:D,connectionState:O,machineName:T,localRefs:L,conversations:R};h.set(D.id,B),b.push(...R)}x.current=h;const S=new Map,N=D=>{const O=Ul(D),T=v.current.get(D.tabKey);if(T&&T.signature===O)return S.set(D.tabKey,T),T.timestamp;const L={signature:O,timestamp:Ja(D)||(T==null?void 0:T.timestamp)||0};return S.set(D.tabKey,L),L.timestamp},E=[...b].sort((D,O)=>Za(D,O,N));return v.current=S,E},[p,r,s,u]),w=a.useMemo(()=>{const h=Kl(f,n);return Es(c.current,h)?c.current:(c.current=h,h)},[f,n]),m=a.useMemo(()=>{const h=new Map,b=Array.from(new Set(w.map(S=>S.ideId)));for(const S of b){const N=Mt(w,S);N&&h.set(S,N)}return h},[w]),C=a.useMemo(()=>{const h=new Map;for(const b of w)if(b.sessionId&&h.set(b.sessionId,b),b.streamSource==="native"&&b.sessionId){const S=m.get(b.ideId);S&&h.set(b.sessionId,S)}return h},[w,m]),g=a.useMemo(()=>{const h=new Map;for(const b of w)b.sessionId&&h.set(b.sessionId,b),h.set(b.ideId,m.get(b.ideId)||b),h.set(b.tabKey,b);return h},[w,m]),y=a.useCallback(h=>{if(h)return C.get(h)},[C]),k=a.useCallback(h=>{if(h)return g.get(h)},[g]),I=a.useMemo(()=>{const h=w.filter(b=>!i.has(b.tabKey));return Es(d.current,h)?d.current:(d.current=h,h)},[w,i]),j=a.useMemo(()=>{const h=I.map(b=>b.tabKey);return Es(l.current,h)?l.current:(l.current=h,h)},[I]);return{chatIdes:p,conversations:w,visibleConversations:I,visibleTabKeys:j,resolveConversationBySessionId:y,resolveConversationByTarget:k}}function Fl({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 Vl({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:i}){a.useEffect(()=>{nt.setIdes(t)},[t]),a.useEffect(()=>{nt.setResolveAction((o,c,d)=>{s(o,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const o=nt.onToast(l=>{r(u=>u.some(v=>v.message===l.message&&l.timestamp-v.timestamp<3e3)?u:[...u.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(u=>u.filter(x=>x.id!==l.id)),p)}),c=nt.onSystemMessage((l,p)=>{var f,w;const u=i(l),x=(f=p._localId)==null?void 0:f.startsWith("sys_approval_"),v=!!(u&&(u.status==="waiting_approval"||(w=u.modalButtons)!=null&&w.length||u.modalMessage));x&&v||n(m=>({...m,[l]:[...m[l]||[],p]}))}),d=nt.onClearSystemMessage((l,p)=>{n(u=>{var x;return(x=u[l])!=null&&x.length?{...u,[l]:u[l].filter(v=>{var f;return!(v.role==="system"&&((f=v._localId)!=null&&f.startsWith(p)))})}:u})});return()=>{o(),c(),d()}},[r,n]),a.useEffect(()=>{const o=Ma.on("status_event",c=>{!c||typeof c!="object"||typeof c.event!="string"||nt.handleRawEvent(c,"ws")});return()=>{o()}},[]),a.useEffect(()=>{var c;const o=d=>{var C;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,u=i(p),x=(u==null?void 0:u.ideId)||l.ideId;if(!x)return;const v=Number(l.buttonIndex),f=l.button||((C=u==null?void 0:u.modalButtons)==null?void 0:C[v])||"Approve",w=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),m=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);s(x,"resolve_action",{action:m?"approve":"reject",button:f,...Number.isFinite(v)&&{buttonIndex:v},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.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 Gl="adhdev_dashboardLayout_v1",ql="adhdev_dashboardDockview_v1",bs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Qa(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function ei(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function ti(t){return`${Gl}:${t}`}function Yl(t){const s=ti(t);return Qa(s,null)}function Xl(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=ti(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function si(t){return`${ql}:${t}`}function Jl(t){const s=si(t);return Qa(s,null)}function Zl(t,s){try{const r=si(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ql(){return{groupAssignments:[...bs.groupAssignments],focusedGroup:bs.focusedGroup,groupActiveTabIds:{...bs.groupActiveTabIds},groupTabOrders:{...bs.groupTabOrders},groupSizes:[...bs.groupSizes]}}function ed(){const[t]=a.useState(()=>ei(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,u]=a.useState([]),[x,v]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[f,w]=a.useState(!1),m=a.useCallback(()=>{if(f)return;const C=Yl(t)??Ql();r(new Map(C.groupAssignments)),i(C.focusedGroup),c(C.groupActiveTabIds),l(C.groupTabOrders),u(C.groupSizes),w(!0)},[f,t]);return a.useEffect(()=>{f&&Xl(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:d,groupSizes:p})},[f,t,s,n,o,d,p]),a.useEffect(()=>{const C=window.matchMedia("(max-width: 767px)"),g=y=>v(y.matches);return C.addEventListener("change",g),()=>C.removeEventListener("change",g)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:i,groupActiveTabIds:o,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:l,groupSizes:p,setGroupSizes:u,isMobile:x,hasHydratedStoredLayout:f,hydrateStoredLayout:m}}function td(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[0],n=[s.providerSessionId,s.sessionId].filter(i=>typeof i=="string"&&i.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function sd({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:i,hydrateStoredLayout:o,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:l,historyModalOpen:p,activeConv:u,isRefreshingHistory:x,ides:v,handleRefreshHistory:f}){const w=a.useRef(!1),m=a.useRef(!1),C=a.useRef(null),g=a.useRef(!1);a.useEffect(()=>{if(!t||w.current||s.length===0)return;if(!i){o();return}const y=r(t);if(!y)return;const k=n.get(y.tabKey)??0;c(I=>({...I,[k]:y.tabKey})),d(k),w.current=!0,m.current=!0,C.current!=null&&(window.clearTimeout(C.current),C.current=null),l(I=>{const j=new URLSearchParams(I);return j.delete("activeTab"),j},{replace:!0})},[t,s,r,n,i,o,c,d,l]),a.useEffect(()=>{if(!(m.current||i)&&s.length!==0){if(!t){o(),m.current=!0;return}if(w.current){m.current=!0;return}if(C.current==null)return C.current=window.setTimeout(()=>{C.current=null,!(m.current||i)&&(o(),m.current=!0)},1500),()=>{C.current!=null&&(window.clearTimeout(C.current),C.current=null)}}},[t,s.length,i,o]),a.useEffect(()=>{if(!p){g.current=!1;return}if(!u||g.current||x)return;const y=v.find(k=>k.id===u.ideId);y&&(!y.chats||y.chats.length===0||td(y.chats,u))&&(g.current=!0,f())},[p,u,x,v,f]),a.useEffect(()=>{if(!u)return;let y=null,k=0,I=-1,j=0;const h=()=>{y=null;const b=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(N=>N.offsetParent!==null);if(b.length===0){k<18&&(k+=1,y=requestAnimationFrame(h));return}let S=0;for(const N of b)N.scrollTop=N.scrollHeight,S+=N.scrollHeight;S===I?j+=1:(j=0,I=S),k+=1,!(j>=2||k>=18)&&(y=requestAnimationFrame(h))};return y=requestAnimationFrame(h),()=>{y!=null&&cancelAnimationFrame(y)}},[u==null?void 0:u.tabKey])}function rd({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:o,ides:c,resolveConversationByTarget:d}){const[l,p]=a.useState(null),[u,x]=a.useState(null),v=a.useMemo(()=>{if(t||!n)return null;const g=d(n);return g&&!Be(g)&&!De(g)?g:null},[t,n,d]),f=a.useMemo(()=>{const g=l==null?void 0:l.ideId;if(!g)return null;const y=l!=null&&l.tabKey?o.find(k=>k.tabKey===l.tabKey):i?o.find(k=>k.tabKey===i):null;return(y==null?void 0:y.ideId)===g?y:Mt(o,g)},[o,l,i]),w=a.useMemo(()=>{if(f)return c.find(g=>g.id===f.ideId)},[c,f]);a.useEffect(()=>{v&&(p({ideId:v.ideId,tabKey:vn(v)}),x(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const m=a.useCallback(g=>{g&&(p({ideId:g.ideId,tabKey:vn(g)}),x(g))},[]),C=a.useCallback(()=>{p(null),x(null)},[]);return{remoteDialogConv:f,remoteDialogIdeEntry:w,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:m,closeRemoteDialog:C}}function os(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return Be(t)||De(t)?{...s,agentType:Xt(t)}:t.streamSource==="agent-stream"?{...s,agentType:Xt(t)}:s}function Cs(t){return t?Wr(t):""}function gs(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function pr(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[0];if((r==null?void 0:r.active)===!0)return!0;const n=[s.providerSessionId,s.sessionId].filter(i=>typeof i=="string"&&i.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Rn({sendDaemonCommand:t,activeConv:s,chats:r,updateIdeChats:n,setToasts:i,setLocalUserMessages:o,setClearedTabs:c}){const[d,l]=a.useState(!1),[p,u]=a.useState(!1),x=a.useCallback(async m=>{try{await t("standalone","launch_ide",{ideType:m,enableCdp:!0})}catch(C){console.error("Launch failed",C)}},[t]),v=a.useCallback(async(m,C)=>{try{const g=m||(s==null?void 0:s.daemonId)||"",y=await t(g,"switch_chat",{id:C,sessionId:C,...os(s)}),k=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||k==="switched"||k==="switched-by-title")return;k===!1||k==="not_found"?gs(i,"⚠️ Session tab not found — try refreshing history"):typeof k=="string"&&k.startsWith("error:")?gs(i,`⚠️ Switch error: ${k}`):gs(i,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),gs(i,`❌ Switch failed: ${g.message||"connection error"}`)}},[s,t,i]),f=a.useCallback(async()=>{if(!(!s||d)){l(!0);try{const m=Cs(s);await t(m,"new_chat",{...os(s)}),c(C=>({...C,[s.tabKey]:Date.now()})),o(C=>({...C,[s.tabKey]:[]}))}catch(m){console.error("New chat failed",m)}finally{l(!1)}}},[s,d,t,c,o]),w=a.useCallback(async()=>{var m,C;if(!(!s||p)){u(!0);try{const g=Cs(s),y=async()=>t(g,"list_chats",{forceExpand:!0,...os(s)});let k=await y(),I=(k==null?void 0:k.chats)||((m=k==null?void 0:k.result)==null?void 0:m.chats);pr(I,s)&&(await new Promise(j=>setTimeout(j,450)),k=await y(),I=(k==null?void 0:k.chats)||((C=k==null?void 0:k.result)==null?void 0:C.chats)),k!=null&&k.success&&Array.isArray(I)&&(n(s.ideId,I),pr(I,s)&&!pr(r,s)&&gs(i,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{u(!1)}}},[s,r,p,t,n,i]);return{isCreatingChat:d,isRefreshingHistory:p,handleLaunchIde:x,handleSwitchSession:v,handleNewChat:f,handleRefreshHistory:w}}function nd(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 ad(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function En(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 $s(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 $n(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 id(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 od(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 Dn(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 Bn(t){return Array(t).fill(100/t)}function cd({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:i,groupSizes:o,setGroupSizes:c,isMobile:d,visibleConversations:l,visibleTabKeys:p}){const u=a.useRef(null),x=a.useMemo(()=>$s(t,p),[t,p]),v=x.assignments,f=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),w=f>1,m=a.useCallback((j,h)=>{s(b=>{const S=new Map($s(b,p).assignments);return h===0?S.delete(j):S.set(j,h),S}),n(b=>({...b,[h]:j})),r(h)},[s,p,n,r]),C=a.useCallback(j=>{s(h=>{const b=$s(h,p).assignments,S=new Map;for(const[N,E]of b)E!==j&&(E>j?S.set(N,E-1):S.set(N,E));return S}),c(h=>{if(h.length<=1)return[];const b=[...h];b.splice(j,1);const S=b.reduce((N,E)=>N+E,0);return S>0?b.map(N=>N/S*100):[]}),r(0)},[s,p,c,r]),g=a.useCallback((j,h)=>{h.preventDefault();const b=u.current;if(!b)return;const S=h.clientX,N=b.offsetWidth,E=o.length===f?[...o]:Bn(f),D=T=>{const _=(T.clientX-S)/N*100,R=[...E];R[j]=Math.max(15,E[j]+_),R[j+1]=Math.max(15,E[j+1]-_),c(R)},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,f,c]),y=a.useCallback((j,h,b)=>{if(f>=4)return;const S=b==="left"?h:h+1;s(N=>{const E=$s(N,p).assignments,D=new Map;for(const O of l){const T=E.get(O.tabKey)??0,L=T>=S?T+1:T;L>0&&D.set(O.tabKey,L)}return S>0&&D.set(j,S),D}),c(N=>{const E=N.length===f?[...N]:Bn(f),D=E[h]??100/f,O=Math.max(15,D/2),T=Math.max(15,D/2),L=[...E];L[h]=O,L.splice(S,0,T);const _=L.reduce((R,B)=>R+B,0);return L.map(R=>R/_*100)}),n(N=>{const E=Dn(N,S);return E[S]=j,E}),i(N=>{const E=Dn(N,S);return E[S]=[j],E}),r(S)},[f,s,p,l,c,n,i,r]);a.useEffect(()=>{nd(t,v)||s(v)},[t,v,s]),a.useEffect(()=>{const{mapping:j,usedGroups:h}=x;n(b=>{const S=$n(b,j);return En(b,S)?b:S}),i(b=>{const S=$n(b,j);return En(b,S)?b:S}),r(b=>{const S=d?0:id(b,h,j);return b===S?b:S}),c(b=>{const S=d?[]:od(b,h,x.groupCount);return ad(b,S)?b:S})},[x,d,n,i,r,c]);const k=a.useMemo(()=>{const j=Array.from({length:f},()=>[]);for(const h of l){const b=v.get(h.tabKey)??0,S=Math.min(b,f-1);j[S].push(h)}return j},[l,v,f]),I=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:v,numGroups:f,isSplitMode:w,groupedConvs:k,moveTabToGroup:m,closeGroup:C,handleResizeStart:g,splitTabRelative:y,clearAllSplits:I}}function ld({ides:t,sendDaemonCommand:s}){const r="0.8.35",n=a.useMemo(()=>t.filter(p=>{if(p.type!=="adhdev-daemon")return!1;const u=p.version||p.daemonVersion||null;return!u||!r?!1:u!==r}),[r,t]),[i,o]=a.useState(!1),[c,d]=a.useState({}),l=a.useCallback(async p=>{var u,x;d(v=>({...v,[p]:"upgrading"}));try{const v=await s(p,"daemon_upgrade",{});(u=v==null?void 0:v.result)!=null&&u.upgraded||(x=v==null?void 0:v.result)!=null&&x.success?d(f=>({...f,[p]:"done"})):d(f=>({...f,[p]:"error"}))}catch{d(v=>({...v,[p]:"error"}))}},[s]);return{versionMismatchDaemons:n,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:o,upgradingDaemons:c,handleBannerUpgrade:l}}function Kn(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function qr(t){return t instanceof Error?t.message:String(t||"")}function Wn(t){const s=qr(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function On(t,s){const r=qr(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function sr({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),u=a.useRef(null),x=a.useCallback(async m=>{if(!s)return;const C=m.trim();if(!C||p.current)return;const g=s.tabKey,y=Date.now(),k=u.current;if(k&&k.tabKey===g&&k.message===C&&y-k.timestamp<2e3)return;p.current=!0,l(!0),u.current={tabKey:g,message:C,timestamp:y};const I=`${y}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:C,timestamp:y,_localId:I},h=!(Be(s)||De(s));h&&r(b=>({...b,[g]:[...b[g]||[],j]}));try{const b=Cs(s);if(!b)return;const S=await t(b,"send_chat",{message:C,...os(s)}),N=Kn(S);if(h&&(N!=null&&N.deduplicated||(N==null?void 0:N.sent)===!1)){r(E=>({...E,[g]:(E[g]||[]).filter(D=>D._localId!==I)}));return}if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");setTimeout(()=>{const E=Date.now()-6e4;r(D=>{const O=D[g];if(!O)return D;const T=O.filter(L=>L.timestamp>E);return T.length===O.length?D:{...D,[g]:T}})},6e4)}catch(b){const S=qr(b);S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.error("Send failed",b),h&&r(N=>({...N,[g]:(N[g]||[]).filter(E=>E._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(m){console.error("Relaunch failed",m)}},[s,t]),f=a.useCallback(async m=>{if(s)try{const g=(s.modalButtons||[]).indexOf(m),y=m.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y),I=Cs(s);if(!I)return;const j=await t(I,"resolve_action",{button:m,action:k?"approve":"reject",...g>=0&&{buttonIndex:g},...os(s)}),h=Kn(j);h.success||n(b=>[...b,{ideId:s.tabKey,text:On(m,h==null?void 0:h.error),timestamp:Date.now()}])}catch(C){Wn(C)||console.error("[ModalButton] Error:",C),n(g=>[...g,{ideId:s.tabKey,text:Wn(C)?On(m,C):`❌ **${m}** 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(m){console.error("Focus agent failed",m)}finally{c(!1)}}},[s,o,t]);return{isSendingChat:d,isFocusingAgent:o,handleSendChat:x,handleRelaunch:v,handleModalButton:f,handleFocusAgent:w}}const Yr=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:i,terminalRef:o,handleModalButton:c,handleRelaunch:d,handleSendChat:l,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:f,scrollToBottomRequestNonce:w,isInputActive:m=!0}){return e.jsxs(e.Fragment,{children:[e.jsx(ja,{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(qt,{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(Nc,{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(Ir,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:f,scrollToBottomRequestNonce:w,isInputActive:m})})]}):e.jsx(Ir,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:x,actionLogs:v,userName:f,scrollToBottomRequestNonce:w,isInputActive:m})]})},(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 dd({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:i,userName:o,isSendingChat:c,isFocusingAgent:d,onBack:l,onOpenNativeConversation:p,onOpenMachine:u,onOpenHistory:x,onOpenRemote:v,onHideConversation:f,onStopCli:w,cliViewMode:m,onSetCliViewMode:C,handleSendChat:g,handleFocusAgent:y,handleModalButton:k,handleRelaunch:I}){const j=a.useRef(null),h=Be(t)&&!s,b=h&&m==="terminal",S=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 ${S} 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(Rr,{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:Fe(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(Ia,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(t),onOpenMachine:()=>u(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[h&&m&&e.jsx(zr,{mode:m,onChange:C,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(ft,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(t),type:"button",children:e.jsx($r,{size:14})}),!s&&!h&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(t),type:"button",children:e.jsx(ct,{size:14})}),f&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(t),type:"button",title:"Close chat",children:e.jsx(ft,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Yr,{activeConv:t,clearToken:0,isCliTerminal:b,ideEntry:n,terminalRef:j,handleModalButton:k,handleRelaunch:I,handleSendChat:g,isSendingChat:c,handleFocusAgent:y,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 ud(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ri(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[i,o]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(ud())},[]);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 ni({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:ct},{key:"chats",label:"Chats",icon:At}];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 Ds({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function rs({children:t,className:s=""}){return e.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:t})}function 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 Bs({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}=ms(t.conversation),p=Fe(t.conversation),u=Zt(t.conversation),x=Pa(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:wa(t.timestamp)})]}),e.jsxs("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:[u,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…"})]}):x==="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 zn({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 md({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:i,hiddenConversations:o,machineCards:c,getAvatarText:d,onOpenConversation:l,onShowConversation:p,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:v,onOpenSettings:f,onSectionChange:w,wsStatus:m="connected",isStandalone:C=!1}){const g=m==="disconnected"||m==="reconnecting"||m==="offline"||m==="auth_failed",y=c.length>0,k=s.length>0||r.length>0||n.length>0||i.length>0,I=t==="machines"?"Machines":"Chats",j=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",h=C?"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 ${j}`,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(Qs,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:f,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(Js,{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(zn,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:m==="offline"?"Your device appears to be offline. Waiting for network…":m==="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:C?"Waiting for your daemon":"Connect your first machine",subtitle:C?"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:!C&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(ri,{})})}):e.jsx(rs,{children:c.map((b,S)=>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] ${S>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(b.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(b.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:b.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:b.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[b.unread," new"]}):b.total>0?`${b.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:b.subtitle}),b.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[b.total," chat",b.total!==1?"s":"",b.unread>0?` · ${b.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},b.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(Ds,{title:"Needs attention",className:"mb-0"}),e.jsx(rs,{children:s.map((b,S)=>e.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:e.jsx(Bs,{item:b,type:"needs_attention",getAvatarText:d,onOpenConversation:l})},b.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(Ds,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(rs,{children:r.map((b,S)=>e.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:e.jsx(Bs,{item:b,type:"task_complete",getAvatarText:d,onOpenConversation:l})},b.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(Ds,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(rs,{children:n.map((b,S)=>e.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:e.jsx(Bs,{item:b,type:"working",getAvatarText:d,onOpenConversation:l})},b.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(Ds,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),i.length>0?e.jsx(rs,{children:i.map((b,S)=>e.jsx("div",{className:S>0?"border-t border-border-subtle/70":"",children:e.jsx(Bs,{item:b,type:"earlier",getAvatarText:d,onOpenConversation:l})},b.conversation.tabKey))}):k?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(zn,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):y?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(At,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):e.jsx(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:u,children:"Restore all"})]}),e.jsx(rs,{className:"bg-bg-secondary/25",children:o.map((b,S)=>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 ${S>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(b),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(Fe(b))}),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:Fe(b)}),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:Zt(b)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},b.tabKey))})]})]}),t==="chats"&&x&&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:x,"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(ni,{section:t,onSectionChange:w})]})}function pd(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 rr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=pd(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 fd(t){const s=t.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function nr(t,s,r){const n=await t(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const 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 ar({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[u,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const v=fd(r),f=u.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(ft,{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(Rr,{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:u,onChange:w=>x(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!f||i||(w.preventDefault(),l(f))},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:()=>{!f||i||l(f)},disabled:!f||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(cs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children: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(f||r),disabled:!f&&!r||i,children:c})]})]})})}function Xr({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:i,onWorkspaceChange:o,confirmLabel:c="Launch",busy:d=!1,showArgsInput:l,argsValue:p,onArgsChange:u,showModelInput:x,modelValue:v,onModelChange:f,historyProviderNode:w,onConfirm:m,onCancel:C}){const g=n==null?void 0:n.find(y=>y.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:C,"aria-label":"Close launch confirmation",children:e.jsx(ft,{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:y=>o(y.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(y=>e.jsx("option",{value:y.key,children:y.label},y.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(y=>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:y.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:y.value})]},`${y.label}:${y.value}`)),x&&f&&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:y=>f(y.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&&u&&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:y=>u(y.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:C,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:m,disabled:d,children:[e.jsx(Dr,{size:14}),d?"Launching…":c]})]})]})})}function Un(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Vt(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?"⭐ ":""}${Un(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:Un(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 xr(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function xd({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:i,onListSavedSessions:o}){var ee,ye,A,G;const[c,d]=a.useState(!1),l=(((ee=t.detectedIdes)==null?void 0:ee.length)||0)>0,p=a.useMemo(()=>(t.workspaces||[]).map(z=>({id:z.id,path:z.path,label:z.label})),[t]),u=t.defaultWorkspaceId||null,[x,v]=a.useState(u||((ye=p[0])==null?void 0:ye.id)||""),[f,w]=a.useState(""),[m,C]=a.useState(""),[g,y]=a.useState([]),[k,I]=a.useState(!1),[j,h]=a.useState(""),[b,S]=a.useState(!1),[N,E]=a.useState(xr(l,s.length,r.length)),D=a.useRef(null),[O,T]=a.useState(null),L=a.useRef("__home__"),[_,R]=a.useState("__home__"),[B,Y]=a.useState(""),[K,$]=a.useState(""),[W,F]=a.useState(""),[V,te]=a.useState([]),[ke,J]=a.useState(!1),[Z,q]=a.useState(!1),xe=a.useRef(null),re=x==="__custom__"?f.trim():((A=p.find(z=>z.id===x))==null?void 0:A.path)||"",he=x==="__custom__"&&!!re&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ve=x!=="__custom__"&&((G=p.find(z=>z.id===x))==null?void 0:G.path)||"",ie=a.useCallback(async z=>{I(!0),h("");try{const ae=await i(z);C(ae.path),w(ae.path),y(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__"),S(!0);const z=rr(t.platform,[f.trim(),ve,(ae=p.find(Ce=>Ce.id===u))==null?void 0:ae.path,(de=p[0])==null?void 0:de.path]);ie(z)},[f,u,ie,ve,t.platform,p]),oe=a.useCallback(z=>{if(z!=null&&z.workspaceId){v(z.workspaceId),w("");return}if(z!=null&&z.workspacePath){v("__custom__"),w(z.workspacePath);return}v(""),w("")},[]),ge=a.useCallback(z=>{if(v(z),z==="__custom__"){pe();return}w("")},[pe]),X=a.useCallback(z=>{v("__custom__"),w(z)},[]),se=a.useCallback((z,ae)=>{D.current=ae,L.current=z.selectedWorkspaceKey||"__home__",R(z.selectedWorkspaceKey||"__home__"),Y(z.initialArgs||""),$(z.initialModel||""),F(""),te([]),T(z),z.providerType&&o&&(J(!0),o(z.providerType).then(de=>te(de||[])).catch(de=>console.warn("Failed to load saved sessions",de)).finally(()=>J(!1)))},[o]),Q=a.useCallback(()=>{D.current&&(q(!0),D.current().finally(()=>{D.current=null,q(!1),T(null)}))},[]),fe=a.useCallback(()=>{D.current=null,T(null)},[]),M=a.useCallback(z=>{L.current=z,R(z)},[]);return a.useEffect(()=>{var z;xe.current!==t.id&&(xe.current=t.id,v(u||((z=p[0])==null?void 0:z.id)||"__custom__"),w(""),C(""),y([]),h(""),S(!1),E(xr(l,s.length,r.length)))},[r.length,s.length,u,l,t.id,p]),a.useEffect(()=>{var z;x!=="__custom__"&&(x&&p.some(ae=>ae.id===x)||v(u||((z=p[0])==null?void 0:z.id)||"__custom__"))},[u,x,p]),a.useEffect(()=>{N==="ide"&&l||N==="cli"&&s.length>0||N==="acp"&&r.length>0||E(xr(l,s.length,r.length))},[N,r.length,s.length,l]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:l,workspaceRows:p,defaultWorkspaceId:u,workspaceChoice:x,customWorkspacePath:f,browseCurrentPath:m,browseDirectories:g,browseBusy:k,browseError:j,browseDialogOpen:b,activeLauncherKind:N,launchConfirm:O,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:_,launchConfirmArgs:B,launchConfirmModel:K,launchConfirmResumeId:W,launchConfirmSavedSessions:V,launchConfirmSessionsLoading:ke,launchConfirmBusy:Z,resolvedWorkspacePath:re,canCreateMissingWorkspace:he,openBrowseDialog:pe,loadBrowsePath:ie,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:X,setCustomWorkspacePath:w,setBrowseDialogOpen:S,setActiveLauncherKind:E,openLaunchConfirm:se,handleConfirmLaunch:Q,closeLaunchConfirm:fe,setWorkspaceSelectionFromOption:oe,setLaunchConfirmWorkspaceKeyAndSync:M,setLaunchConfirmArgs:Y,setLaunchConfirmModel:$,setLaunchConfirmResumeId:F}}function hd({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:i,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:d,isStandalone:l,section:p,showBottomNav:u,onBack:x,onSectionChange:v,onOpenConversation:f,onOpenRecent:w,onOpenMachineDetails:m,onMachineUpgrade:C,onLaunchDetectedIde:g,onAddWorkspace:y,onBrowseDirectory:k,onLaunchWorkspaceProvider:I,onListSavedSessions:j}){const h=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",b=r.slice(0,4),S=s.slice(0,3),N=xd({selectedMachineEntry:t,cliProviders:n,acpProviders:i,machineAction:d,onBrowseDirectory:k,onListSavedSessions:j}),E=a.useMemo(()=>b.map(R=>({key:`recent-launch:${R.id}`,primary:R.label,secondary:`${h(R.kind)}${R.subtitle?` · ${R.subtitle}`:""}`,onClick:()=>{const{options:B,selectedKey:Y}=Vt({machine:{workspaces:N.workspaceRows,defaultWorkspaceId:N.defaultWorkspaceId},currentWorkspacePath:R.workspace});N.openLaunchConfirm({title:`Launch ${R.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:B,selectedWorkspaceKey:Y,details:[{label:"Mode",value:h(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const K=B.find($=>$.key===N.launchConfirmWorkspaceKeyRef.current);N.setWorkspaceSelectionFromOption(K),await w({...R,workspace:(K==null?void 0:K.workspacePath)??null})})}})),[N,w,b]),D=a.useMemo(()=>S.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:Fe(R.conversation),secondary:yc(R.conversation,{timestampLabel:R.timestamp?wa(R.timestamp):null}),unread:R.unread,onClick:()=>f(R.conversation)})),[f,S]),O=N.showAllRecent?E:E.slice(0,4),T=E.length>0,L=D.length>0,_=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 ${_} 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:x,type:"button","aria-label":"Back",children:e.jsx(Rr,{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:ot(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:[L&&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(R=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),T&&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(R=>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:R.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.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:()=>N.setShowAllRecent(R=>!R),children:N.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(N.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:N.workspaceChoice,onChange:R=>N.handleWorkspaceChoiceChange(R.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:N.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[N.workspaceRows.map(R=>e.jsxs("option",{value:R.id,children:[R.id===N.defaultWorkspaceId?"⭐ ":"",er(R.path,R.label)||R.path]},R.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),N.workspaceChoice==="__custom__"&&e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:e.jsx(cs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:N.resolvedWorkspacePath||N.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:N.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:()=>{N.resolvedWorkspacePath&&y(N.resolvedWorkspacePath)},disabled:!N.resolvedWorkspacePath||N.browseBusy,children:"Save as workspace"})]})]}),N.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:N.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[N.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${N.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:()=>N.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${N.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:()=>N.setActiveLauncherKind("cli"),children:"CLI"}),i.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${N.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:()=>N.setActiveLauncherKind("acp"),children:"ACP"})]}),N.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:N.activeLauncherKind==="ide"?"Choose an IDE":N.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:N.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(R=>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:Y}=Vt({machine:{workspaces:N.workspaceRows,defaultWorkspaceId:N.defaultWorkspaceId},currentWorkspaceId:N.workspaceChoice!=="__custom__"?N.workspaceChoice:null,currentWorkspacePath:N.resolvedWorkspacePath});N.openLaunchConfirm({title:`Launch ${R.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:B,selectedWorkspaceKey:Y,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:R.name}]},async()=>{const K=B.find($=>$.key===N.launchConfirmWorkspaceKeyRef.current);N.setWorkspaceSelectionFromOption(K),g(R.type,{workspacePath:(K==null?void 0:K.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:R.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:N.resolvedWorkspacePath||"Use selected workspace"})]},R.type)):(N.activeLauncherKind==="cli"?n:i).map(R=>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=N.activeLauncherKind==="cli"?"cli":"acp",{options:Y,selectedKey:K}=Vt({machine:{workspaces:N.workspaceRows,defaultWorkspaceId:N.defaultWorkspaceId},currentWorkspaceId:N.workspaceChoice!=="__custom__"?N.workspaceChoice:null,currentWorkspacePath:N.resolvedWorkspacePath});N.openLaunchConfirm({title:`Launch ${R.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${B.toUpperCase()}`,workspaceOptions:Y,selectedWorkspaceKey:K,details:[{label:"Mode",value:B.toUpperCase()},{label:"Provider",value:R.displayName}],showArgsInput:!0,showModelInput:B==="acp",initialArgs:"",initialModel:"",providerType:R.type},async()=>{const $=Y.find(W=>W.key===N.launchConfirmWorkspaceKeyRef.current);N.setWorkspaceSelectionFromOption($),I(B,R.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:N.launchConfirmArgs,model:N.launchConfirmModel,resumeSessionId:N.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[R.icon?`${R.icon} `:"",R.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:N.resolvedWorkspacePath||"Use selected workspace"})]},R.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,N.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:()=>y(N.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:C,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:m,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"})]})]})]})]}),N.browseDialogOpen&&e.jsx(ar,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:N.browseCurrentPath,directories:N.browseDirectories,busy:N.browseBusy,error:N.browseError,confirmLabel:"Use this folder",onClose:()=>N.setBrowseDialogOpen(!1),onNavigate:R=>{N.loadBrowsePath(R)},onConfirm:R=>{N.chooseCustomWorkspacePath(R),N.setBrowseDialogOpen(!1)}}),N.launchConfirm&&e.jsx(Xr,{title:N.launchConfirm.title,description:N.launchConfirm.description,details:N.launchConfirm.details,workspaceOptions:N.launchConfirm.workspaceOptions,selectedWorkspaceKey:N.launchConfirmWorkspaceKey,onWorkspaceChange:N.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:N.launchConfirm.confirmLabel,busy:N.launchConfirmBusy,showArgsInput:N.launchConfirm.showArgsInput,argsValue:N.launchConfirmArgs,onArgsChange:N.setLaunchConfirmArgs,showModelInput:N.launchConfirm.showModelInput,modelValue:N.launchConfirmModel,onModelChange:N.setLaunchConfirmModel,historyProviderNode:N.launchConfirm.providerType&&(N.launchConfirmSessionsLoading||N.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"}),N.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:N.launchConfirmResumeId,onChange:R=>N.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),N.launchConfirmSavedSessions.map(R=>e.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]})]}),onConfirm:N.handleConfirmLaunch,onCancel:N.closeLaunchConfirm}),u&&e.jsx(ni,{section:p,onSectionChange:v})]})}function ai(t){var r;const s=((r=t.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function bd(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=Ss(n)?"cli":as(n)?"acp":"ide";return{id:`${i}:${n.type}:${n.workspace||""}`,label:((o=n.activeChat)==null?void 0:o.title)||(Ss(n)?n.cliName||n.type:as(n)&&n.cliName||n.type),kind:i,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:as(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((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 gd(t,s){const r=new Map;for(const n of s){const i=Pt(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((x,v)=>v.timestamp-x.timestamp)[0]||null,c=(o==null?void 0:o.conversation)||null,d=Cr(n),l=i.filter(x=>x.unread||x.requiresAction).length,p=ai(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:ot(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:l,total:i.length,latestConversation:c,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:d,preview:c?vc(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 Ks(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 yd({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:i,screen:o,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:l,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:v,onRequestedMobileSectionConsumed:f,setSelectedTabKey:w,setScreen:m,setSelectedMachineId:C,setSection:g,setMachineBackTarget:y,resetMachineAction:k}){const I=a.useRef(null),j=a.useCallback(h=>{if(!(h!=null&&h.sessionId))return;const b=ks(h,c),S=Math.max(Date.now(),Ft(h),b.lastUpdated||0);Ks("mark_read:start",{tabKey:h.tabKey,sessionId:h.sessionId,displayPrimary:Fe(h),inboxBucket:b.inboxBucket,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,activityAt:Ft(h),readAt:S}),d(Pt(h)||h.ideId,"mark_session_seen",{sessionId:h.sessionId,seenAt:S}).then(N=>{Ks("mark_read:result",{tabKey:h.tabKey,sessionId:h.sessionId,result:N})}).catch(N=>{Ks("mark_read:error",{tabKey:h.tabKey,sessionId:h.sessionId,error:N instanceof Error?N.message:String(N)})})},[c,d]);return a.useEffect(()=>{var b;if(!n){m("inbox"),w(((b=t[0])==null?void 0:b.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,j(n))},[t,j,o,n,m,w]),a.useEffect(()=>{if(!l)return;const h=t.find(b=>b.tabKey===l);h&&(w(h.tabKey),m("chat"),p==null||p())},[t,p,l,m,w]),a.useEffect(()=>{if(!u)return;const h=s.find(b=>b.id===u);h&&(C(h.id),k(),g("machines"),y("inbox"),m("machine"),x==null||x())},[s,x,u,k,y,m,g,C]),a.useEffect(()=>{v&&(g(v),m("inbox"),f==null||f())},[f,v,m,g]),a.useEffect(()=>{const h=r.filter(b=>b.inboxBucket==="task_complete"||b.unread);h.length!==0&&Ks("inbox_state",{screen:o,selectedTabKey:i,items:h.map(b=>{const S=ks(b.conversation,c);return{liveState:S,tabKey:b.conversation.tabKey,sessionId:b.conversation.sessionId,displayPrimary:Fe(b.conversation),serverBucket:S.inboxBucket,computedBucket:b.inboxBucket,serverUnread:S.unread,computedUnread:b.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Ft(b.conversation)}})})},[r,c,o,i]),{markConversationRead:j}}function vd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Hn(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function wd(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function jd({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[i,o]=a.useState("idle"),[c,d]=a.useState(""),[l,p]=a.useState(null),u=a.useCallback(()=>{o("idle"),d(""),p(null)},[]),x=a.useCallback(async(y,k,I)=>{var j;try{o("loading"),d(`Launching ${k}…`);const h={ideType:k,enableCdp:!0};(j=I==null?void 0:I.workspacePath)!=null&&j.trim()&&(h.workspace=I.workspacePath.trim()),await t(y,"launch_ide",h),o("done"),d(`${k} 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(y,k,I)=>{if(k.trim())try{o("loading"),d(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const j=await t(y,"workspace_add",{path:k.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(j!=null&&j.success){o("done"),d(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),d((j==null?void 0:j.error)||"Could not save workspace")}catch(j){o("error"),d(j instanceof Error?j.message:"Could not save workspace")}},[t]),f=a.useCallback(async y=>{var k,I,j,h,b,S;try{o("loading"),d("Starting daemon upgrade…");const N=await t(y,"daemon_upgrade",{});if((k=N==null?void 0:N.result)!=null&&k.alreadyLatest){o("done"),d(`Already on v${((I=N==null?void 0:N.result)==null?void 0:I.version)||"latest"}.`);return}if((j=N==null?void 0:N.result)!=null&&j.upgraded||(h=N==null?void 0:N.result)!=null&&h.success){o("done"),d(`Upgrade to v${((b=N==null?void 0:N.result)==null?void 0:b.version)||"latest"} started. Daemon is restarting…`);return}o("error"),d(((S=N==null?void 0:N.result)==null?void 0:S.error)||"Upgrade failed")}catch(N){o("error"),d(N instanceof Error?N.message:"Upgrade failed")}},[t]),w=a.useCallback(async(y,k,I,j)=>{var S,N,E;const h=Date.now(),b={machineId:y,kind:k,providerType:I,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:h};try{o("loading"),d(`Launching ${I}…`),p(b);const D={cliType:I};(S=j==null?void 0:j.workspacePath)!=null&&S.trim()?D.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(D.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(D.resumeSessionId=j.resumeSessionId),(N=j==null?void 0:j.args)!=null&&N.trim()&&(D.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),(E=j==null?void 0:j.model)!=null&&E.trim()&&(D.initialModel=j.model.trim());const O=await t(y,"launch_cli",D),T=(O==null?void 0:O.result)||O,L=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(O!=null&&O.success&&L){p(null),o("done"),d(`${I} launched`),s(`/dashboard?activeTab=${encodeURIComponent(L)}`);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)||(T==null?void 0:T.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(D){if(wd(D)){o("loading"),d(`${I} launch requested — waiting for session…`);return}p(null),o("error"),d(D instanceof Error?D.message:`Could not launch ${k.toUpperCase()} workspace`)}},[s,t]),m=a.useCallback(async(y,k)=>{try{const I=await t(y,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(I==null?void 0:I.result)??I;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[t]),C=a.useCallback(async(y,k)=>nr(t,y,k),[t]);a.useEffect(()=>{var j;if(!l)return;const y=Hn(l.workspacePath),k=r.find(h=>{var O,T,L,_;if(!h||h.type==="adhdev-daemon"||h.daemonMode||vd(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(y){const R=Hn(h.workspace||h.runtimeWorkspaceLabel);return R?R===y:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((_=(L=(T=(O=h.activeChat)==null?void 0:O.messages)==null?void 0:T.at)==null?void 0:L.call(T,-1))==null?void 0:_.timestamp)||0)>=l.startedAt-5e3});if(!k)return;const I=typeof k.sessionId=="string"&&k.sessionId?k.sessionId:typeof k.instanceId=="string"&&k.instanceId?k.instanceId:(j=n.find(h=>h.ideId===k.id))==null?void 0:j.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 y=window.setTimeout(()=>{p(k=>!k||k.startedAt!==l.startedAt?k:(o("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(y)},[l]);const g=a.useCallback(async(y,k)=>{if(k.kind==="ide"&&k.providerType){await x(y,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await w(y,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[x,w]);return{machineAction:{state:i,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:v,handleMachineUpgrade:f,handleLaunchWorkspaceProvider:w,handleListSavedSessions:m,handleBrowseDirectory:C,handleOpenRecent:g}}function kd({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:i,setSelectedTabKey:o,setScreen:c,setSelectedMachineId:d,setSection:l,setMachineBackTarget:p}){const u=a.useCallback(g=>{o(g.tabKey),c("chat"),n(g)},[n,c,o]),x=a.useCallback(g=>{const y=t.find(k=>k.ideId===g.ideId&&k.streamSource==="native");y&&(o(y.tabKey),c("chat"),n(y))},[t,n,c,o]),v=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),f=a.useCallback((g,y="inbox")=>{d(g),i(),l("machines"),p(y),c("machine")},[i,p,c,l,d]),w=a.useCallback(g=>{const y=Pt(g);y&&f(y,"chat")},[f]),m=a.useCallback(()=>{i(),c(r)},[r,i,c]),C=a.useCallback(g=>{l(g),c("inbox")},[c,l]);return{openConversation:u,openNativeConversation:x,backFromConversation:v,openMachine:f,openConversationMachine:w,backFromMachine:m,changeMachineSection:C}}function Nd(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function Sd(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 Cd({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,userName:l,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:v,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,onOpenHistory:m,onOpenRemote:C,onStopCli:g,wsStatus:y,isConnected:k,onShowHiddenConversation:I,onShowAllHiddenConversations:j,onHideConversation:h,onOpenNewSession:b}){const[S,N]=a.useState(()=>{var A;return((A=t[0])==null?void 0:A.tabKey)||null}),[E,D]=a.useState(()=>t[0]?"chat":"inbox"),[O,T]=a.useState("chats"),[L,_]=a.useState(null),[R,B]=a.useState("inbox"),Y=ds(),K="0.8.35",$=a.useMemo(()=>t.find(A=>A.tabKey===S)||t[0]||null,[t,S]),W=a.useMemo(()=>$?r.find(A=>A.id===$.ideId):void 0,[r,$]),F=a.useMemo(()=>!$||De($)||!Be($)?null:ls($),[$]),V=a.useMemo(()=>r.filter(A=>A.type==="adhdev-daemon"||A.daemonMode).sort(Kr),[r]),te=a.useMemo(()=>V.find(A=>A.id===L)||null,[V,L]),ke=a.useMemo(()=>_s(r),[r]),J=sr({sendDaemonCommand:i,activeConv:$||void 0,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),Z=jd({sendDaemonCommand:i,navigate:Y,ides:r,conversations:t}),q=a.useMemo(()=>t.map(A=>{const G=E==="chat"&&($==null?void 0:$.tabKey)===A.tabKey,z=Ns(A,ke,{hideOpenTaskCompleteUnread:!0,isOpenConversation:G}),ae=Ft(A),de=La(A);return{conversation:A,timestamp:ae,preview:de,unread:z.unread,requiresAction:z.requiresAction,isWorking:z.isWorking,inboxBucket:z.inboxBucket}}),[t,ke,E,$]),{markConversationRead:xe}=yd({conversations:t,machineEntries:V,items:q,selectedConversation:$,selectedTabKey:S,screen:E,liveSessionInboxState:ke,sendDaemonCommand:i,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:v,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,setSelectedTabKey:N,setScreen:D,setSelectedMachineId:_,setSection:T,setMachineBackTarget:B,resetMachineAction:Z.resetMachineAction}),re=kd({conversations:t,selectedConversation:$,machineBackTarget:R,markConversationRead:xe,resetMachineAction:Z.resetMachineAction,setSelectedTabKey:N,setScreen:D,setSelectedMachineId:_,setSection:T,setMachineBackTarget:B}),he=a.useMemo(()=>q.filter(A=>A.requiresAction),[q]),ve=a.useMemo(()=>q.filter(A=>A.unread&&!A.requiresAction),[q]),ie=a.useMemo(()=>q.filter(A=>!A.unread&&!A.requiresAction&&A.isWorking),[q]),pe=a.useMemo(()=>q.filter(A=>!A.unread&&!A.requiresAction&&!A.isWorking),[q]),oe=a.useMemo(()=>te?q.filter(A=>Pt(A.conversation)===te.id):[],[q,te]),ge=a.useMemo(()=>bd(te,r),[r,te]),X=(te==null?void 0:te.version)||null,se=!!te&&!!X&&!0&&X!==K,Q=a.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),fe=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(()=>gd(V,q),[q,V]),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(dd,{selectedConversation:$,isAcp:De($),isStandalone:d,selectedIdeEntry:W,actionLogs:n,userName:l,isSendingChat:J.isSendingChat,isFocusingAgent:J.isFocusingAgent,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,onBack:re.backFromConversation,onOpenNativeConversation:re.openNativeConversation,onOpenMachine:re.openConversationMachine,onHideConversation:h,onOpenHistory:m,onOpenRemote:C,onStopCli:g,cliViewMode:F,onSetCliViewMode:async A=>{if($&&F!==A)try{await i(Pt($)||$.ideId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:Xt($),mode:A})}catch(G){Sd(G)?console.warn("Skipped CLI view mode switch:",G instanceof Error?G.message:String(G)):console.error("Failed to switch CLI view mode:",G)}},handleSendChat:J.handleSendChat,handleFocusAgent:J.handleFocusAgent}):E==="machine"&&te?e.jsx(hd,{selectedMachineEntry:te,selectedMachineConversations:oe,selectedMachineRecentLaunches:ge,cliProviders:fe,acpProviders:M,selectedMachineNeedsUpgrade:se,appVersion:K,machineAction:Z.machineAction,isStandalone:d,section:O,showBottomNav:R==="inbox",onBack:re.backFromMachine,onSectionChange:re.changeMachineSection,onOpenConversation:re.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>Y(`/machines/${te.id}`),onMachineUpgrade:()=>Z.handleMachineUpgrade(te.id),onLaunchDetectedIde:(A,G)=>Z.handleLaunchDetectedIde(te.id,A,G),onAddWorkspace:(A,G)=>Z.handleAddWorkspace(te.id,A,G),onBrowseDirectory:A=>Z.handleBrowseDirectory(te.id,A),onLaunchWorkspaceProvider:(A,G,z)=>Z.handleLaunchWorkspaceProvider(te.id,A,G,z),onListSavedSessions:A=>Z.handleListSavedSessions(te.id,A)}):e.jsx(md,{section:O,attentionItems:he,unreadItems:ve,workingItems:ie,completedItems:pe,hiddenConversations:s,machineCards:ee,getAvatarText:Nd,onOpenConversation:re.openConversation,onShowConversation:I,onShowAllHidden:j,onOpenNewSession:b,onOpenMachine:re.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:T,wsStatus:y,isConnected:k,isStandalone:d})})}function hr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Id({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:i,onClearPreviewOrder:o}){const c=a.useRef(0),[d,l]=a.useState(!1),[p,u]=a.useState(null),x=a.useCallback(()=>{c.current=0,l(!1),u(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const v=a.useCallback(C=>{C.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,l(!0))},[]),f=a.useCallback(C=>{if(!C.dataTransfer.types.includes("text/tab-key"))return;if(C.preventDefault(),!hr(s,r)){u("merge");return}const g=C.currentTarget.getBoundingClientRect(),y=C.clientX-g.left,k=g.width/3;y<k?u("split-left"):y>k*2?u("split-right"):u("merge")},[s,r]),w=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,l(!1),u(null))},[]),m=a.useCallback(C=>{c.current=0,l(!1);const g=C.dataTransfer.getData("text/tab-key"),y=g?t.some(I=>I.tabKey===g):!1,k=p;if(u(null),o(),!!g){if(C.preventDefault(),k==="split-left"&&hr(s,r)){r==null||r(g,"split-left");return}if(k==="split-right"&&hr(s,r)){r==null||r(g,"split-right");return}if(y){i(g);return}n==null||n(g)}},[t,p,s,r,n,i,o]);return{dragOver:d,dropAction:p,resetDragState:x,handleDragEnter:v,handleDragOver:f,handleDragLeave:w,handleDrop:m}}function Td(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 _d({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:i}){const[o,c]=a.useState(s??null),[d,l]=a.useState(r??[]),[p,u]=a.useState(null),x=a.useRef(null),v=a.useRef(null),f=a.useRef(n),w=a.useRef(i);a.useEffect(()=>{f.current=n},[n]),a.useEffect(()=>{w.current=i},[i]),a.useEffect(()=>{s&&s!==o&&c(s)},[s,o]),a.useEffect(()=>{l(b=>{const S=Td(b,t);return S.length===b.length&&S.every((N,E)=>N===b[E])?b:S})},[t]);const m=a.useMemo(()=>{const b=p??d;if(b.length===0)return t;const S=new Map(b.map((N,E)=>[N,E]));return[...t].sort((N,E)=>{const D=S.get(N.tabKey)??999,O=S.get(E.tabKey)??999;return D-O})},[t,p,d]);a.useEffect(()=>{var S,N;if(m.length===0){o!==null&&(c(null),(S=f.current)==null||S.call(f,null));return}if(o&&m.some(E=>E.tabKey===o))return;const b=m[0].tabKey;b!==o&&(c(b),(N=f.current)==null||N.call(f,b))},[m,o]);const C=a.useMemo(()=>m.find(b=>b.tabKey===o),[m,o]),g=a.useCallback(b=>{var S;c(b),(S=f.current)==null||S.call(f,b)},[]),y=a.useCallback((b,S,N)=>{l(E=>{var L;const D=E.filter(_=>_!==b),O=D.indexOf(S);if(O<0)return E;const T=N==="left"?O:O+1;return D.splice(T,0,b),(L=w.current)==null||L.call(w,D),D}),u(null)},[]),k=a.useCallback((b,S,N)=>{const D=(d.length>0?d:t.map(L=>L.tabKey)).filter(L=>L!==b),O=D.indexOf(S);if(O<0)return;const T=N==="left"?O:O+1;D.splice(T,0,b),x.current=D,u(D)},[d,t]),I=a.useCallback(()=>{var S;const b=x.current;b&&(l(b),(S=w.current)==null||S.call(w,b))},[]),j=a.useCallback(()=>{x.current=null,u(null)},[]),h=a.useCallback(b=>{l(S=>{var E;const N=S.filter(D=>D!==b);return N.push(b),(E=w.current)==null||E.call(w,N),N})},[]);return{activeTabId:o,activeConv:C,sortedConversations:m,previewOrderRef:x,draggingTabRef:v,selectTab:g,handleTabReorder:y,updatePreviewOrder:k,commitPreviewOrder:I,clearPreviewOrder:j,moveTabToEnd:h,setDraggingTabKey:b=>{v.current=b}}}function Ad({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 Jr({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(ri,{}),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(ha,{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 ii="adhdev-tab-shortcuts";function Md(){try{return JSON.parse(localStorage.getItem(ii)||"{}")}catch{return{}}}function oi({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const i=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=a.useState(()=>Md()),[d,l]=a.useState(null),p=a.useCallback(x=>{const v=[];return x.metaKey&&v.push(i?"⌘":"Meta"),x.ctrlKey&&v.push("Ctrl"),x.altKey&&v.push(i?"⌥":"Alt"),x.shiftKey&&v.push(i?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(v.push(x.key.length===1?x.key.toUpperCase():x.key),v.join("+"))},[i]),u=a.useCallback(x=>{c(x);try{localStorage.setItem(ii,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const x=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){l(null);return}const f=p(v);if(!f)return;const w={...o};for(const[m,C]of Object.entries(w))C===f&&delete w[m];w[d]=f,u(w),l(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[t,d,o,u,p]),a.useEffect(()=>{if(!t)return;const x=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[f,w]of Object.entries(o))if(s.includes(f)&&p(v)===w){v.preventDefault(),r(),n(f);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,o,s,r,n,p]),{isMac:i,tabShortcuts:o,shortcutListening:d,setShortcutListening:l,saveShortcuts:u}}const Ld=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:i,shortcut:o,conversationKeys:c,draggingTabRef:d,onFocus:l,onSelectTab:p,onConversationActivated:u,onPreviewReorder:x,onReorderTab:v,onCommitPreviewOrder:f,onClearPreviewOrder:w,onDragStateReset:m,onDragTabKeyChange:C,onReceiveTab:g,onOpenContextMenu:y,longPressTimer:k,isGroupActive:I}){const j=ms(s),h=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",b=j.isReconnecting,S=a.useCallback(B=>{d.current=s.tabKey,C(s.tabKey),B.dataTransfer.setData("text/tab-key",s.tabKey),B.dataTransfer.effectAllowed="move"},[s.tabKey,d,C]),N=a.useCallback(()=>{d.current=null,C(null),f(),w(),m()},[d,C,f,w,m]),E=a.useCallback(B=>{const Y=d.current;if(!(!Y||Y===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";x(Y,s.tabKey,$)}},[s.tabKey,d,x]),D=a.useCallback(B=>{B.preventDefault(),B.stopPropagation();const Y=B.dataTransfer.getData("text/tab-key");if(Y&&Y!==s.tabKey){const K=B.currentTarget.getBoundingClientRect(),$=B.clientX<K.left+K.width/2?"left":"right";c.includes(Y)?v(Y,s.tabKey,$):g&&g(Y)}w()},[s.tabKey,c,v,g,w]),O=a.useCallback(B=>{B.stopPropagation(),l(),p(s.tabKey),u(s)},[s,u,l,p]),T=a.useCallback(B=>{B.preventDefault(),y(B.clientX,B.clientY,s.tabKey)},[s.tabKey,y]),L=a.useCallback(B=>{const Y=B.touches[0];k.current=setTimeout(()=>{y(Y.clientX,Y.clientY,s.tabKey)},600)},[s.tabKey,k,y]),_=a.useCallback(()=>{k.current&&clearTimeout(k.current)},[k]),R=["adhdev-dockview-tab",h,r&&"is-active",I&&"is-group-active",b&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:R,draggable:!0,onDragStart:S,onDragEnd:N,onDragOver:E,onDrop:D,onClick:O,onContextMenu:T,onTouchStart:L,onTouchEnd:_,onTouchMove:_,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:j.isGenerating?e.jsx("div",{className:"tab-spinner"}):j.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):b?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:Fe(s),children:Fe(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:b?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:is(s)}):j.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[is(s),e.jsx("span",{className:"connecting-dots"})]}):is(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 Pd({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:v,onDragTabKeyChange:f,onReceiveTab:w,onHideTab:m,isGroupActive:C,allowTabShortcuts:g=!0}){const[y,k]=a.useState(null),I=a.useRef(null),j=a.useRef(null),h=a.useMemo(()=>t.map(T=>T.tabKey),[t]);Ts("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:b,tabShortcuts:S,shortcutListening:N,setShortcutListening:E,saveShortcuts:D}=oi({enabled:g,sortedTabKeys:t.map(T=>T.tabKey),onFocus:o,onSelectTab:c});a.useEffect(()=>{if(!y)return;const T=L=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(L.target)||k(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[y]),a.useEffect(()=>{const T=j.current;if(!T)return;const L=_=>{Math.abs(_.deltaY)>Math.abs(_.deltaX)&&(_.preventDefault(),T.scrollLeft+=_.deltaY)};return T.addEventListener("wheel",L,{passive:!1}),()=>T.removeEventListener("wheel",L)},[]);const O=a.useCallback((T,L,_)=>{k({x:T,y:L,tabKey:_})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(T=>e.jsx(Ld,{conv:T,isActive:s===T.tabKey,isDraggedTab:i.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:g?S[T.tabKey]:void 0,conversationKeys:h,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:v,onDragTabKeyChange:f,onReceiveTab:w,onOpenContextMenu:O,longPressTimer:I,isGroupActive:C},T.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),y&&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:y.x,top:y.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:T=>{T.stopPropagation(),E(y.tabKey),k(null)},children:["⌨ ",S[y.tabKey]?`Change shortcut (${S[y.tabKey]})`:"Set shortcut"]}),S[y.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 T={...S};delete T[y.tabKey],D(T),k(null)},children:"✕ Remove shortcut"})]}),m&&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:()=>{m(y.tabKey),k(null)},children:"🚫 Hide from Dashboard"})]})]}),g&&N&&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:T=>T.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. ",b?"⌘+1":"Ctrl+1",", ",b?"⌥+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 Rd({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,hasRegisteredMachines:l,userName:p,groupIndex:u,onFocus:x,isSplitMode:v,numGroups:f,onMoveTab:w,onReceiveTab:m,style:C,detectedIdes:g,handleLaunchIde:y,onActiveTabChange:k,initialActiveTabId:I,initialTabOrder:j,onTabOrderChange:h,onHideTab:b,isFocused:S,allowTabShortcuts:N=!0}){const{sendCommand:E}=Rt(),D=a.useRef(null),{activeTabId:O,activeConv:T,sortedConversations:L,draggingTabRef:_,selectTab:R,handleTabReorder:B,updatePreviewOrder:Y,commitPreviewOrder:K,clearPreviewOrder:$,moveTabToEnd:W,setDraggingTabKey:F}=_d({conversations:t,initialActiveTabId:I,initialTabOrder:j,onActiveTabChange:k,onTabOrderChange:h}),V=sr({sendDaemonCommand:i,activeConv:T,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),{dragOver:te,dropAction:ke,resetDragState:J,handleDragEnter:Z,handleDragOver:q,handleDragLeave:xe,handleDrop:re}=Id({conversations:t,numGroups:f,onMoveTab:w,onReceiveTab:m,onOwnTabDrop:W,onClearPreviewOrder:$}),he=T&&!De(T)&&ls(T)==="terminal",ve=a.useMemo(()=>T?s.find(X=>X.id===T.ideId):void 0,[s,T]),ie=a.useMemo(()=>T?n.filter(X=>X.ideId===T.tabKey):[],[n,T]),pe=a.useMemo(()=>_s(s),[s]),oe=a.useMemo(()=>new Set(L.filter(X=>zo(X,pe,{isOpenConversation:X.tabKey===O})).map(X=>X.tabKey)),[O,pe,L]);Ts("PaneGroup",{groupIndex:u,conversationCount:t.length,activeTabId:O,dragOver:te});const ge=a.useCallback(X=>{X.streamSource==="agent-stream"&&X.agentType&&E(X.ideId,"focus_session",{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...C,outline:te?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(Pd,{conversations:L,activeTabId:O,groupIndex:u,numGroups:f,unreadTabKeys:oe,draggingTabRef:_,onFocus:x,onSelectTab:R,onConversationActivated:ge,onPreviewReorder:Y,onReorderTab:B,onCommitPreviewOrder:K,onClearPreviewOrder:$,onDragStateReset:J,onDragTabKeyChange:F,onMoveTab:w,onReceiveTab:m,onHideTab:b,isGroupActive:S??!1,allowTabShortcuts:N}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Z,onDragOver:q,onDragLeave:xe,onDrop:re,children:[te&&e.jsx(Ad,{dropAction:ke,canSplit:!!(f<4&&w)}),T?e.jsx(Yr,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!he,ideEntry:ve,terminalRef:D,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:ie,userName:p,isInputActive:!v||!!S}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Jr,{conversationsCount:t.length,isSplitMode:v,isStandalone:d,hasRegisteredMachines:l,detectedIdes:g,handleLaunchIde:y})})]})]})}function Ed({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:i,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:p,setActionLogs:u,isStandalone:x,hasRegisteredMachines:v,userName:f,focusedGroup:w,setFocusedGroup:m,moveTabToGroup:C,splitTabRelative:g,closeGroup:y,handleResizeStart:k,detectedIdes:I,handleLaunchIde:j,groupActiveTabIds:h,setGroupActiveTabIds:b,groupTabOrders:S,setGroupTabOrders:N,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,T)=>{const L=s&&n.length===r?`${n[T]}%`:void 0;return e.jsxs(Ve.Fragment,{children:[s&&T>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:_=>k(T-1,_),onDoubleClick:()=>y(T),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(Rd,{style:s?{flexBasis:L??`${100/r}%`,flexGrow:L?0:1,flexShrink:L?0:1}:void 0,conversations:O,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:p,setActionLogs:u,isStandalone:x,hasRegisteredMachines:v,userName:f,groupIndex:T,isFocused:s&&w===T,onFocus:()=>m(T),isSplitMode:s,numGroups:r,onMoveTab:(_,R)=>{R==="left"&&T>0?C(_,T-1):R==="right"&&T<r-1?C(_,T+1):R==="split-left"&&r<4?g(_,T,"left"):R==="split-right"&&r<4&&g(_,T,"right")},onReceiveTab:_=>C(_,T),detectedIdes:T===0?I:void 0,handleLaunchIde:T===0?j:void 0,onActiveTabChange:_=>b(R=>(R[T]??null)===(_??null)?R:{...R,[T]:_}),initialActiveTabId:h[T],initialTabOrder:S[T],onTabOrderChange:_=>N(R=>{const B=R[T]||[];return B.length===_.length&&B.every((Y,K)=>Y===_[K])?R:{...R,[T]:_}}),onHideTab:E,allowTabShortcuts:D})]},T)})})}function ci({doId:t,ideId:s,ideType:r,connState:n,viewMode:i,instanceId:o}){const[c,d]=a.useState(null),[l,p]=a.useState(null),u=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?He.onScreenshot("ide-page",(f,w)=>{if(f!==t)return;const m=new FileReader;m.onload=()=>d(m.result),m.readAsDataURL(w)}):void 0,[t]),a.useEffect(()=>{n!=="connected"&&d(null)},[n]),a.useEffect(()=>{var f;return t?((f=He.onStatus)==null?void 0:f.call(He,(w,m)=>{w===t&&m!=null&&m.screenshotUsage&&p(m.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{d(null)},[t,s,u]),a.useEffect(()=>{const v=t?He.get(t):null;if(!(!v||n!=="connected"))return i!=="chat"&&u?v.startScreenshots(u):v.stopScreenshots(u),()=>{v.stopScreenshots(u)}},[i,n,u,t]);const x=a.useCallback(async(v,f)=>{const w=t?He.get(t):null;return!w||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):w.sendInput(v,f,o||u)},[t,n,o,u]);return{connScreenshot:c,screenshotUsage:l,handleRemoteAction:x}}const li=a.createContext(null);function ir(){const t=a.useContext(li);if(!t)throw new Error("DashboardDockviewContext missing");return t}function Vs(t){return Fe(t)||t.tabKey}function $d(t){return`remote:${t}`}function Is(t){return t.startsWith("remote:")}function Dd(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 Bd(t,s,r){var d;const n=[s];let i;for(const l of n){let p;for(const u of l){const x=t.addPanel({id:u.tabKey,component:"conversation",title:Vs(u),params:{kind:"conversation",tabKey:u.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:i?{position:{referencePanel:i,direction:"right"},inactive:!0}:{}});p||(p=x.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 Fn(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Is(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!==Vs(n)&&i.api.setTitle(Vs(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:Vs(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?$d(r):null;for(const u of[...t.panels])Is(u.id)&&(!n||u.id!==n)&&t.removePanel(u);if(!r||!n)return;const i=Mt(s,r);if(!i&&t.totalPanels===0)return;const o=t.getPanel(n),c=kc(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(u=>!Is(u.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 Kd({params:t,api:s}){var x;const r=ir(),n=a.useRef(null),[i,o]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=sr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{o(s.isActive);const v=[s.onDidActiveChange(f=>o(f.isActive)),s.onDidActiveGroupChange(f=>{if(!s.isActive&&!f.isActive){o(!1);return}o(s.isActive)})];return()=>{for(const f of v)f.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(Jr,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const u=!De(c)&&ls(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Yr,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,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:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:i})})}function Wd({params:t}){var l;const s=ir(),r=a.useMemo(()=>Mt([...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}=ci({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(ya,{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 Od(){const t=ir();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Jr,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function zd(t){var f,w;Dd(t);const s=ir(),r=a.useCallback(m=>{"button"in m&&m.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const m=Mt([...s.conversationsByTabKey.values()],t.params.ideId),C=((f=t.api.group.activePanel)==null?void 0:f.id)===t.api.id,g=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${C?" is-active":""}${g?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(m==null?void 0:m.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:m!=null&&m.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:m.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=Ns(n,s.liveSessionInboxState,{isOpenConversation:i}),d=c.isReconnecting,l=c.isConnecting,p=c.isGenerating,u=c.isWaiting,x=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:Fe(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:m=>{m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey})},children:[x&&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"}):u?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:Fe(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:is(n)}):l?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:is(n)}):e.jsx("span",{children:is(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 Ud({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,hasRegisteredMachines:l,initialDataLoaded:p,userName:u,detectedIdes:x,handleLaunchIde:v,toggleHiddenTab:f,registerActionHandlers:w,onActiveTabChange:m,requestedActiveTabKey:C,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:y,scrollToBottomRequest:k}){const{theme:I}=Vr(),{sendCommand:j}=Rt(),h=a.useRef(null),b=a.useRef(null),S=a.useRef(!1),N=a.useRef(!1),E=a.useRef(!1),D=a.useRef(null),[O,T]=a.useState(null),[L,_]=a.useState(!1),[R,B]=a.useState(!1),Y=a.useRef(null),K=a.useMemo(()=>ei(typeof window<"u"?window.innerWidth:1280),[]),$=a.useMemo(()=>new Map(t.map(A=>[A.tabKey,A])),[t]),W=a.useMemo(()=>_s(r),[r]),F=a.useCallback(()=>{var A;(A=h.current)==null||A.focus()},[]),V=a.useCallback(A=>{const G=h.current;if(!G)return;const z=G.getPanel(A);z&&(z.group.model.openPanel(z),z.api.setActive())},[]),te=a.useCallback(A=>{const G=h.current,z=G==null?void 0:G.activePanel,ae=(G==null?void 0:G.activeGroup)||(z==null?void 0:z.group);if(!G||!z||!ae)return;const de=ae.panels||[];if(de.length<=1)return;const Ce=de.findIndex(ze=>ze.id===z.id);if(Ce<0)return;const Ee=(Ce+A+de.length)%de.length,Le=de[Ee];Le&&(Le.group.model.openPanel(Le),Le.api.setActive())},[]),ke=a.useCallback(A=>{var at;const G=h.current,z=(G==null?void 0:G.activeGroup)||((at=G==null?void 0:G.activePanel)==null?void 0:at.group);if(!G||!z)return;const ae=G.groups||[],de=ae.find(Re=>Re.id===z.id);if(!de)return;const Ce=de.element.getBoundingClientRect(),Ee=Ce.left+Ce.width/2,Le=Ce.top+Ce.height/2,ze=(Re,Ie,Je,qe)=>Math.max(0,Math.min(Ie,qe)-Math.max(Re,Je)),lt=Re=>{const Ie=Re.element.getBoundingClientRect(),Je=Ie.left+Ie.width/2,qe=Ie.top+Ie.height/2;let H=0,we=0,Ne=0,Pe=!1;if(A==="left"?(Pe=Je<Ee,H=Math.max(0,Ce.left-Ie.right),we=Math.abs(qe-Le),Ne=ze(Ce.top,Ce.bottom,Ie.top,Ie.bottom)):A==="right"?(Pe=Je>Ee,H=Math.max(0,Ie.left-Ce.right),we=Math.abs(qe-Le),Ne=ze(Ce.top,Ce.bottom,Ie.top,Ie.bottom)):A==="above"?(Pe=qe<Le,H=Math.max(0,Ce.top-Ie.bottom),we=Math.abs(Je-Ee),Ne=ze(Ce.left,Ce.right,Ie.left,Ie.right)):(Pe=qe>Le,H=Math.max(0,Ie.top-Ce.bottom),we=Math.abs(Je-Ee),Ne=ze(Ce.left,Ce.right,Ie.left,Ie.right)),!Pe)return Number.POSITIVE_INFINITY;const Ge=Ne>0?0:120;return H*3+we+Ge};let Xe=null,We=Number.POSITIVE_INFINITY;for(const Re of ae){if(Re.id===de.id)continue;const Ie=lt(Re);Number.isFinite(Ie)&&(Ie>=We||(We=Ie,Xe=Re))}return Xe||void 0},[]),J=a.useCallback(A=>{const G=ke(A);if(!G)return;const z=G.activePanel||G.panels[0];z&&(G.model.openPanel(z),z.api.setActive())},[ke]),Z=a.useCallback((A,G)=>{const z=h.current,ae=z==null?void 0:z.activePanel,de=(z==null?void 0:z.activeGroup)||(ae==null?void 0:ae.group);if(!z||!ae||!de)return;let Ce=ke(A);!Ce&&(G!=null&&G.createGroupIfMissing)&&(Ce=z.addGroup({referenceGroup:de,direction:A})),Ce&&(ae.api.moveTo({group:Ce,position:"center"}),ae.group.model.openPanel(ae),ae.api.setActive())},[ke]),{isMac:q,tabShortcuts:xe,shortcutListening:re,setShortcutListening:he,saveShortcuts:ve}=oi({sortedTabKeys:t.map(A=>A.tabKey),onFocus:F,onSelectTab:V}),ie=a.useCallback(()=>{var z;const A=h.current;if(!A)return;const G=A.activePanel;if(G){if(Is(G.id)){const ae=((z=G.params)==null?void 0:z.ideId)||G.id.slice(7),de=Mt(t,ae);de!=null&&de.tabKey&&he(de.tabKey);return}$.has(G.id)&&he(G.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:()=>J("left"),focusRightPane:()=>J("right"),focusUpPane:()=>J("above"),focusDownPane:()=>J("below"),moveActiveTabToLeftPane:()=>Z("left"),moveActiveTabToRightPane:()=>Z("right"),moveActiveTabToUpPane:()=>Z("above"),moveActiveTabToDownPane:()=>Z("below")}),()=>w==null?void 0:w(null)),[te,J,Z,w,ie]),a.useEffect(()=>{if(!O)return;const A=G=>{const z=document.querySelector("[data-dockview-tab-context-menu]");z&&z.contains(G.target)||T(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[O]);const pe=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:$,detectedIdes:x,handleLaunchIde:v,ides:r,isStandalone:d,hasRegisteredMachines:l,liveSessionInboxState:W,sendDaemonCommand:i,setActionLogs:c,setLocalUserMessages:o,toggleHiddenTab:f,userName:u,scrollToBottomRequest:k,tabShortcuts:xe,openTabContextMenu:({x:A,y:G,tabKey:z})=>T({x:A,y:G,tabKey:z})}),[n,s,$,x,v,r,d,l,W,i,c,o,f,u,k,xe]),oe=a.useCallback(A=>{if(!A)return!1;const G=h.current;if(!G)return!1;const z=G.getPanel(A);return z?(z.group.model.openPanel(z),z.api.setActive(),y==null||y(),!0):!1},[y]),ge=a.useCallback(()=>{if(E.current)return!1;const A=oe(D.current);return A&&(E.current=!0),A},[oe]),X=a.useCallback(()=>{var G;const A=h.current;A&&Zl(K,{activeTabId:((G=A.activePanel)==null?void 0:G.id)??null,layout:A.toJSON()})},[K]),se=a.useCallback(()=>{const A=b.current;if(!A)return;const G=A.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const z of G)z.setAttribute("data-adhdev-force-hidden","true")},[]),Q=a.useCallback(()=>{const A=b.current;if(!A)return;const G=A.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const z of G)z.removeAttribute("data-adhdev-force-hidden")},[]),fe=a.useCallback(()=>{const A=b.current;if(!A)return;const G=A.querySelectorAll(".dv-drop-target-container");for(const de of G)de.remove();const z=A.querySelectorAll(".dv-drop-target-dropzone");for(const de of z)de.remove();const ae=A.querySelectorAll(".dv-drop-target");for(const de of ae)de.classList.remove("dv-drop-target")},[]),M=a.useCallback(()=>{_(!1),B(!1),Q(),se(),fe(),!(typeof window>"u")&&(Y.current!=null&&window.clearTimeout(Y.current),window.requestAnimationFrame(()=>{se(),fe()}),Y.current=window.setTimeout(()=>{se(),fe(),Y.current=null},80))},[Q,se,fe]),ee=a.useCallback(A=>{var z;h.current=A.api;const G=Jl(K);D.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&A.api.fromJSON(G.layout,{reuseExistingPanels:!1}),N.current=!!(G!=null&&G.layout)&&!p&&t.length===0,N.current||(Fn(A.api,t),Vn(A.api,t,g)),A.api.totalPanels===0&&t.length>0?Bd(A.api,t,C):!N.current&&!oe(C)&&ge(),S.current=!0,A.api.onDidActivePanelChange(ae=>{var Ce;if(D.current=(ae==null?void 0:ae.id)??null,E.current=!0,ae&&Is(ae.id)){const Ee=((Ce=ae.params)==null?void 0:Ce.ideId)||ae.id.slice(7),Le=Mt(t,Ee);m((Le==null?void 0:Le.tabKey)??null),X();return}if(m((ae==null?void 0:ae.id)??null),X(),!ae)return;const de=$.get(ae.id);(de==null?void 0:de.streamSource)==="agent-stream"&&de.agentType&&j(de.ideId,"focus_session",{agentType:de.agentType,...de.sessionId&&{targetSessionId:de.sessionId}}).catch(()=>{})}),A.api.onDidLayoutChange(()=>{X()}),A.api.onWillDragPanel(()=>{_(!0),B(!1),se()}),A.api.onWillDragGroup(()=>{_(!0),B(!1),se()}),A.api.onWillShowOverlay(()=>{Q(),B(!0)}),A.api.onDidMovePanel(M),A.api.onDidDrop(M),m(((z=A.api.activePanel)==null?void 0:z.id)??null)},[oe,M,Q,$,p,K,se,fe,m,X,C,g,j,t]);a.useEffect(()=>{const A=h.current;if(!A||!S.current||N.current&&!p||(N.current&&(N.current=!1),Fn(A,t),Vn(A,t,g),C&&oe(C)))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,C,g,t]),a.useEffect(()=>{S.current&&oe(C)},[oe,C]),a.useEffect(()=>{if(!L||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,L]),a.useEffect(()=>()=>{typeof window>"u"||Y.current!=null&&window.clearTimeout(Y.current)},[]),a.useEffect(()=>{const A=G=>{const z=G.target;if(!z)return;const ae=z.querySelector("[data-tab-key]")||z.closest("[data-tab-key]");if(ae){const de=ae.getAttribute("data-tab-key");de&&G.dataTransfer&&G.dataTransfer.setData("text/tab-key",de)}};return window.addEventListener("dragstart",A),()=>window.removeEventListener("dragstart",A)},[]);const ye=I==="light"?Fi:Vi;return e.jsxs(li.Provider,{value:pe,children:[e.jsx("div",{ref:b,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Hi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${L?" is-dragging-dockview":""}${R?" is-showing-dockview-overlay":""}`,components:{conversation:Kd,remote:Wd},defaultTabComponent:zd,watermarkComponent:Od,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),T(null)},children:["⌨ ",xe[O.tabKey]?`Change shortcut (${xe[O.tabKey]})`:"Set shortcut"]}),xe[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={...xe};delete A[O.tabKey],ve(A),T(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. ",q?"⌘+1":"Ctrl+1",", ",q?"⌥+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 di="adhdev-recent-launch-args-v1",Hd=8;function Fd(t){return String(t||"").trim().replace(/\s+/g," ")}function ui(t,s){return`${t.trim()}::${s.trim()}`}function mi(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(di)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Vd(t){if(!(typeof window>"u"))try{window.localStorage.setItem(di,JSON.stringify(t))}catch{}}function pi(t,s){var o;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((o=mi().byKey[ui(r,n)])==null?void 0:o.items)||[]}function fi(t,s,r){var u;const n=String(t||"").trim(),i=String(s||"").trim(),o=Fd(r);if(!n||!i||!o)return;const c=mi(),d=ui(n,i),l=((u=c.byKey[d])==null?void 0:u.items)||[],p=[o,...l.filter(x=>x!==o)].slice(0,Hd);c.byKey[d]={items:p},Vd(c)}function br(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Gd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Gn(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 qd(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Yd(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 Xd(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 Jd(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 Zd({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,u]=a.useState(null),[x,v]=a.useState(!0),[f,w]=a.useState(""),[m,C]=a.useState(null);a.useEffect(()=>{var T;l(n||((T=t[0])==null?void 0:T.id)||null)},[n,t]);const g=a.useMemo(()=>t.find(T=>T.id===d)||t[0]||null,[d,t]),y=a.useMemo(()=>r.filter(T=>{if(T.daemonMode||T.transport!=="pty")return!1;const L=Gd(T.daemonId||T.id);return!!(g!=null&&g.id)&&L===g.id}),[g==null?void 0:g.id,r]),k=a.useMemo(()=>{const T=new Map;for(const L of y){const _=s.find(R=>R.sessionId===L.sessionId||R.ideId===L.id);L.sessionId&&_&&T.set(L.sessionId,_)}return T},[y,s]),I=a.useCallback(async T=>{if(g!=null&&g.id){T!=null&&T.silent||v(!0);try{const L=await i(g.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),_=br(L);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Could not load session host diagnostics");u(_.diagnostics||_.result||null),w("")}catch(L){const _=L instanceof Error?L.message:"Could not load session host diagnostics";w(_)}finally{T!=null&&T.silent||v(!1)}}},[g==null?void 0:g.id,i]);a.useEffect(()=>{I();const T=window.setInterval(()=>{I({silent:!0})},1e4);return()=>window.clearInterval(T)},[I]);const j=a.useCallback(async(T,L)=>{if(!(g!=null&&g.id)||T==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
41
- This will terminate the hosted runtime.`))return;const _=`${T}:${L.sessionId}`;C(_);try{const R=await i(g.id,T,{sessionId:L.sessionId}),B=br(R);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Session host action failed");const Y=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${Y}: ${L.displayName}`,"success"),await I({silent:!0})}catch(R){const B=R instanceof Error?R.message:"Session host action failed";w(B),nt.showToast(B,"warning")}finally{C(R=>R===_?null:R)}},[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.`))){C("session_host_prune_duplicate_sessions");try{const L=await i(g.id,"session_host_prune_duplicate_sessions",{}),_=br(L);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Duplicate prune failed");const R=_.result||{},B=Array.isArray(R.prunedSessionIds)?R.prunedSessionIds.length:0,Y=typeof R.duplicateGroupCount=="number"?R.duplicateGroupCount:0;nt.showToast(`Pruned ${B} duplicate runtime(s) across ${Y} group(s)`,"success"),await I({silent:!0})}catch(L){const _=L instanceof Error?L.message:"Duplicate prune failed";w(_),nt.showToast(_,"warning")}finally{C(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[g==null?void 0:g.id,I,i]),b=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((T,L)=>(L.lastActivityAt||0)-(T.lastActivityAt||0)),[p==null?void 0:p.sessions]),S=a.useMemo(()=>Jd(b),[b]),N=a.useMemo(()=>b.reduce((T,L)=>{var _;return T+(((_=L.attachedClients)==null?void 0:_.length)||0)},0),[b]),E=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.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:T=>T.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(Lt,{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:x,"aria-label":"Refresh session host",children:e.jsx(us,{size:16})}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close session host",children:e.jsx(ft,{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(T=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${T.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(T.id),children:T.label},T.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:[f&&!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(qt,{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:f})]})]})}),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:N})]}),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:Gn(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(qt,{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(Zs,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:m==="session_host_prune_duplicate_sessions",onClick:()=>{h()},children:m==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${S}`}),e.jsxs("div",{className:"text-[11px] text-text-secondary",children:[y.length," dashboard session",y.length===1?"":"s"]})]})]}),b.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:b.map(T=>{var W,F;const L=k.get(T.sessionId),_=y.find(V=>V.sessionId===T.sessionId),R=m===`session_host_resume_session:${T.sessionId}`,B=m===`session_host_restart_session:${T.sessionId}`,Y=m===`session_host_stop_session:${T.sessionId}`,K=Yd(T.meta),$=typeof((W=T.meta)==null?void 0:W.runtimeRecoveryError)=="string"?String(T.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:T.displayName||(_==null?void 0:_.runtimeDisplayName)||(_==null?void 0:_.cliName)||T.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Xd(T.lifecycle)}`,children:T.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:T.workspaceLabel||(_==null?void 0:_.runtimeWorkspaceLabel)||T.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:T.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((F=T.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:qd(T.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(Er,{size:11})," ",T.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",qn(T.lastActivityAt),T.osPid?` · pid ${T.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:[L&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{o(L),c()},children:"Open chat"}),(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!m,onClick:()=>{j("session_host_resume_session",T)},children:R?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!m,onClick:()=>{j("session_host_restart_session",T)},children:B?"Restarting…":"Restart"}),(T.lifecycle==="running"||T.lifecycle==="starting"||T.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:!!m,onClick:()=>{j("session_host_stop_session",T)},children:Y?"Stopping…":"Stop"})]})]},T.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(T=>{const L=b.find(_=>_.sessionId===T.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:(L==null?void 0:L.displayName)||T.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Gn(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]})]})]})]})})}function gr(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 Ws(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qd({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:i,onSaveWorkspace:o,onLaunchIde:c,onLaunchProvider:d,onListSavedSessions:l,sendDaemonCommand:p,onOpenConversation:u}){var Je,qe;const x=a.useMemo(()=>[...t].sort(Kr),[t]),[v,f]=a.useState(((Je=x[0])==null?void 0:Je.id)||""),w=a.useMemo(()=>x.find(H=>H.id===v)||x[0],[v,x]),m=a.useMemo(()=>((w==null?void 0:w.workspaces)||[]).map(H=>({id:H.id,path:H.path,label:H.label})),[w]),C=(w==null?void 0:w.defaultWorkspaceId)||null,[g,y]=a.useState(""),[k,I]=a.useState(""),[j,h]=a.useState(gr(x[0])),[b,S]=a.useState(""),[N,E]=a.useState(""),[D,O]=a.useState([]),[T,L]=a.useState(""),[_,R]=a.useState([]),[B,Y]=a.useState(!1),[K,$]=a.useState(""),[W,F]=a.useState(!1),[V,te]=a.useState(!1),[ke,J]=a.useState(null),[Z,q]=a.useState(!1),[xe,re]=a.useState(""),[he,ve]=a.useState(!1),[ie,pe]=a.useState(""),[oe,ge]=a.useState([]),[X,se]=a.useState(!1),[Q,fe]=a.useState(""),[M,ee]=a.useState(!1),ye=a.useRef(null),A=a.useRef(0);a.useEffect(()=>{var H;!v&&((H=x[0])!=null&&H.id)&&f(x[0].id)},[v,x]);const G=a.useMemo(()=>((w==null?void 0:w.availableProviders)||[]).filter(H=>H.category==="cli"&&H.installed!==!1),[w]),z=a.useMemo(()=>((w==null?void 0:w.availableProviders)||[]).filter(H=>H.category==="acp"&&H.installed!==!1),[w]),ae=a.useMemo(()=>((w==null?void 0:w.detectedIdes)||[]).map(H=>({id:H.type,label:H.name||H.type,meta:H.running?"Detected locally":"Available to open"})),[w]),de=a.useMemo(()=>j==="cli"?G.map(H=>({id:H.type,label:H.displayName||H.type,meta:"CLI provider"})):j==="acp"?z.map(H=>({id:H.type,label:H.displayName||H.type,meta:"ACP provider"})):ae,[z,j,G,ae]);a.useEffect(()=>{var we;if(!w)return;if(ye.current!==w.id){ye.current=w.id,y(C||((we=m[0])==null?void 0:we.id)||"__home__"),I(""),h(gr(w)),S(""),E(""),L(""),R([]),$(""),re("");return}y(Ne=>{var Pe;return Ne==="__custom__"||Ne==="__home__"||m.some(Ge=>Ge.id===Ne)?Ne:C||((Pe=m[0])==null?void 0:Pe.id)||"__home__"}),h(Ne=>Ne==="ide"&&ae.length>0||Ne==="cli"&&G.length>0||Ne==="acp"&&z.length>0?Ne:gr(w))},[z.length,G.length,C,ae.length,w,m]),a.useEffect(()=>{var H;j&&(de.some(we=>we.id===b)||S(((H=de[0])==null?void 0:H.id)||""))},[j,de,b]);const Ce=a.useCallback(async(H,we)=>{const Ne=A.current+1;return A.current=Ne,Y(!0),$(""),l(H,we).then(Pe=>{A.current===Ne&&R(Pe)}).catch(Pe=>{A.current===Ne&&(R([]),$(Pe instanceof Error?Pe.message:"Could not load saved sessions"))}).finally(()=>{A.current===Ne&&Y(!1)})},[l]),Ee=a.useCallback((H,we)=>{O(pi(H,we))},[]);a.useEffect(()=>{if(L(""),!w||!b||j==="ide"?O([]):Ee(w.id,b),j!=="cli"){R([]),$(""),Y(!1);return}if(!w||!b){R([]),$(""),Y(!1);return}Ce(w.id,b)},[j,Ee,Ce,w,b]),a.useEffect(()=>{if(!T)return;const H=_.find(we=>we.providerSessionId===T);H!=null&&H.canResume||L("")},[_,T]);const Le=g==="__custom__"?k.trim():g==="__home__"?"":((qe=m.find(H=>H.id===g))==null?void 0:qe.path)||"",ze=a.useCallback(H=>{const we=String(H.workspace||"").trim();if(!we)return;const Ne=m.find(Pe=>Ws(Pe.path)===Ws(we));if(Ne){y(Ne.id),I("");return}y("__custom__"),I(we)},[m]),lt=a.useCallback(H=>{const we=String(H.workspace||"").trim();if(!we)return{workspaceId:null,workspacePath:null};const Ne=m.find(Pe=>Ws(Pe.path)===Ws(we));return Ne?{workspaceId:Ne.id,workspacePath:null}:{workspaceId:null,workspacePath:we}},[m]),Xe=a.useMemo(()=>{var we;if(j!=="cli"||!w||!b)return null;const H=((we=G.find(Ne=>Ne.type===b))==null?void 0:we.displayName)||b;return{ideId:w.id,daemonId:w.id,providerSessionId:T||void 0,transport:"pty",mode:"chat",agentName:H,agentType:b,status:"idle",title:H,messages:[],ideType:b,workspaceName:Le,displayPrimary:H,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${w.id}:${b}`,machineName:ot(w,{fallbackId:w.id})}},[j,G,Le,w,T,b]),We=a.useCallback(()=>{var we,Ne;if(!w)return;y("__custom__"),ve(!0),fe("");const H=rr(w.platform,[k.trim(),Le,(we=m.find(Pe=>Pe.id===C))==null?void 0:we.path,(Ne=m[0])==null?void 0:Ne.path]);se(!0),i(w.id,H).then(Pe=>{pe(Pe.path),I(Pe.path),ge(Pe.directories)}).catch(Pe=>{fe(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>se(!1))},[k,C,i,Le,w,m]),at=a.useCallback(H=>{w&&(se(!0),fe(""),i(w.id,H).then(we=>{pe(we.path),I(we.path),ge(we.directories)}).catch(we=>{fe(we instanceof Error?we.message:"Could not load folder")}).finally(()=>se(!1)))},[i,w]),Re=a.useCallback(async()=>{if(!w||!Le)return;ee(!0),re("");const H=await o(w.id,Le);if(ee(!1),!H.ok){re(H.error||"Could not save workspace");return}re("Workspace saved. It will appear in the list once the machine state refreshes.")},[o,Le,w]),Ie=a.useCallback(async()=>{if(!w||!j||!b)return;q(!0),re("");const H=N.trim()?N.trim().split(/\s+/).filter(Boolean):[],we=j==="ide"?await c(w.id,b,{workspacePath:Le||null}):await d(w.id,j,b,{workspaceId:g!=="__home__"&&g!=="__custom__"?g:null,workspacePath:g==="__custom__"&&Le||null,resumeSessionId:j==="cli"&&T?T:null,cliArgs:H});if(q(!1),!we.ok){re(we.error||"Could not start session");return}j!=="ide"&&N.trim()&&(fi(w.id,b,N),Ee(w.id,b)),n()},[j,N,Ee,n,c,d,Le,w,T,b,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(ft,{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:H=>f(H.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:x.map(H=>e.jsx("option",{value:H.id,children:ot(H,{fallbackId:H.id})},H.id))})]}),j==="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(Lt,{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:H=>{const we=H.target.value;y(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"}),m.map(H=>e.jsxs("option",{value:H.id,children:[H.id===C?"⭐ ":"",er(H.path,H.label)||H.path]},H.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.":Le||"Select a workspace folder."}),g==="__custom__"&&Le&&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(cs,{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:G.length>0},{id:"ide",label:"IDE",enabled:ae.length>0},{id:"acp",label:"ACP",enabled:z.length>0}].map(H=>e.jsx("button",{type:"button",className:`btn btn-sm ${j===H.id?"btn-primary":"btn-secondary"}`,onClick:()=>h(H.id),disabled:!H.enabled||Z,children:H.label},H.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:j==="ide"?"Choose IDE":j==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[de.map(H=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${b===H.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>S(H.id),disabled:Z,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:H.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:H.meta})]},H.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."})]})]}),j!=="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:N,onChange:H=>E(H.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(H=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>E(H),disabled:Z,title:H,children:H},H))})]}),j==="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||!b||B,onClick:()=>{!w||!b||Ce(w.id,b)},children:B?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:Z||!w||!b,onClick:()=>{!w||!b||(F(!0),Ce(w.id,b))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:T,onChange:H=>{const we=H.target.value;if(L(we),!we)return;const Ne=_.find(Pe=>Pe.providerSessionId===we);!Ne||!Ne.canResume||ze(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"}),_.map(H=>e.jsxs("option",{value:H.providerSessionId,disabled:!H.canResume,children:[H.title||H.providerSessionId,H.canResume?"":" (workspace missing)"]},H.providerSessionId))]})}),T&&(()=>{const H=_.find(we=>we.providerSessionId===T);return H?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:H.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[H.workspace||"Workspace unknown",H.currentModel?` · ${H.currentModel}`:""]})]}):null})(),K&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:K}),!B&&!K&&_.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),xe&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${xe.includes("saved")||xe.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:xe})]}),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||!j||!b||g==="__custom__"&&!Le,children:[e.jsx(Dr,{size:14}),Z?"Starting…":"Start session"]})]})]})}),he&&e.jsx(ar,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ie,directories:oe,busy:X,error:Q,onClose:()=>ve(!1),onNavigate:at,onConfirm:H=>{I(H),pe(H),y("__custom__"),ve(!1)}}),W&&Xe&&e.jsx(Ur,{activeConv:Xe,ides:[],isCreatingChat:!1,isRefreshingHistory:B,savedSessions:_,isSavedSessionsLoading:B,isResumingSavedSessionId:ke,onClose:()=>F(!1),onNewChat:()=>{L(""),F(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!w||!b||Ce(w.id,b)},onResumeSavedSession:H=>{if(!w||!b||ke||!H.canResume)return;const we=lt(H);L(H.providerSessionId),ze(H),J(H.providerSessionId),F(!1),q(!0),re(""),d(w.id,"cli",b,{workspaceId:we.workspaceId,workspacePath:we.workspacePath,resumeSessionId:H.providerSessionId}).then(Ne=>{if(!Ne.ok){re(Ne.error||"Could not resume session");return}n()}).finally(()=>{q(!1),J(Ne=>Ne===H.providerSessionId?null:Ne)})}}),V&&w&&e.jsx(Zd,{machineCards:[{id:w.id,label:ot(w,{fallbackId:w.id}),subtitle:[w.platform||"machine",ai(w)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:w.id,sendDaemonCommand:p,onOpenConversation:H=>{te(!1),n(),u(H)},onClose:()=>te(!1)})]}):null}const xi="adhdev-dashboard-action-shortcuts",eu=1200,tu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function su(){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 hi(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 ru(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Yn(t){const s=Object.fromEntries(hi(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(xi)||"{}"),n={...s,...r};for(const[i,o]of Object.entries(tu))n[i]===o&&(n[i]=s[i]);return n}catch{return s}}function nu(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function au({enabled:t=!0,onTrigger:s}){const r=su(),[n,i]=a.useState(()=>Yn(r)),[o,c]=a.useState(null),[d,l]=a.useState([]),p=a.useRef({parts:[],timer:null}),u=a.useCallback(m=>{const C=[];return m.metaKey&&C.push(r?"⌘":"Meta"),m.ctrlKey&&C.push("Ctrl"),m.altKey&&C.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&C.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(C.push(nu(m.key)),C.join("+"))},[r]),x=a.useCallback(m=>{i(m);try{localStorage.setItem(xi,JSON.stringify(m))}catch{}},[]);a.useEffect(()=>{const m=Yn(r),C=Object.entries(n),g=Object.entries(m);C.length===g.length&&C.every(([y,k])=>m[y]===k)||x(m)},[n,r,x]);const v=a.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),f=a.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},eu))},[]);a.useEffect(()=>{if(!o)return;const m=C=>{if(C.preventDefault(),C.stopPropagation(),C.key==="Escape"){c(null),l([]);return}const g=u(C);if(!g)return;const k=!(C.metaKey||C.ctrlKey||C.altKey)&&/^[A-Z0-9]$/.test(g);if(d.length===0&&k){l([g]);return}const j=[...d,g].slice(0,2).join(" "),h={...n};for(const[b,S]of Object.entries(h))S===j&&delete h[b];h[o]=j,x(h),c(null),l([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,u,x,o,d]),a.useEffect(()=>{if(!t||o)return;const m=C=>{if(C.defaultPrevented)return;const g=u(C);if(!g)return;const y=C.metaKey||C.ctrlKey||C.altKey;if(ru(C.target)&&!y)return;const k=p.current.parts,I=y?[g]:[...k.slice(-1),g].slice(-2),j=I.join(" "),h=I[I.length-1],b=Object.entries(n).filter(([,O])=>!!O),S=b.find(([,O])=>O===j);if(S){C.preventDefault(),v(),s(S[0]);return}if(b.some(([,O])=>O.startsWith(`${j} `))){C.preventDefault(),p.current.parts=I,f();return}const E=b.find(([,O])=>O===h);if(E){C.preventDefault(),v(),s(E[0]);return}if(b.some(([,O])=>O.startsWith(`${h} `))){C.preventDefault(),p.current.parts=[h],f();return}v()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,f,t,u,s,v,o]),a.useEffect(()=>()=>v(),[v]);const w=a.useMemo(()=>hi(r),[r]);return{isMac:r,actionDefinitions:w,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:l,saveShortcuts:x}}function iu(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 ou(t){return t instanceof Error?t.message:String(t||"")}function cu(t){const s=ou(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function lu({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:i,isConnected:o,onOpenHistory:c,onOpenRemote:d,onStopCli:l,activeCliViewMode:p,onSetActiveCliViewMode:u,mobileChatConversations:x,hiddenConversations:v,ides:f,actionLogs:w,sendDaemonCommand:m,setLocalUserMessages:C,setActionLogs:g,isStandalone:y,initialDataLoaded:k,userName:I,requestedMobileTabKey:j,onRequestedMobileTabConsumed:h,requestedMachineId:b,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:E,containerRef:D,isSplitMode:O,numGroups:T,groupSizes:L,groupedConvs:_,clearedTabs:R,focusedGroup:B,setFocusedGroup:Y,moveTabToGroup:K,splitTabRelative:$,closeGroup:W,handleResizeStart:F,detectedIdes:V,handleLaunchIde:te,groupActiveTabIds:ke,setGroupActiveTabIds:J,groupTabOrders:Z,setGroupTabOrders:q,toggleHiddenTab:xe,visibleConversations:re,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:ve,onDesktopActiveTabChange:ie,onHideConversation:pe,onShowHiddenConversation:oe,onShowAllHiddenConversations:ge,scrollToBottomRequest:X,machineEntries:se,onBrowseMachineDirectory:Q,onSaveMachineWorkspace:fe,onLaunchMachineIde:M,onLaunchMachineProvider:ee,onListMachineSavedSessions:ye}){const A=Ve.useRef(null),[G,z]=Ve.useState(!1),[ae,de]=Ve.useState(!1),[Ce,Ee]=Ve.useState(!1),[Le,ze]=Ve.useState(!1),[lt,Xe]=Ve.useState(!1),[We,at]=Ve.useState("quickstart"),[Re,Ie]=Ve.useState("workspace"),Je=!t&&!s,qe=Ve.useCallback(ne=>{z(ne),ne&&de(!1)},[]),H=Ve.useCallback(ne=>{de(ne),ne&&z(!1)},[]),we=Ve.useCallback(()=>{at(re.length===0?"quickstart":"shortcuts"),Ie("workspace"),Ee(!0),z(!1),de(!1)},[re.length]),Ne=Ve.useCallback(async ne=>{var Ct;if(!r)return;const $e=(Ct=r.modalButtons)==null?void 0:Ct[ne];if(!$e)return;const vt=Cs(r);if(!vt)return;const St=$e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),wt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(St);try{await m(vt,"resolve_action",{button:$e,action:wt?"approve":"reject",buttonIndex:ne,...os(r)})}catch(P){cu(P)||console.error("[Shortcut approval] Failed:",P)}},[r,m]),{isMac:Pe,actionDefinitions:Ge,actionShortcuts:Et,shortcutListening:dt,shortcutListeningDraft:xt,setShortcutListening:$t,setShortcutListeningDraft:kt,saveShortcuts:yt}=au({enabled:Je&&!Ce,onTrigger:ne=>{var $e,vt,St,wt,Ct,P,U,ce,be,Te,Se,Ke,et;if(ne==="openShortcutHelp"){we();return}if(ne==="hideCurrentTab"){r&&pe(r);return}if(ne==="toggleHiddenTabs"){H(!ae);return}if(ne==="openHistoryForActiveTab"){r&&!De(r)&&c(r);return}if(ne==="openRemoteForActiveTab"){r&&!Be(r)&&!De(r)&&d(r);return}if(ne==="splitActiveTabRight"){($e=A.current)==null||$e.splitActiveTabRight();return}if(ne==="splitActiveTabDown"){(vt=A.current)==null||vt.splitActiveTabDown();return}if(ne==="focusLeftPane"){(St=A.current)==null||St.focusLeftPane();return}if(ne==="focusRightPane"){(wt=A.current)==null||wt.focusRightPane();return}if(ne==="focusUpPane"){(Ct=A.current)==null||Ct.focusUpPane();return}if(ne==="focusDownPane"){(P=A.current)==null||P.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"){(Te=A.current)==null||Te.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"){(Ke=A.current)==null||Ke.activatePreviousTabInGroup();return}if(ne==="selectNextGroupTab"){(et=A.current)==null||et.activateNextTabInGroup();return}!r||!Be(r)||De(r)||ne==="toggleCliView"&&u(p==="chat"?"terminal":"chat")}}),Nt=Ve.useCallback(()=>{Ee(!1),$t(null),kt([])},[$t,kt]),Ae=Ve.useMemo(()=>Re==="all"?Ge:Ge.filter(ne=>iu(ne)===Re),[Ge,Re]),Dt=Ve.useCallback(()=>{const ne=Object.fromEntries(Ge.map($e=>[$e.id,""]));yt(ne)},[Ge,yt]),es=Ve.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ne=Object.fromEntries(Ge.map($e=>[$e.id,$e.defaultShortcut]));yt(ne)},[Ge,yt]);return Ve.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]),Ve.useEffect(()=>{if(!Ce||dt)return;const ne=$e=>{$e.key==="Escape"&&($e.preventDefault(),Nt())};return window.addEventListener("keydown",ne,!0),()=>window.removeEventListener("keydown",ne,!0)},[Nt,Ce,dt]),Ve.useEffect(()=>{if(!Je){Xe(!1);return}Xe(!0);const ne=window.setTimeout(()=>{Xe(!1)},1e4);return()=>window.clearTimeout(ne)},[Je]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(Ic,{activeConv:r,agentCount:n.length,wsStatus:i,isConnected:o,conversations:re,hiddenConversations:v,onOpenHistory:c,onOpenConversation:oe,onHideConversation:pe,onShowConversation:oe,onShowAllHidden:ge,inboxOpen:G,onInboxOpenChange:qe,hiddenOpen:ae,onHiddenOpenChange:H,onOpenNewSession:s?void 0:()=>ze(!0),onOpenRemote:()=>{!r||Be(r)||De(r)||d(r)},onStopCli:l,activeCliViewMode:p,onSetCliViewMode:u}),t?e.jsx(Cd,{conversations:x,hiddenConversations:v,ides:f,actionLogs:w,sendDaemonCommand:m,setLocalUserMessages:C,setActionLogs:g,isStandalone:y,userName:I,requestedActiveTabKey:j,onRequestedActiveTabConsumed:h,requestedMachineId:b,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:d,onStopCli:l,wsStatus:i,isConnected:o,onShowHiddenConversation:oe,onShowAllHiddenConversations:ge,onOpenNewSession:()=>ze(!0)}):s?e.jsx(Ed,{containerRef:D,isSplitMode:O,numGroups:T,groupSizes:L,groupedConvs:_,clearedTabs:R,ides:f,actionLogs:w,sendDaemonCommand:m,setLocalUserMessages:C,setActionLogs:g,isStandalone:y,hasRegisteredMachines:se.length>0,userName:I,focusedGroup:B,setFocusedGroup:Y,moveTabToGroup:K,splitTabRelative:$,closeGroup:W,handleResizeStart:F,detectedIdes:V,handleLaunchIde:te,groupActiveTabIds:ke,setGroupActiveTabIds:J,groupTabOrders:Z,setGroupTabOrders:q,toggleHiddenTab:xe,allowTabShortcuts:!1}):e.jsx(Ud,{visibleConversations:re,clearedTabs:R,ides:f,actionLogs:w,sendDaemonCommand:m,setLocalUserMessages:C,setActionLogs:g,isStandalone:y,hasRegisteredMachines:se.length>0,initialDataLoaded:k,userName:I,detectedIdes:V,handleLaunchIde:te,toggleHiddenTab:xe,registerActionHandlers:ne=>{A.current=ne},onActiveTabChange:ie,requestedActiveTabKey:he,onRequestedActiveTabConsumed:ve,scrollToBottomRequest:X}),Le&&e.jsx(Qd,{machines:se,conversations:x,ides:f,onClose:()=>ze(!1),onBrowseDirectory:Q,onSaveWorkspace:fe,onLaunchIde:M,onLaunchProvider:ee,onListSavedSessions:ye,sendDaemonCommand:m,onOpenConversation:ne=>{ze(!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:Nt,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:Nt,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:()=>at(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 ",Pe?"⌥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:Dt,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:es,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:Ae.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?xt.length>0?`${xt.join(" ")} ...`:"Listening...":Et[ne.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$t(ne.id),kt([])},children:dt===ne.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const $e={...Et};$e[ne.id]="",yt($e)},children:"Disable"})]})]})},ne.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Pe?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:we,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${lt?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),lt&&e.jsx("span",{children:"Guide"})]})]})}const yr=[{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 du({onClose:t}){const[s,r]=a.useState(0),n=yr[s],i=s===yr.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,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:e.jsx(ft,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:yr.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",{className:"flex justify-between items-center mt-6",children:[e.jsx("button",{onClick:t,className:"btn btn-secondary border-none",children:"Skip"}),e.jsx("button",{onClick:()=>i?t():r(o=>o+1),className:"btn btn-primary",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 uu({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 mu({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:i,preferredTabKey:o}){const[c,d]=a.useState(()=>o||"native"),l=a.useMemo(()=>$a(s),[s]),p=a.useMemo(()=>t?Hr(t,n,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,l,r]),u=a.useMemo(()=>p.find(C=>C.streamSource==="native"),[p]),x=a.useMemo(()=>p.filter(C=>C.streamSource==="agent-stream"),[p]),v=a.useMemo(()=>t?Mt(p,t.id):null,[p,t]);a.useEffect(()=>{o&&d(o)},[o]),a.useEffect(()=>{if(o||!v)return;const C=v.streamSource==="native"?"native":v.tabKey;!C||c===C||c==="native"&&d(C)},[c,v,o]),a.useEffect(()=>{var C;c!=="native"&&(x.some(g=>g.tabKey===c)||d(((C=x[0])==null?void 0:C.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(u||x[0]&&d(x[0].tabKey))},[c,u,x]);const f=a.useMemo(()=>c==="native"&&u?u:x.find(C=>C.tabKey===c)||v||u||x[0],[c,u,v,x]),w=a.useMemo(()=>x.map(C=>({tabKey:C.tabKey,title:Ra(C)||i,status:C.status})),[x,i]),m=a.useCallback(C=>{if(C)return p.find(g=>g.sessionId===C||g.ideId===C||g.tabKey===C||g.ideType===C||g.agentType===C)},[p]);return{activeChatTab:c,setActiveChatTab:d,activeConv:f,conversations:p,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:m}}function pu({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:i,localUserMessages:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:p,userName:u,onOpenHistory:x,onConversationChange:v,onClose:f}){const[w,m]=a.useState("split"),[C,g]=a.useState(()=>jt(t)?"native":t.tabKey),y=a.useRef(null),k=a.useMemo(()=>s||r.find(B=>B.id===t.ideId),[t.ideId,s,r]),I=a.useMemo(()=>Oe((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:j,extensionTabs:h,hasExtensions:b}=mu({ideData:k,allIdes:r,connectionStates:n,localUserMessages:o,ideName:I||"IDE",preferredTabKey:jt(t)?void 0:t.tabKey}),S=a.useMemo(()=>k?Mt(j,k.id):null,[k,j]);a.useEffect(()=>{const B=y.current,Y={ideId:t.ideId,tabKey:t.tabKey,streamSource:t.streamSource};if(y.current=Y,!(B&&B.ideId===Y.ideId&&B.tabKey===Y.tabKey&&B.streamSource===Y.streamSource)){if(jt(t)){g("native");return}g(t.tabKey)}},[t.ideId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(C==="native"){if(j.some(B=>B.streamSource==="native"))return;(S==null?void 0:S.streamSource)==="agent-stream"&&g(S.tabKey);return}if(!j.some(B=>B.tabKey===C)){if((S==null?void 0:S.streamSource)==="agent-stream"){g(S.tabKey);return}g("native")}},[j,C,S]);const N=a.useMemo(()=>C==="native"?j.find(B=>B.streamSource==="native")||t:j.find(B=>B.tabKey===C)||t,[t,j,C]),E=Wr(N),D=sr({sendDaemonCommand:c,activeConv:N,setLocalUserMessages:d,setActionLogs:l,isStandalone:p}),{connScreenshot:O,screenshotUsage:T,handleRemoteAction:L}=ci({doId:E,ideId:N.ideId,ideType:N.ideType,connState:N.connectionState||"new",viewMode:w,instanceId:k==null?void 0:k.instanceId}),_=a.useMemo(()=>i.filter(B=>B.ideId===N.tabKey),[i,N.tabKey]);a.useEffect(()=>{v==null||v(N)},[N,v]),a.useEffect(()=>{const B=Y=>{Y.key==="Escape"&&f()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[f]);const R=a.useCallback(B=>{B.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:f,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:R,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:tr(N)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,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(B=>{const Y=w===B;return e.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${Y?"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:()=>m(B),title:B==="split"?"Split view":"Remote only",children:B==="split"?e.jsx(xo,{size:15}):e.jsx(ct,{size:15})},B)})}),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:()=>x(N),title:"Chat History",children:[e.jsx($r,{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:f,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(uu,{hasExtensions:b,ideName:I||"IDE",activeChatTab:C,extensionTabs:h,onSelectTab:g}),e.jsx(ja,{activeConv:N,onModalButton:D.handleModalButton}),e.jsx(Ir,{activeConv:N,ideEntry:k,showMetaChips:!1,handleSendChat:D.handleSendChat,isSendingChat:D.isSendingChat,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:_,userName:u})]}),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(ya,{addLog:()=>{},connState:N.connectionState||"new",connScreenshot:O,screenshotUsage:T,transportType:N.transport,onAction:L})})]})]})})}function fu({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:i}){const o=jc(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 xu({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:i,savedHistorySessions:o,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:l,onNewHistoryChat:p,onSwitchHistorySession:u,onRefreshHistory:x,onResumeSavedHistorySession:v,remoteDialogConv:f,remoteDialogIdeEntry:w,connectionStates:m,actionLogs:C,localUserMessages:g,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:I,isStandalone:j,userName:h,onOpenRemoteHistory:b,onRemoteConversationChange:S,onCloseRemoteDialog:N,cliStopDialogOpen:E,cliStopTargetConv:D,onCancelCliStop:O,onStopCliNow:T,onSaveCliAndStop:L,toasts:_,onDismissToast:R,onClickToast:B,showOnboarding:Y,onCloseOnboarding:K}){var $;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(Ur,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:i,savedSessions:o,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:l,onNewChat:p,onSwitchSession:u,onRefreshHistory:x,onResumeSavedSession:v}),f&&e.jsx(pu,{activeConv:f,ideEntry:w,ides:r,connectionStates:m,actionLogs:C,localUserMessages:g,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:I,isStandalone:j,userName:h,onOpenHistory:b,onConversationChange:S,onClose:N}),E&&D&&(Be(D)||De(D))&&e.jsx(fu,{activeConv:D,canSaveAndStop:Be(D)&&!De(D)&&!!(($=D.resume)!=null&&$.supported),onCancel:O,onStopNow:T,onSaveAndStop:L}),e.jsx(Ea,{toasts:_,onDismiss:R,onClickToast:B}),Y&&e.jsx(du,{onClose:K})]})}function hu({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(us,{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=ot(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 shrink-0",onClick:i,title:"Dismiss",children:e.jsx(ft,{size:16})})]})}function bu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Xn(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function yu(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 vu(){var tn,sn,rn,nn,an;const{sendCommand:t}=Rt(),s=Pr(),r=ds(),[n,i]=Gi(),o=n.get("activeTab"),c=((tn=s.state)==null?void 0:tn.openRemoteForTabKey)||null,d=((sn=s.state)==null?void 0:sn.openMachineId)||null,l=((rn=s.state)==null?void 0:rn.mobileSection)||null,p=Aa(),u=p.ides||[],x=p.initialLoaded??!0,{updateIdeChats:v,setToasts:f}=p,[w,m]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),C=p.toasts||[],g=p.wsStatus||"connected",y=p.isConnected??!0,k=p.connectionStates||{},I=p.showReconnected||!1,{groupAssignments:j,setGroupAssignments:h,focusedGroup:b,setFocusedGroup:S,groupActiveTabIds:N,setGroupActiveTabIds:E,groupTabOrders:D,setGroupTabOrders:O,groupSizes:T,setGroupSizes:L,isMobile:_,hasHydratedStoredLayout:R,hydrateStoredLayout:B}=ed(),[Y,K]=a.useState(!1),[$,W]=a.useState(!1),[F,V]=a.useState(null),[te,ke]=a.useState([]),[J,Z]=a.useState(!1),[q,xe]=a.useState(null),[re]=a.useState(()=>Ya()),[he,ve]=a.useState([]),[ie,pe]=a.useState({}),[oe,ge]=a.useState({}),[X,se]=a.useState(null),[Q,fe]=a.useState(null),[M,ee]=a.useState(null),ye=a.useRef(null);Ts("Dashboard",{ideCount:u.length,toastCount:C.length,focusedGroup:b,groupCount:Object.keys(j).length,localMessageTabs:Object.keys(ie).length,actionLogCount:he.length});const A=u.find(le=>le.type==="adhdev-daemon"),G=(A==null?void 0:A.detectedIdes)||[],z=a.useMemo(()=>u.filter(le=>le.type==="adhdev-daemon"||le.daemonMode).sort(Kr),[u]),ae=!!A,de=(A==null?void 0:A.terminalBackend)||null,Ce=A?ot(A,{fallbackId:A.id}):null,Ee=(A==null?void 0:A.id)||null,{hiddenTabs:Le,hideTab:ze,toggleTab:lt,showTab:Xe,showAllTabs:We}=Pl(),{chatIdes:at,conversations:Re,visibleConversations:Ie,visibleTabKeys:Je,resolveConversationBySessionId:qe,resolveConversationByTarget:H}=Hl({ides:u,connectionStates:k,localUserMessages:ie,clearedTabs:oe,hiddenTabs:Le}),we=a.useMemo(()=>_s(u),[u]),Ne=a.useRef(null),{containerRef:Pe,normalizedGroupAssignments:Ge,numGroups:Et,isSplitMode:dt,groupedConvs:xt,moveTabToGroup:$t,closeGroup:kt,handleResizeStart:yt,splitTabRelative:Nt}=cd({groupAssignments:j,setGroupAssignments:h,setFocusedGroup:S,setGroupActiveTabIds:E,setGroupTabOrders:O,groupSizes:T,setGroupSizes:L,isMobile:_,visibleConversations:Ie,visibleTabKeys:Je}),Ae=a.useMemo(()=>{var je,me;if(!_){if(X){const ue=Re.find(_e=>_e.tabKey===X);if(ue)return ue}return Ie[0]}const le=N[b];if(le){const ue=Re.find(_e=>_e.tabKey===le);if(ue)return ue}return((je=xt[b])==null?void 0:je[0])||((me=xt[0])==null?void 0:me[0])},[X,_,N,b,Re,xt,Ie]);a.useEffect(()=>{if(_){Ne.current=null;return}if(!(Ae!=null&&Ae.sessionId)){Ne.current=null;return}const le=`${Ae.tabKey}:${Ae.sessionId}`;if(Ne.current===le)return;const je=()=>{if(document.visibilityState!=="visible"||Ne.current===le)return;Ne.current=le;const me=ks(Ae,we),ue=Math.max(Date.now(),Ft(Ae),me.lastUpdated||0);t(Ae.daemonId||Ae.ideId,"mark_session_seen",{sessionId:Ae.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)}}},[Ae,_,we,t]);const{requestedDesktopTabKey:Dt,requestedMobileTabKey:es,consumeRequestedActiveTab:ne}=Fl({isMobile:_,urlActiveTab:o,resolveConversationBySessionId:qe,setSearchParams:i}),{remoteDialogConv:$e,remoteDialogIdeEntry:vt,remoteDialogActiveConv:St,setRemoteDialogActiveConv:wt,openRemoteDialog:Ct,closeRemoteDialog:P}=rd({isMobile:_,location:s,navigate:r,requestedRemoteTabTarget:c,requestedDesktopTabKey:Dt,conversations:Re,ides:u,resolveConversationByTarget:H}),U=St||$e||Ae,ce=!!U&&Be(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]),Te=a.useMemo(()=>Ie,[Ie]),Se=_&&re==="chat",Ke=a.useMemo(()=>Re.filter(le=>Le.has(le.tabKey)),[Re,Le]),et=a.useCallback(le=>{const je=new URLSearchParams(n);je.set("activeTab",le),i(je,{replace:!0})},[n,i]),ut=a.useCallback(async(le,je)=>nr(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]),ps=a.useCallback(async(le,je,me)=>{var ue;try{const _e={ideType:je,enableCdp:!0};(ue=me==null?void 0:me.workspacePath)!=null&&ue.trim()&&(_e.workspace=me.workspacePath.trim());const Qe=await t(le,"launch_ide",_e);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(_e){return{ok:!1,error:_e instanceof Error?_e.message:"Could not launch IDE"}}},[t]),bi=a.useCallback(async(le,je,me,ue)=>{var Qe,fs,ts;const _e=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),(ts=ue==null?void 0:ue.initialModel)!=null&&ts.trim()&&(ht.initialModel=ue.initialModel.trim());const tt=await t(le,"launch_cli",ht),it=(tt==null?void 0:tt.result)||tt,xs=(it==null?void 0:it.sessionId)||(it==null?void 0:it.id);return tt!=null&&tt.success&&xs?(et(xs),{ok:!0}):tt!=null&&tt.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:_e}),{ok:!0}):{ok:!1,error:(tt==null?void 0:tt.error)||(it==null?void 0:it.error)||`Could not launch ${je.toUpperCase()} session`}}catch(ht){return gu(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:_e}),{ok:!0}):{ok:!1,error:ht instanceof Error?ht.message:`Could not launch ${je.toUpperCase()} session`}}},[et,t]),gi=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=Xn(M.workspacePath),je=u.find(_e=>{var tt,it,xs,on;if(!_e||_e.type==="adhdev-daemon"||_e.daemonMode||bu(_e.daemonId||_e.id)!==M.machineId||(Ss(_e)?"cli":as(_e)?"acp":"ide")!==M.kind||String(_e.agentType||_e.ideType||_e.type||"")!==M.providerType)return!1;if(M.resumeSessionId)return String(_e.providerSessionId||"")===M.resumeSessionId;if(le){const cr=Xn(_e.workspace||_e.runtimeWorkspaceLabel);return cr?cr===le:!1}return Number(_e.lastUpdated||_e._lastUpdate||_e.timestamp||((on=(xs=(it=(tt=_e.activeChat)==null?void 0:tt.messages)==null?void 0:it.at)==null?void 0:xs.call(it,-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(_e=>_e.ideId===je.id))==null?void 0:ue.sessionId;me&&(ee(null),et(me))},[Re,et,u,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]),Rl({visibleConversations:Ie,clearedTabs:oe,setClearedTabs:ge,setActionLogs:ve}),Vl({ides:u,sendDaemonCommand:t,setToasts:f,setLocalUserMessages:pe,resolveConversationByTarget:H});const{isRefreshingHistory:yi,handleLaunchIde:vi,handleRefreshHistory:wi}=Rn({sendDaemonCommand:t,activeConv:Ae,chats:(nn=u.find(le=>le.id===(Ae==null?void 0:Ae.ideId)))==null?void 0:nn.chats,updateIdeChats:v,setToasts:f,setLocalUserMessages:pe,setClearedTabs:ge}),{isCreatingChat:ji,isRefreshingHistory:ki,handleSwitchSession:Ni,handleNewChat:Si,handleRefreshHistory:Ci}=Rn({sendDaemonCommand:t,activeConv:U,chats:(an=u.find(le=>le.id===(U==null?void 0:U.ideId)))==null?void 0:an.chats,updateIdeChats:v,setToasts:f,setLocalUserMessages:pe,setClearedTabs:ge}),or=a.useCallback(async()=>{if(!(!U||!ce||J)){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,J,ce,t]);a.useEffect(()=>{if(!Y){ye.current=null;return}if(!ce){ye.current=null,ke([]),Z(!1);return}!be||J||ye.current!==be&&(ye.current=be,or())},[or,Y,J,ce,be]);const Ii=a.useCallback(async le=>{if(!U||!ce||!le.providerSessionId||!le.workspace)return;const je=U.daemonId||U.ideId,me=U.agentType||U.ideType;try{xe(le.providerSessionId);const ue=await t(je,"launch_cli",{cliType:me,dir:le.workspace,resumeSessionId:le.providerSessionId,initialModel:le.currentModel}),_e=(ue==null?void 0:ue.result)??ue,Qe=typeof(_e==null?void 0:_e.sessionId)=="string"?_e.sessionId:typeof(_e==null?void 0:_e.id)=="string"?_e.id:"";Qe&&i(fs=>{const ts=new URLSearchParams(fs);return ts.set("activeTab",Qe),ts},{replace:!0}),K(!1)}catch(ue){console.error("Resume saved session failed",ue)}finally{xe(null)}},[U,ce,t,i]);sd({urlActiveTab:_&&!Se?o:null,conversations:Re,resolveConversationBySessionId:qe,normalizedGroupAssignments:Ge,hasHydratedStoredLayout:_&&!Se?R:!0,hydrateStoredLayout:_&&!Se?B:()=>{},setGroupActiveTabIds:E,setFocusedGroup:S,setSearchParams:i,historyModalOpen:Y,activeConv:Ae,isRefreshingHistory:yi,ides:u,handleRefreshHistory:wi});const Zr=a.useCallback(async(le,je)=>{const me=je||F||Ae;if(!me||!Be(me)&&!De(me))return;const ue=me.ideType||me.agentType||"",_e=me.ideId||me.daemonId||"";try{await t(_e,"stop_cli",{cliType:ue,targetSessionId:me.sessionId,mode:le})}catch(Qe){console.error("Stop CLI failed:",Qe)}},[Ae,F,t]),Ti=a.useCallback(async le=>{const je=le||Ae;!je||!Be(je)&&!De(je)||(V(je),W(!0))},[Ae]),_i=a.useMemo(()=>!Ae||!Be(Ae)||De(Ae)?null:ls(Ae),[Ae]),Ai=a.useCallback(async le=>{if(!(!Ae||!Be(Ae)||De(Ae)||ls(Ae)===le))try{await t(Pt(Ae)||Ae.ideId,"set_cli_view_mode",{targetSessionId:Ae.sessionId,cliType:Xt(Ae),mode:le})}catch(me){yu(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[Ae,t]),{versionMismatchDaemons:Mi,appVersion:Li,versionBannerDismissed:Pi,setVersionBannerDismissed:Ri,upgradingDaemons:Ei,handleBannerUpgrade:$i}=ld({ides:u,sendDaemonCommand:t}),Qr=a.useCallback(le=>{se(le.tabKey),i(je=>{const me=new URLSearchParams(je),ue=cc(le);return ue?me.set("activeTab",ue):me.delete("activeTab"),me},{replace:!0})},[i]),en=a.useCallback(le=>{Xe(le.tabKey),Qr(le)},[Qr,Xe]),Di=a.useCallback(le=>{ze(le.tabKey)},[ze]);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(Sc,{wsStatus:g,showReconnected:I}),e.jsx(Cc,{terminalBackend:de,isStandalone:ae,machineLabel:Ce,machineKey:Ee}),!Pi&&e.jsx(hu,{daemons:Mi,targetVersion:Li,upgradingDaemons:Ei,onUpgrade:$i,onDismiss:()=>Ri(!0)}),e.jsx(lu,{showMobileChatMode:Se,isMobile:_,activeConv:Ae,chatIdes:at,wsStatus:g,isConnected:y,onOpenHistory:le=>{le&&wt(le),K(!0)},onOpenRemote:Ct,onStopCli:Ti,activeCliViewMode:_i,onSetActiveCliViewMode:Ai,mobileChatConversations:Te,ides:u,actionLogs:he,sendDaemonCommand:t,setLocalUserMessages:pe,setActionLogs:ve,isStandalone:ae,initialDataLoaded:x,userName:p.userName,requestedMobileTabKey:es,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:Pe,isSplitMode:dt,numGroups:Et,groupSizes:T,groupedConvs:xt,clearedTabs:oe,focusedGroup:b,setFocusedGroup:S,moveTabToGroup:$t,splitTabRelative:Nt,closeGroup:kt,handleResizeStart:yt,detectedIdes:G,handleLaunchIde:vi,groupActiveTabIds:N,setGroupActiveTabIds:E,groupTabOrders:D,setGroupTabOrders:O,toggleHiddenTab:lt,visibleConversations:Ie,hiddenConversations:Ke,requestedDesktopTabKey:Dt,onRequestedDesktopTabConsumed:ne,onDesktopActiveTabChange:se,onHideConversation:Di,onShowHiddenConversation:en,onShowAllHiddenConversations:We,scrollToBottomRequest:Q,machineEntries:z,onBrowseMachineDirectory:ut,onSaveMachineWorkspace:Ze,onLaunchMachineIde:ps,onLaunchMachineProvider:bi,onListMachineSavedSessions:gi}),e.jsx("style",{children:`
46
- body { overflow: hidden; overscroll-behavior: none; }
47
- `}),e.jsx(xu,{historyModalOpen:Y,historyTargetConv:U,ides:u,isHistoryCreatingChat:ji,isHistoryRefreshingHistory:ce?!1:ki,savedHistorySessions:te,isSavedHistoryLoading:J,isResumingSavedHistorySessionId:q,onCloseHistory:()=>K(!1),onNewHistoryChat:Si,onSwitchHistorySession:Ni,onRefreshHistory:ce?or:Ci,onResumeSavedHistorySession:Ii,remoteDialogConv:$e,remoteDialogIdeEntry:vt,connectionStates:k,actionLogs:he,localUserMessages:ie,sendDaemonCommand:t,setLocalUserMessages:pe,setActionLogs:ve,isStandalone:ae,userName:p.userName,onOpenRemoteHistory:le=>{le&&wt(le),K(!0)},onRemoteConversationChange:wt,onCloseRemoteDialog:P,cliStopDialogOpen:$,cliStopTargetConv:F,onCancelCliStop:()=>{W(!1),V(null)},onStopCliNow:async()=>{W(!1),await Zr("hard",F),V(null)},onSaveCliAndStop:async()=>{W(!1),await Zr("save",F),V(null)},toasts:C,onDismissToast:le=>f(je=>je.filter(me=>me.id!==le)),onClickToast:le=>{if(le.targetKey){const je=H(le.targetKey);je&&(S(Ge.get(je.tabKey)??0),en(je),fe({tabKey:je.tabKey,nonce:Date.now()}))}},showOnboarding:w,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}m(!1)}})]})}function wu({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:i}){const[o,c]=a.useState([]),[d,l]=a.useState(null),[p,u]=a.useState(null),[x,v]=a.useState(!1),[f,w]=a.useState(null),[m,C]=a.useState(!1),[g,y]=a.useState(""),k=a.useRef(null),I=a.useCallback(K=>{k.current=K},[]),j=a.useCallback((K,$,W=!1)=>{c(F=>[...F.slice(-100),{timestamp:Date.now(),level:K,message:$}]),setTimeout(()=>{var F;return(F=i.current)==null?void 0:F.scrollIntoView({behavior:"smooth"})},100),W&&nt.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")},[]),b=a.useCallback(async(K,$)=>{var W;if(!t||d)return!1;l(K),j("info",`Launching ${Oe(K)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const F={ideType:K,enableCdp:!0};(W=$==null?void 0:$.workspace)!=null&&W.trim()?F.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(F.useDefaultWorkspace=!0);const V=await r(t,"launch_ide",F);return j(V!=null&&V.success?"info":"error",V!=null&&V.success?`${Oe(K)} launched`:`Failed: ${V==null?void 0:V.error}`,!0),!!(V!=null&&V.success)}catch(F){return j("error",`Launch error: ${F.message}`,!0),!1}finally{l(null)}},[t,d,j,r]),S=a.useCallback(async K=>{if(!t)return{success:!1};const{cliType:$,dir:W,workspaceId:F,useDefaultWorkspace:V,useHome:te,argsStr:ke,model:J,resumeSessionId:Z}=K;if(!$)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const q=ke?ke.split(/\s+/).filter(Boolean):void 0,xe=(W==null?void 0:W.trim())||(F?"(saved id)":V?"(default workspace)":te?"(home)":"");j("info",`Launching ${$}${xe?` in ${xe}`:""}${J?` (model: ${J})`:""}...`),u($);try{const re={cliType:$,cliArgs:q,initialModel:J||void 0};W!=null&&W.trim()?re.dir=W.trim():F?re.workspaceId=F:V?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?(j("info",`${$} launched`,!0),(ve==null?void 0:ve.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(ve==null?void 0:ve.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ve==null?void 0:ve.sessionId}):(j("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:J}),{success:!1,sessionId:ve==null?void 0:ve.sessionId})}catch(re){return h(re)?(j("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${re.message}`,!0),{success:!1})}finally{u(null)}},[t,j,h,r]),N=a.useCallback(async(K,$,W,F)=>t?K?$.trim()?S({cliType:K,dir:$,argsStr:W,model:F}):(w({cliType:K,argsStr:W,model:F}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[t,j,S]),E=a.useCallback(async(K,$,W)=>{if(t&&window.confirm(`Stop ${K}?
48
- This will terminate the process.`))try{const F=await r(t,"stop_cli",{cliType:K,dir:$,targetSessionId:W});F!=null&&F.success?j("info",`${K} stopped`,!0):j("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){j("error",`Stop failed: ${F.message}`,!0)}},[t,j,r]),D=a.useCallback(async K=>{try{await r(K.daemonId,"restart_ide",{ideType:K.type}),j("info",`${Oe(K.type)} restart initiated`,!0)}catch($){j("error",`Restart failed: ${$.message}`,!0)}},[j,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?j("info",`${Oe(K.type)} stopped`,!0):j("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){j("error",`Stop failed: ${$.message}`,!0)}},[j,r]),T=a.useCallback(async()=>{if(t)try{const K=await r(t,"detect_ides",{});j("info",`Found ${((K==null?void 0:K.result)||[]).length} IDE(s)`,!0)}catch(K){j("error",`Detection failed: ${K.message}`,!0)}},[t,j,r]),L=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?(j("info",`Workspace added: ${K.trim()}`),!0):(j("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return j("error",$.message),!1}finally{v(!1)}},[t,j,r]),_=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?j("info","Workspace removed",!0):j("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){j("error",$.message,!0)}finally{v(!1)}}},[t,j,r]),R=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){j("info",K?"Default workspace updated":"Default workspace cleared",!0);const F=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";F&&(($=k.current)==null||$.call(k,F))}else j("error",(W==null?void 0:W.error)||"workspace_set_default failed",!0)}catch(W){j("error",W.message,!0)}finally{v(!1)}}},[t,j,r]),B=a.useCallback(async K=>{var W;if(!t||!K.trim())return;const $=K.trim();v(!0);try{const F=await r(t,"workspace_set_default",{path:$});F!=null&&F.success?(j("info","Default workspace set from history"),(W=k.current)==null||W.call(k,$)):j("error",(F==null?void 0:F.error)||"Could not set default (path missing on disk?)")}catch(F){j("error",F.message)}finally{v(!1)}},[t,j,r]),Y=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){j("warn",`Live nickname updated, but account sync failed: ${K.message}`)}j("info",`Nickname set to "${g||"(cleared)"}"`),C(!1)}catch(K){j("error",`Failed: ${K.message}`)}},[t,g,s,j,n,r]);return{logs:o,launchingIde:d,launchingAgentType:p,workspaceBusy:x,launchPick:f,setLaunchPick:w,editingNickname:m,setEditingNickname:C,nicknameInput:g,setNicknameInput:y,addLog:j,handleLaunchIde:b,runLaunchCliCore:S,handleLaunchCli:N,handleStopCli:E,handleRestartIde:D,handleStopIde:O,handleDetectIdes:T,handleWorkspaceAdd:L,handleWorkspaceRemove:_,handleWorkspaceSetDefault:R,handleWorkspaceResumePath:B,handleSaveNickname:Y,setOnDefaultWorkspaceChanged:I}}function ju({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:i,actions:o,sendDaemonCommand:c}){const{workspaceBusy:d,handleWorkspaceAdd:l,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,[x,v]=a.useState(!1),[f,w]=a.useState(""),[m,C]=a.useState([]),[g,y]=a.useState(!1),[k,I]=a.useState(""),j=a.useCallback(async E=>{y(!0),I("");try{const D=await nr(c,t,E);w(D.path),C(D.directories)}catch(D){I(D instanceof Error?D.message:"Could not load folder")}finally{y(!1)}},[t,c]),h=a.useCallback(()=>{var D;v(!0);const E=rr(s.platform,[s.defaultWorkspacePath,(D=s.workspaces[0])==null?void 0:D.path]);j(E)},[j,s.defaultWorkspacePath,s.platform,s.workspaces]),b=s.availableMem??s.freeMem,S=s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-b)/s.totalMem*100))):0,N=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(Ls,{icon:e.jsx(xa,{size:16}),label:"Uptime",value:Yo(s.uptime)}),e.jsx(Ls,{icon:e.jsx(ct,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Ls,{icon:e.jsx(Zs,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Ls,{icon:e.jsx(bo,{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(fn,{value:Math.min(Math.round(N/s.cpus*100),100),max:100,label:"CPU Load",color:"#8b5cf6",detail:`${N.toFixed(2)} avg / ${s.cpus} cores`}),e.jsx(fn,{value:S,max:100,label:"Memory",color:"#3b82f6",detail:`${bn(s.totalMem-b)} / ${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(cs,{size:14})," Workspaces"]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),e.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:d,value:s.defaultWorkspaceId||"",onChange:E=>void u(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:er(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))})]}),x&&e.jsx(ar,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:f,directories:m,busy:g,error:k,confirmLabel:"Add workspace",onClose:()=>v(!1),onNavigate:E=>{j(E)},onConfirm:E=>{(async()=>{if(!E)return;await l(E)&&v(!1)})()}})]})}function ku(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 Nu(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 Jn=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Su=[{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 Cu({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[i,o]=a.useState("config"),[c,d]=a.useState("codex-cli"),[l,p]=a.useState([]),[u,x]=a.useState(""),[v,f]=a.useState([]),[w,m]=a.useState(""),C=a.useRef(null),g=a.useRef(null),y=S=>{p(N=>N.includes(S)?N.filter(E=>E!==S):[...N,S])},k=()=>p([...Jn]),I=()=>p([]);a.useEffect(()=>{var S;(S=C.current)==null||S.scrollIntoView({behavior:"smooth"})},[v]),a.useEffect(()=>()=>{g.current&&clearInterval(g.current)},[]);const j=a.useCallback(()=>{g.current&&clearInterval(g.current),g.current=setInterval(async()=>{try{const S=await r(t,"provider_auto_fix_status",{providerType:s.type});(S==null?void 0:S.running)===!1&&i==="running"&&(o("done"),f(N=>[...N,`
50
- ✅ Auto-fix completed!`]),g.current&&clearInterval(g.current))}catch{}},3e3)},[t,s.type,r,i]),h=async()=>{if(l.length!==0){o("running"),f(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${l.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),m("");try{const S=await r(t,"provider_auto_fix",{providerType:s.type,functions:l,agent:c,...u?{comment:u}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(f(N=>[...N,"✅ Agent started. Monitoring progress..."]),j()):(o("error"),m((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){o("error"),m((S==null?void 0:S.message)||"Connection failed")}}},b=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),f(S=>[...S,`
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:S=>S.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:Su.map(S=>e.jsxs("button",{onClick:()=>d(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===S.value?S.color+"66":"var(--border-subtle)",background:c===S.value?S.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===S.value?S.color:"var(--text-primary)"},children:S.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.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:k,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:Jn.map(S=>e.jsxs("button",{onClick:()=>y(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:l.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:l.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[l.includes(S)?"☑ ":"☐ ",S]},S))})]}),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:u,onChange:S=>x(S.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((S,N)=>e.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},N)),i==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:C})]}),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:b,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"),f([]),m("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Iu({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:i}){var j;const o=s.filter(h=>h.category==="ide"),[c,d]=a.useState(((j=o[0])==null?void 0:j.type)||""),[l,p]=a.useState(""),[u,x]=a.useState(""),[v,f]=a.useState(!1),[w,m]=a.useState(""),[C,g]=a.useState(!1),y=h=>{const b=h.toLowerCase().replace(/[^a-z0-9-]/g,"");p(b),(!u||u===k(l))&&x(k(b))},k=h=>h.split("-").map(b=>b.charAt(0).toUpperCase()+b.slice(1)).join(" "),I=async()=>{if(!(!l||!u||!c)){f(!0),m("");try{const h=await r(t,"provider_clone",{type:l,name:u,category:"ide",location:"user",cloneFrom:c});h!=null&&h.success||h!=null&&h.created?(g(!0),i==null||i(l)):m((h==null?void 0:h.error)||"Failed to create provider")}catch(h){m((h==null?void 0:h.message)||"Connection failed")}f(!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:C?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=>y(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:u,onChange:h=>x(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:C?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||!u||v,className:"machine-btn",style:{background:l&&u?"rgba(34,197,94,0.12)":void 0,borderColor:l&&u?"rgba(34,197,94,0.3)":void 0,color:l&&u?"#86efac":void 0,opacity:!l||!u||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Tu({machineId:t,providers:s,sendDaemonCommand:r}){const[n,i]=a.useState([]),[o,c]=a.useState(!1),[d,l]=a.useState(null),[p,u]=a.useState("all"),[x,v]=a.useState(null),[f,w]=a.useState(!1),m=a.useCallback(async()=>{if(t){c(!0);try{const g=await r(t,"get_provider_settings",{}),y=ku(g);if(y){const k=Nu(y,s);k.sort((I,j)=>I.category.localeCompare(j.category)||I.displayName.localeCompare(j.displayName)),i(k)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&m()},[]);const C=async(g,y,k)=>{l(`${g}.${y}`),i(I=>I.map(j=>j.type===g?{...j,values:{...j.values,[y]:k}}:j));try{const I=await r(t,"set_provider_setting",{providerType:g,key:y,value:k});I!=null&&I.success||m()}catch{m()}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:()=>u(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:m,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),p!=="all"&&n.filter(g=>g.category===p).length>1&&(()=>{const g=n.filter(j=>j.category===p),y=new Map;for(const j of g)for(const h of j.schema){if(h.type!=="boolean")continue;const b=y.get(h.key),S=!!(j.values[h.key]??h.default);b?(b.onCount+=S?1:0,b.total+=1):y.set(h.key,{label:h.label||h.key,onCount:S?1:0,total:1})}const k=[...y.entries()].filter(([,j])=>j.total===g.length);if(k.length===0)return null;const I=async(j,h)=>{for(const b of g)await C(b.type,j,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:k.map(([j,h])=>{const b=h.onCount===h.total,S=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(j,!0),disabled:b,className:`machine-btn text-[9px] px-1.5 py-px ${b?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void I(j,!1),disabled:S,className:`machine-btn text-[9px] px-1.5 py-px ${S?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},j)})})]})})(),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(y=>y.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(y=>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:[y.label||y.key,d===`${g.type}.${y.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),y.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:y.description})]}),e.jsx("div",{className:"shrink-0",children:y.type==="boolean"?e.jsx("button",{onClick:()=>C(g.type,y.key,!(g.values[y.key]??y.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:g.values[y.key]??y.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[y.key]??y.default?21:3}})}):y.type==="number"?e.jsx("input",{type:"number",value:Number(g.values[y.key]??y.default??0)||0,min:y.min,max:y.max,onChange:k=>{const I=parseInt(k.target.value)||0;y.min!==void 0&&I<y.min||y.max!==void 0&&I>y.max||C(g.type,y.key,I)},className:"machine-input w-20 text-center text-[11px]"}):y.type==="select"&&y.options?e.jsx("select",{value:String(g.values[y.key]??y.default??""),onChange:k=>C(g.type,y.key,k.target.value),className:"machine-input text-[11px]",children:y.options.map(k=>e.jsx("option",{value:k,children:k},k))}):e.jsx("input",{type:"text",value:String(g.values[y.key]??y.default??""),onBlur:k=>C(g.type,y.key,k.target.value),className:"machine-input w-[120px] text-[11px]"})})]},y.key))})]},g.type))}),x&&e.jsx(Cu,{machineId:t,provider:x,sendDaemonCommand:r,onClose:()=>v(null)}),f&&e.jsx(Iu,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>w(!1),onCreated:()=>{w(!1),m()}})]})}function _u({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[i,o]=a.useState(0),[c,d]=a.useState(!0),[l,p]=a.useState("debug"),u=a.useRef(null),x=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}),m=(w==null?void 0:w.result)||w;if(w!=null&&w.success&&Array.isArray(m==null?void 0:m.logs)&&m.logs.length>0){n(g=>[...g,...m.logs.map(k=>({timestamp:k.ts,level:k.level,message:`[${k.category}] ${k.message}`}))].slice(-300));const C=Math.max(...m.logs.map(g=>g.ts));o(C)}}catch{}};v();const f=setInterval(v,3e3);return()=>clearInterval(f)},[t,c,i,l,s]),a.useEffect(()=>{if(c&&r.length>0){const v=x.current?"smooth":"instant";setTimeout(()=>{var f;(f=u.current)==null||f.scrollIntoView({behavior:v}),x.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,f)=>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})]},f)),e.jsx("div",{ref:u})]})]})}function vr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function wr(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Zn(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 Au(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Mu(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 Lu(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 Pu(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 Ru({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,i]=a.useState(null),[o,c]=a.useState(!0),[d,l]=a.useState(""),[p,u]=a.useState(null),x=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 j=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),h=vr(j);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(j){const h=j instanceof Error?j.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 f=a.useCallback(async(I,j)=>{const h=`${I}:${j.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${j.displayName}?
52
- This will terminate the hosted runtime.`))){u(h);try{const b=await r(t,I,{sessionId:j.sessionId}),S=vr(b);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Session host action failed");const N=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${N}: ${j.displayName}`,"success"),await v({silent:!0})}catch(b){const S=b instanceof Error?b.message:"Session host action failed";nt.showToast(S,"warning"),l(S)}finally{u(b=>b===h?null:b)}}},[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.`)){u("session_host_prune_duplicate_sessions");try{const j=await r(t,"session_host_prune_duplicate_sessions",{}),h=vr(j);if(!(h!=null&&h.success))throw new Error((h==null?void 0:h.error)||"Duplicate prune failed");const b=h.result||{},S=Array.isArray(b.prunedSessionIds)?b.prunedSessionIds.length:0,N=typeof b.duplicateGroupCount=="number"?b.duplicateGroupCount:0;nt.showToast(`Pruned ${S} duplicate runtime(s) across ${N} group(s)`,"success"),await v({silent:!0})}catch(j){const h=j instanceof Error?j.message:"Duplicate prune failed";nt.showToast(h,"warning"),l(h)}finally{u(j=>j==="session_host_prune_duplicate_sessions"?null:j)}}},[v,t,r]),m=a.useMemo(()=>[...(n==null?void 0:n.sessions)||[]].sort((I,j)=>(j.lastActivityAt||0)-(I.lastActivityAt||0)),[n==null?void 0:n.sessions]),C=a.useMemo(()=>Pu(m),[m]),g=a.useMemo(()=>m.reduce((I,j)=>{var h;return I+(((h=j.attachedClients)==null?void 0:h.length)||0)},0),[m]),y=a.useMemo(()=>[...(n==null?void 0:n.recentTransitions)||[]].slice(-6).reverse(),[n==null?void 0:n.recentTransitions]),k=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(Lt,{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:[C>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 (${C})`}),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(us,{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(qt,{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:Zn(n.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:wr(n.hostStartedAt)})]})]}),k&&e.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[e.jsx(qt,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[wr(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[e.jsx(Zs,{size:14})," Hosted Runtimes"]}),m.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:m.map(I=>{var D;const j=p===`session_host_resume_session:${I.sessionId}`,h=p===`session_host_restart_session:${I.sessionId}`,b=p===`session_host_stop_session:${I.sessionId}`,S=Mu(I.meta),N=x.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||(N==null?void 0:N.cliName)||I.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Lu(I.lifecycle)}`,children:I.lifecycle}),S&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),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||(N==null?void 0:N.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:Au(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(Er,{size:11})," ",E]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Zn(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:()=>{f("session_host_resume_session",I)},children:j?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!p,onClick:()=>{f("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:()=>{f("session_host_stop_session",I)},children:b?"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"}),y.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:y.map(I=>{var h;const j=m.find(b=>b.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:(j==null?void 0:j.displayName)||((h=x.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:wr(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 Eu({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 jr({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 kr({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 $u({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=u=>u==="ide"?"IDE":u==="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(jr,{icon:e.jsx(At,{size:13}),children:"Current Chats"}),e.jsx(kr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(u=>{const x=Mr(u);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(u),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:Fe(u)}),x>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:va(x)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Zt(u)})]},u.tabKey)})})})]}),l.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(jr,{icon:e.jsx(xa,{size:13}),children:"Recent Launches"}),e.jsx(kr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(u=>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(u),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:u.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[p(u.kind),u.subtitle?` · ${u.subtitle}`:""]})]},u.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(jr,{icon:e.jsx(qt,{size:13}),children:"Daemon Update"}),e.jsx(kr,{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(us,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Du(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Bu={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 Os(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ku(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 Nr({category:t,machine:s,machineId:r,providers:n,managedEntries:i,getIcon:o,actions:c,sendDaemonCommand:d,initialWorkspaceId:l,initialWorkspacePath:p}){const u=ds(),{handleLaunchIde:x,handleStopCli:v,handleRestartIde:f,handleStopIde:w,handleDetectIdes:m,launchingIde:C,launchingAgentType:g,addLog:y}=c,[k,I]=a.useState(null),j=a.useCallback(P=>{P&&u({pathname:"/",search:`?activeTab=${encodeURIComponent(P)}`})},[u]),h=Bu[t],b=t==="ide",S=t==="acp",N=a.useMemo(()=>n.filter(P=>P.category===t&&(t==="ide"||P.installed!==!1)),[t,n]),E=a.useMemo(()=>new Map(N.map(P=>[P.type,P.displayName||P.type])),[N]),[D,O]=a.useState(""),[T,L]=a.useState(""),[_,R]=a.useState([]),[B,Y]=a.useState(""),[K,$]=a.useState(""),[W,F]=a.useState([]),[V,te]=a.useState(!1),[ke,J]=a.useState(""),[Z,q]=a.useState(!1),[xe,re]=a.useState(null),[he,ve]=a.useState(p?"__custom__":l||s.defaultWorkspaceId||""),[ie,pe]=a.useState(p||""),[oe,ge]=a.useState([]),[X,se]=a.useState(!1),[Q,fe]=a.useState(""),[M,ee]=a.useState([]),[ye,A]=a.useState(!1),[G,z]=a.useState(""),ae=a.useRef(null),[de,Ce]=a.useState(null),Ee=a.useRef("__home__"),[Le,ze]=a.useState("__home__"),[lt,Xe]=a.useState(!1),We=a.useRef(0),at=oe.filter(P=>!i.some(U=>U.type===P&&rt(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(()=>{b||D&&(N.some(P=>P.type===D)||(O(""),$("")))},[N,b,D]);const Ie=(()=>{if(he==="__custom__")return ie.trim();if(!he)return"";const P=(s.workspaces||[]).find(U=>U.id===he);return(P==null?void 0:P.path)||""})(),Je=a.useCallback(P=>{const U=Re.current[P];U&&(clearTimeout(U),delete Re.current[P]),ge(ce=>ce.includes(P)?ce.filter(be=>be!==P):ce)},[]),qe=a.useRef(new Set),H=a.useCallback(async P=>{if(d){A(!0),z("");try{const U=await nr(d,r,P);fe(U.path),pe(U.path),ee(U.directories)}catch(U){z(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 P=rr(s.platform,[ie.trim(),Ie,s.defaultWorkspacePath,(U=s.workspaces[0])==null?void 0:U.path]);H(P)},[ie,H,s.defaultWorkspacePath,s.platform,s.workspaces,Ie,d]),Ne=a.useCallback(P=>{const U=String(P.workspace||"").trim();if(!U)return;const ce=(s.workspaces||[]).find(be=>Os(be.path)===Os(U));if(ce){ve(ce.id),pe("");return}ve("__custom__"),pe(U)},[s.workspaces]),Pe=a.useCallback(P=>{const U=String(P.workspace||"").trim();if(!U)return{workspaceId:null,workspacePath:"",useHome:!0};const ce=(s.workspaces||[]).find(be=>Os(be.path)===Os(U));return ce?{workspaceId:ce.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:U,useHome:!1}},[s.workspaces]),Ge=a.useCallback(async P=>{if(!d||!P||t!=="cli"){F([]),te(!1),J("");return}const U=We.current+1;We.current=U,te(!0),J("");try{const ce=await d(r,"list_saved_sessions",{providerType:P,kind:"cli",limit:30});if(We.current!==U)return;const be=(ce==null?void 0:ce.result)??ce;F(Array.isArray(be==null?void 0:be.sessions)?be.sessions:[])}catch(ce){if(We.current!==U)return;F([]),J(ce instanceof Error?ce.message:"Could not load saved sessions")}finally{We.current===U&&te(!1)}},[t,r,d]),Et=a.useMemo(()=>{if(t!=="cli"||!D)return null;const P=E.get(D)||D;return{ideId:r,daemonId:r,providerSessionId:K||void 0,transport:"pty",mode:"chat",agentName:P,agentType:D,status:"idle",title:P,messages:[],ideType:D,workspaceName:Ie,displayPrimary:P,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${D}`}},[t,r,E,Ie,K,D]),dt=a.useCallback(P=>{if(t==="ide"||!P){R([]);return}R(pi(r,P))},[t,r]);a.useEffect(()=>{if($(""),dt(D),t!=="cli"||!D){F([]),J(""),te(!1);return}Ge(D)},[t,dt,Ge,D]),a.useEffect(()=>{if(!K)return;const P=W.find(U=>U.providerSessionId===K);P!=null&&P.canResume||$("")},[W,K]);const xt=a.useCallback((P,U)=>{ae.current=U,Ee.current=P.selectedWorkspaceKey||"__home__",ze(P.selectedWorkspaceKey||"__home__"),Ce(P)},[]),$t=a.useCallback(()=>{ae.current&&(Xe(!0),ae.current().finally(()=>{ae.current=null,Xe(!1),Ce(null)}))},[]),kt=a.useCallback(P=>{if(!P)return;ge(ce=>ce.includes(P)?ce:[...ce,P]);const U=Re.current[P];U&&clearTimeout(U),Re.current[P]=setTimeout(()=>{ge(ce=>ce.includes(P)?ce.filter(be=>be!==P):ce),delete Re.current[P]},2e4)},[]);a.useEffect(()=>{for(const U of i)rt(U.status)!=="stopped"&&(oe.includes(U.type)&&!qe.current.has(U.type)&&(qe.current.add(U.type),y("info",`${E.get(U.type)||U.type} launched`,!0)),Je(U.type));const P=new Set(i.filter(U=>rt(U.status)!=="stopped").map(U=>U.type));qe.current.forEach(U=>{!oe.includes(U)&&!P.has(U)&&qe.current.delete(U)})},[y,Je,i,oe,E]),a.useEffect(()=>()=>{Object.values(Re.current).forEach(clearTimeout),Re.current={}},[]);const[yt,Nt]=a.useState({}),[Ae,Dt]=a.useState(null);a.useEffect(()=>{if(!b||!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)&&Nt(ce.ideExtensions)}catch{}})()},[b,r,d]);const es=P=>b?Oe(P.type):t==="cli"?P.cliName:P.acpName,ne=b?s.detectedIdes||[]:[],$e=a.useCallback(async P=>{const U=(P==null?void 0:P.type)||D,ce=(P==null?void 0:P.workspacePath)??Ie;if(b){await x(U,ce?{workspace:ce}:void 0)&&kt(U);return}const be=await c.runLaunchCliCore({cliType:U,dir:P!=null&&P.workspaceId?void 0:ce||void 0,workspaceId:(P==null?void 0:P.workspaceId)||void 0,useHome:(P==null?void 0:P.useHome)||!(P!=null&&P.workspaceId)&&!ce,argsStr:(P==null?void 0:P.argsStr)??(T||void 0),model:(P==null?void 0:P.model)??(S&&B||void 0),resumeSessionId:(P==null?void 0:P.resumeSessionId)||!S&&t==="cli"&&U===D&&K||void 0});if(be.success||be.pending){const Te=(P==null?void 0:P.argsStr)??T;!b&&(Te!=null&&Te.trim())&&(fi(r,U,Te),dt(U)),kt(U),be.success&&be.sessionId&&j(be.sessionId)}},[c,x,S,b,T,B,dt,kt,r,j,Ie,K,D]),vt=()=>{var be;const P=b?Oe(D):E.get(D)||D,{options:U,selectedKey:ce}=Vt({machine:s,currentWorkspaceId:he&&he!=="__custom__"?he:null,currentWorkspacePath:Ie});xt({title:`Launch ${P}?`,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:P},...!b&&t==="cli"&&K?[{label:"Resume",value:((be=W.find(Te=>Te.providerSessionId===K))==null?void 0:be.title)||K}]:[],...!b&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...S&&B.trim()?[{label:"Model",value:B.trim()}]:[]]},async()=>{const Te=U.find(Se=>Se.key===Ee.current);Te!=null&&Te.workspaceId?(ve(Te.workspaceId),pe("")):Te!=null&&Te.workspacePath?(ve("__custom__"),pe(Te.workspacePath)):(ve(""),pe("")),await $e({workspaceId:(Te==null?void 0:Te.workspaceId)??null,workspacePath:(Te==null?void 0:Te.workspacePath)??"",useHome:!(Te!=null&&Te.workspaceId)&&!(Te!=null&&Te.workspacePath)})})},St=P=>{b?w(P):v(P.type,P.workspace,P.id)},wt=a.useCallback(async(P,U,ce=!1)=>{if(P.mode===U){ce&&P.sessionId&&j(P.sessionId);return}if(!d||!P.sessionId){ce&&P.sessionId&&j(P.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:P.type,mode:U}),ce&&j(P.sessionId)}catch(be){Ku(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,j,d]),Ct=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:P=>{const U=P.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(P=>e.jsxs("option",{value:P.id,children:[P.id===s.defaultWorkspaceId?"⭐ ":"",er(P.path,P.label)]},P.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:P=>pe(P.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:b?ne.length>0?ne.map(P=>{const U=i.find(Ke=>(Ke.type||"").toLowerCase()===(P.type||"").toLowerCase()&&rt(Ke.status)!=="stopped"),ce=P.running||!!U,be=!!U&&U.cdpConnected,Te=oe.includes(P.type||P.id||""),Se=D===(P.type||"");return e.jsxs("button",{onClick:()=>{if(be&&U){const Ke=U.sessionId;Ke?u(`/dashboard?activeTab=${encodeURIComponent(Ke)}`,{state:{openRemoteForTabKey:Ke}}):u("/dashboard",{state:{openRemoteForTabKey:U.id}});return}Te||O(Ke=>Ke===(P.type||"")?"":P.type||"")},disabled:!!C||Te,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:C&&C!==P.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(P.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:P.name||Oe(P.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${be?"text-green-400":Te?"text-orange-400":Se?"text-accent-primary":"text-text-muted"}`,children:be?"Open Session":Te?"Starting...":Se?"Configure":"Select"})]})]},P.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:m,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(mo,{size:14})," Scan System"]})]}):N.length>0?N.map(P=>{const U=D===P.type,ce=oe.includes(P.type),Te=!!i.find(Se=>Se.type===P.type&&rt(Se.status)!=="stopped");return e.jsxs("button",{onClick:()=>O(Se=>Se===P.type?"":P.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:P.icon}),Te&&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:P.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"})]})]},P.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&&(b?ne.find(P=>P.type===D):N.find(P=>P.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:b?Oe(D):E.get(D)||D})]}),Ct,!b&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!S&&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 Ge(D),disabled:!D||V,children:V?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{D&&(q(!0),Ge(D))},disabled:!D,children:"Open History"})]})]}),K?(()=>{const P=W.find(U=>U.providerSessionId===K);return P?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:P.title||P.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:P.providerSessionId}),e.jsx("div",{children:P.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:[S&&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:P=>Y(P.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:T,onChange:P=>L(P.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(P=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(P),title:P,children:P},P))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:vt,disabled:!!g||!!C||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||C===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(P=>!i.some(U=>U.type===P&&rt(U.status)!=="stopped")).length,")"]}),i.length===0&&at.length===0?e.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",h.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map(P=>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(P)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:b?Oe(P):E.get(P)||P}),e.jsx("div",{className:"text-[11px] text-text-muted",children:g===P?"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:${P}`)),i.map(P=>{const U=b?P:null,ce=S?P:null,be=!b&&!S?P:null,Te=rt(P.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(P.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[es(P),(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:P.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(Ke=>Ke===be.runtimeKey?null:Ke)},1200)},children:k===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:Du(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 ${Te==="stopped"?"bg-red-500/[0.08] text-red-500":Te==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Te}),b&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Se=P.sessionId;if(Se){u(`/dashboard?activeTab=${encodeURIComponent(Se)}`,{state:{openRemoteForTabKey:Se}});return}u("/dashboard",{state:{openRemoteForTabKey:P.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=P.workspace||"",{options:Ke,selectedKey:et}=Vt({machine:s,currentWorkspacePath:Se});xt({title:`Restart ${Oe(P.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Ke,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Oe(P.type)}]},async()=>{const ut=Ke.find(ps=>ps.key===Ee.current),Ze=(ut==null?void 0:ut.workspacePath)??"";if(Ze&&Ze!==Se){await $e({type:P.type,workspacePath:Ze});return}await f(P)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:e.jsx(us,{size:14})})]}),S&&e.jsx("button",{onClick:()=>{const Se=P.sessionId;Se&&j(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:!P.sessionId,children:e.jsx(At,{size:14})}),be&&Te!=="stopped"&&e.jsxs(e.Fragment,{children:[be.mode&&e.jsx(zr,{mode:be.mode,onChange:Se=>void wt(be,Se,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Se=P.sessionId;Se&&j(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:!P.sessionId,children:be.mode==="chat"?e.jsx(At,{size:14}):e.jsx(ct,{size:13})})]}),Te==="stopped"?e.jsx("button",{onClick:()=>{const Se=P.workspace||"",Ke=b?Oe(P.type):es(P),{options:et,selectedKey:ut}=Vt({machine:s,currentWorkspacePath:Se});xt({title:`Launch ${Ke}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:et,selectedWorkspaceKey:ut,details:[{label:"Mode",value:h.label},{label:"Provider",value:Ke}]},async()=>{const Ze=et.find(ps=>ps.key===Ee.current);await $e({type:P.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(P.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(P.type)?"⏳":e.jsx(Dr,{size:14})}):e.jsx("button",{onClick:()=>St(P),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(ft,{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] ${ka(Se.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Se.name," · ",rt(Se.status)]},Se.id))}),U&&(yt[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:(yt[U.type]||[]).map(Se=>e.jsxs("button",{disabled:Ae===`${U.type}.${Se.type}`,onClick:async()=>{const Ke=`${U.type}.${Se.type}`;Dt(Ke);try{await d(r,"set_ide_extension",{ideType:U.type,extensionType:Se.type,enabled:!Se.enabled}),Nt(et=>({...et,[U.type]:(et[U.type]||[]).map(ut=>ut.type===Se.type?{...ut,enabled:!ut.enabled}:ut)}))}catch(et){console.error("Extension toggle failed:",et)}finally{Dt(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))})]})]},P.id)})]}),X&&d&&e.jsx(ar,{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:G,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:P=>{H(P)},onConfirm:P=>{pe(P),ve("__custom__"),se(!1)}}),de&&e.jsx(Xr,{title:de.title,description:de.description,details:de.details,workspaceOptions:de.workspaceOptions,selectedWorkspaceKey:Le,onWorkspaceChange:P=>{Ee.current=P,ze(P)},confirmLabel:de.confirmLabel,busy:lt,onConfirm:$t,onCancel:()=>{ae.current=null,Ce(null)}}),Z&&Et&&e.jsx(Ur,{activeConv:Et,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:W,isSavedSessionsLoading:V,isResumingSavedSessionId:xe,onClose:()=>q(!1),onNewChat:()=>{$(""),q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ge(D)},onResumeSavedSession:P=>{if(!P.canResume||xe)return;const U=Pe(P);$(P.providerSessionId),Ne(P),re(P.providerSessionId),q(!1),$e({type:P.providerType,workspaceId:U.workspaceId,workspacePath:U.workspacePath,useHome:U.useHome,resumeSessionId:P.providerSessionId}).finally(()=>{re(ce=>ce===P.providerSessionId?null:ce)})}})]})}const Qn=[{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 Wu({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:i,acpSessions:o,actions:c,getIcon:d,initialCategory:l="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:x}){var m;const[v,f]=a.useState(l);a.useEffect(()=>{f(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:Qn.map(C=>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===C.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>f(C.id),children:[e.jsx("span",{children:C.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===C.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:w[C.id]})]},C.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(m=Qn.find(C=>C.id===v))==null?void 0:m.helper})]}),v==="ide"&&e.jsx(Nr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u}),v==="cli"&&e.jsx(Nr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u}),v==="acp"&&e.jsx(Nr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u})]})}function Ou({onNicknameSynced:t}={}){var ve,ie,pe,oe,ge,X,se,Q,fe;const{id:s}=qi(),r=ds(),n=Pr(),{sendCommand:i}=Rt(),o=Aa(),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"),[u,x]=a.useState("workspace"),[v,f]=a.useState("ide"),w=a.useRef(null),[m,C]=a.useState(null),g=a.useRef("__home__"),[y,k]=a.useState("__home__"),[I,j]=a.useState(!1),h=a.useRef(null),b=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},S=wu({machineId:s,registeredMachineId:(l==null?void 0:l.machineId)||null,sendDaemonCommand:i,onNicknameSynced:t,logsEndRef:h});a.useEffect(()=>nt.onToast(ee=>{o.setToasts(A=>{if(A.some(ae=>ae.message===ee.message&&ee.timestamp-ae.timestamp<3e3))return A;const z={id:ee.id,message:ee.message,type:ee.type,timestamp:ee.timestamp,targetKey:ee.targetKey,actions:ee.actions};return[...A.slice(-4),z]});const ye=ee.duration||5e3;setTimeout(()=>o.setToasts(A=>A.filter(G=>G.id!==ee.id)),ye)}),[o]);const N=(l==null?void 0:l.availableProviders)||[],E={};for(const M of N)E[M.type]=M.icon;const D=M=>E[M]||"",O=l?{id:l.id,hostname:Na(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:(X=l.machine)==null?void 0:X.availableMem,loadavg:((se=l.machine)==null?void 0:se.loadavg)||[],uptime:((Q=l.machine)==null?void 0:Q.uptime)||0,release:((fe=l.machine)==null?void 0:fe.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,T=c.filter(M=>M.daemonId===s&&!M.daemonMode).filter(M=>!Ss(M)&&!as(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:tc(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})),L=c.filter(M=>M.daemonId===s&&Ss(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})),_=c.filter(M=>M.daemonId===s&&as(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})),R=l?ot(l,{fallbackId:s}):"",B="workspace",Y=n.state,K=Y==null?void 0:Y.initialMachineTab,$=Y==null?void 0:Y.initialWorkspaceCategory,W=Y==null?void 0:Y.initialWorkspaceId,F=Y==null?void 0:Y.initialWorkspacePath,V=K==="ides"||K==="clis"||K==="acps"?"workspace":K||B,te=K==="ides"?"ide":K==="clis"?"cli":K==="acps"?"acp":$,ke=[...T.map(M=>{var ee,ye,A,G,z;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:((z=(G=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:G.call(A,-1))==null?void 0:z.timestamp)||0}}),...L.map(M=>{var ee,ye,A,G,z;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:((z=(G=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:G.call(A,-1))==null?void 0:z.timestamp)||0}}),..._.map(M=>{var ee,ye,A,G,z;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:((z=(G=(A=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:A.at)==null?void 0:G.call(A,-1))==null?void 0:z.timestamp)||0}})].sort((M,ee)=>ee.timestamp-M.timestamp).map(({timestamp:M,...ee})=>ee),J=((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)=>Mr(A)-Mr(ye))},[c,o.connectionStates,s]),q=a.useCallback(M=>{const ee=M.sessionId||M.tabKey;ee&&r(`/dashboard?activeTab=${encodeURIComponent(ee)}`)},[r]),xe=a.useCallback(()=>{w.current&&(j(!0),w.current().finally(()=>{w.current=null,j(!1),C(null)}))},[]),re=a.useCallback(M=>{if(!O)return;const{options:ee,selectedKey:ye}=Vt({machine:O,currentWorkspacePath:M.workspace}),A=async()=>{f(M.kind),x("workspace")};w.current=async()=>{const G=ee.find(de=>de.key===g.current),z=(G==null?void 0:G.workspacePath)??null,ae=(G==null?void 0:G.workspaceId)??null;if(M.kind==="ide"&&M.providerType){await S.handleLaunchIde(M.providerType,z?{workspace:z}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await S.runLaunchCliCore({cliType:M.providerType,dir:ae?void 0:z||"",workspaceId:ae||void 0,model:M.kind==="acp"?M.currentModel:void 0,resumeSessionId:M.providerSessionId});return}await A()},g.current=ye,k(ye),C({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}]:[]]})},[S,O]);if(a.useEffect(()=>{x(V)},[B,V,s]),a.useEffect(()=>{te&&f(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:b,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:T.length+L.length+_.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Lt,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Js,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fo,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(lo,{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:b,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:[S.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:S.nicknameInput,onChange:M=>S.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&S.handleSaveNickname(),M.key==="Escape"&&S.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:S.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:()=>S.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:()=>{S.setEditingNickname(!0),S.setNicknameInput(O.machineNickname||"")},title:"Click to set nickname",children:R}),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:()=>x(M.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${u===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 ${u===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:[u==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx($u,{machineEntry:l,providers:N,recentLaunches:J,currentConversations:Z,onUpgradeDaemon:async()=>{try{await i(s,"daemon_upgrade",{})}catch{}},onOpenRecent:re,onOpenConversation:q}),e.jsx(Wu,{machine:O,machineId:s,providers:N,ideSessions:T,cliSessions:L,acpSessions:_,actions:S,getIcon:D,initialCategory:v,initialWorkspaceId:W,initialWorkspacePath:F,sendDaemonCommand:i})]}),u==="providers"&&e.jsx(Tu,{machineId:s,providers:N,sendDaemonCommand:i}),u==="overview"&&e.jsx(ju,{machineId:s,machine:O,ideSessions:T,cliSessions:L,acpSessions:_,actions:S,sendDaemonCommand:i}),u==="session-host"&&e.jsx(Ru,{machineId:s,cliSessions:L,sendDaemonCommand:i}),u==="logs"&&e.jsx(_u,{machineId:s,sendDaemonCommand:i})]})})}),S.launchPick&&O&&e.jsx(Eu,{machine:O,launchPick:S.launchPick,actions:S}),m&&e.jsx(Xr,{title:m.title,description:m.description,details:m.details,workspaceOptions:m.workspaceOptions,selectedWorkspaceKey:y,onWorkspaceChange:M=>{g.current=M,k(M)},confirmLabel:m.confirmLabel,busy:I,onConfirm:xe,onCancel:()=>{w.current=null,C(null)}}),e.jsx(Ea,{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
- `})]})}class zu{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 It=new zu;function Uu(){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 ea=Uu(),ta=3e3,Hu=3e4;let Tt=null,Fu=0;const Xs=new Map;let Wt=null,ws=null;function sa(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Vu(t){return t==="connected"?"connected":t}async function Gs(t,s,r){const n=$c(t,r||{}),i=Tt;if(i&&i.readyState===WebSocket.OPEN){const o=`req_${++Fu}_${Date.now()}`;return new Promise((c,d)=>{const l=setTimeout(()=>{Xs.delete(o),d(new Error(`WS command timeout: ${s}`))},3e4);Xs.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 Gu{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Tt==null?void 0:Tt.readyState)===WebSocket.OPEN}get connectionState(){return(Tt==null?void 0:Tt.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,Wt&&(clearInterval(Wt),Wt=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());It.emitScreenshot(this.daemonId,i)}}catch{}};r(),Wt=setInterval(r,2e3)}stopScreenshots(s){Wt&&(clearInterval(Wt),Wt=null)}}let pt=null;function qu(t){return(!pt||pt.daemonId!==t)&&(pt=new Gu(t)),pt}function Yu({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,f)=>{o(v),ws==null||ws(v,f)},[]),d=a.useRef(null),l=a.useRef(),p=a.useRef(ta),u=a.useRef(!0),x=a.useRef(!1);return a.useEffect(()=>{u.current=!0,x.current=!1;function v(){var m,C;if(!u.current||((m=d.current)==null?void 0:m.readyState)===WebSocket.OPEN||((C=d.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${ea}...`);let w;try{w=new WebSocket(ea)}catch(g){console.error("[Standalone WS] Failed to create WebSocket:",g),f();return}d.current=w,w.onopen=()=>{if(!u.current){w.close();return}c("connected"),p.current=ta,console.log("[Standalone WS] Connected")},Tt=w,w.onmessage=g=>{var y;try{const k=JSON.parse(g.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const I=Xs.get(k.requestId);I&&(Xs.delete(k.requestId),k.type==="error"?I.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):I.resolve(k.data));return}if(k.type==="session_output"){const I=k.sessionId||k.cliId||k.cliType;I&&It.emitSessionOutput(I,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){It.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="status"||k.type==="initial_state"){const I=k.data;if(!I)return;const{injectEntries:j,markLoaded:h}=s.current,b=I.id||"standalone",S=qu(b);It.register(b,S),It.setState(b,"connected"),c("connected",b),It.emitStatus(b,I);const N=Rc(I,{daemonId:b});sa("ws_status",{type:k.type,daemonId:b,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}))}),sa("entries",{daemonId:b,entries:N.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}))}),N.length>0&&j(N,{authoritativeDaemonIds:[b]}),h(),I.userName&&i.current&&i.current(I.userName)}}catch(k){console.error("[Standalone WS] Parse error:",k)}},w.onclose=()=>{u.current&&(pt==null||pt.stopScreenshots(),pt&&It.setState(pt.daemonId,"disconnected"),c("disconnected"),d.current=null,f())},w.onerror=g=>{x.current||!u.current||console.warn("[Standalone WS] Error, will reconnect:",g)}}function f(){if(!u.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,Hu),v()},w)}return v(),()=>{u.current=!1,x.current=!0,clearTimeout(l.current),d.current&&(d.current.onerror=null,d.current.onclose=null,d.current.close(),d.current=null,Tt=null),pt&&(pt.stopScreenshots(),It.unregister(pt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function Xu({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=Vu(s),l={};return n&&(l[n]=d),l.standalone=d,{wsStatus:s,isConnected:c,connectionStates:l}},[s,n]);return e.jsx(to,{connectionOverrides:o,children:e.jsx(Yu,{children:t})})}const Ju=[{id:"dashboard",path:"/dashboard",icon:e.jsx(ua,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Lt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(Js,{}),label:"Settings"}];function Zu({children:t}){const s=ds(),r=Pr(),[n,i]=a.useState(!1),[o,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=u=>{s(u),i(!1)},l=()=>{c(u=>{const x=!u;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},p=u=>`nav-item${r.pathname.startsWith(u)?" active":""} cursor-pointer ${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:u=>u.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:Ju.map(u=>e.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>d(u.path),title:o?u.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:u.icon}),!o&&u.label]},u.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(ma,{})}),!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(pa,{})}),!o&&"About"]}),!o&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.35"]}),e.jsx(fl,{collapsed:o}),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(Lt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(At,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(fa,{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(js,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(ma,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],em=[{icon:e.jsx(ha,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(ua,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(Qs,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(co,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(Er,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(uo,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],tm=[{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 sm(){return e.jsxs(Ua,{icon:e.jsx(pa,{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.35"]}),children:[e.jsx(bt,{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(bt,{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(bt,{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:Ba.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Wa.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Ka.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(bt,{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:em.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(bt,{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:tm.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(Ha,{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(Co,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function rm(){const{ides:t}=Gt(),s=t.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Rt(),{userName:i}=Gt(),[o,c]=a.useState(i||"");a.useEffect(()=>{i!==void 0&&c(i)},[i]);const d=x=>{const v=x.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}}),u=x=>{p(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return e.jsxs(Ua,{icon:e.jsx(Js,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(cl,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(bt,{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.35"]}),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(bt,{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(x=>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 ${x.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:x.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:x.type})]},x.type))})}),e.jsx(bt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(bl,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(bt,{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(wl,{})]}),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(_l,{})]}),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(Ml,{})]})]})}),e.jsx(bt,{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(xl,{}),e.jsx(Ot,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(So,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:l,onChange:u})]})}),e.jsx(bt,{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(oo,{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:x=>c(x.target.value),onBlur:d,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}pl();Il();const nm=la({baseUrl:""});function ra(){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(Sr,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Sr,{to:"/dashboard",replace:!0})}function am(){return e.jsx(Yi,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(no,{client:nm,children:e.jsx(Xu,{children:e.jsx(io,{value:{sendCommand:Gs,sendData:()=>!1},children:e.jsx(Zu,{children:e.jsxs(Xi,{children:[e.jsx(Bt,{path:"/dashboard",element:e.jsx(vu,{})}),e.jsx(Bt,{path:"/machine",element:e.jsx(ra,{})}),e.jsx(Bt,{path:"/machines/:id",element:e.jsx(Ou,{})}),e.jsx(Bt,{path:"/machines",element:e.jsx(ra,{})}),e.jsx(Bt,{path:"/about",element:e.jsx(sm,{})}),e.jsx(Bt,{path:"/settings",element:e.jsx(rm,{})}),e.jsx(Bt,{path:"*",element:e.jsx(Sr,{to:"/dashboard",replace:!0})})]})})})})})})}gc({connectionManager:It});Ji(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(am,{})}));