@adhdev/daemon-standalone 0.8.18 → 0.8.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-CKqklWLC.js","assets/vendor-CPghmr9Y.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var Va=Object.defineProperty;var Ga=(t,s,r)=>s in t?Va(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var qe=(t,s,r)=>Ga(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as Sn,a as Cn,b as qa,c as Ya,u as zt,R as Ve,t as Xa,d as Ja,e as Za,D as Qa,f as ei,g as ti,h as dr,i as si,k as ri,B as ni,l as ai,m as yt,N as er,n as ii}from"./vendor-CPghmr9Y.js";import{_ as oi}from"./terminal-CKqklWLC.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 In=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}),Tn=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function $r(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 zs(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 Ss(t){return Array.isArray(t)?t.map(Ss):!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,Ss(r)]))}function ci(t,s){try{return JSON.stringify(Ss(t))===JSON.stringify(Ss(s))}catch{return!1}}function us(t,s,r){return ci(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function li(t,s,r){var l,f,m,x,h,p,j;const n=Date.now(),i=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(u=>({...u,_lastUpdate:n}));const o=new Map;for(const u of s)o.set(u.id,u);for(const u of t){const b=o.get(u.id);if(!b){o.set(u.id,{...u,_lastUpdate:n});continue}const g=$r(u),v=$r(b);if(g>v){const S=(l=u.chats)!=null&&l.length?u.chats:b.chats,R=zs(b,u,{...b,...u,chats:S,_lastUpdate:n});o.set(u.id,us(b,R,n))}else if(g<v){const S={};if(u.status&&u.status!==b.status&&(S.status=u.status),u.cdpConnected!==void 0&&(S.cdpConnected=u.cdpConnected),(f=u.chats)!=null&&f.length&&!((m=b.chats)!=null&&m.length)&&(S.chats=u.chats),u.machineNickname!==void 0&&u.machineNickname!==b.machineNickname&&(S.machineNickname=u.machineNickname),u.version!==void 0&&(S.version=u.version),u.serverVersion!==void 0&&(S.serverVersion=u.serverVersion),u.versionMismatch===!0&&(S.versionMismatch=!0),Object.keys(S).length>0){const R=zs(b,u,{...b,...S,_lastUpdate:b._lastUpdate});o.set(u.id,us(b,R,n))}else us(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const S=u.timestamp||n,R=b._lastUpdate||b.timestamp||0;if(S>=R){const w=(x=u.chats)!=null&&x.length?u.chats:b.chats,N=zs(b,u,{...b,...u,chats:w,_lastUpdate:n});o.set(u.id,us(b,N,n))}else(h=u.chats)!=null&&h.length&&!((p=b.chats)!=null&&p.length)&&o.set(u.id,{...b,chats:u.chats})}}const c=new Set(t.map(u=>u.id)),d=new Set;for(const u of t){const b=u.daemonId||((j=u.id)==null?void 0:j.split(":")[0]);b&&d.add(b)}for(const[u,b]of o){const g=b.daemonId||u.split(":")[0];if(!d.has(g))continue;if(i.has(g)&&!c.has(u)){o.delete(u);continue}const v=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(u)&&v>1e4||b.transport==="acp"&&!c.has(u)&&v>1e4||b.transport==="cdp-page"&&!c.has(u)&&v>3e4)&&o.delete(u)}for(const[u,b]of o)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&o.delete(u);return Array.from(o.values())}function di(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function ui({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[i,o]=a.useState(!1),[c,d]=a.useState([]),[l,f]=a.useState(void 0),m=a.useRef(r);a.useEffect(()=>{m.current=r},[r]);const x=a.useCallback((g,v)=>{n(S=>{let R=!1;const w=S.map(N=>N.id!==g||N.chats===v?N:(R=!0,{...N,chats:v}));return R?w:S})},[]),h=a.useCallback((g,v)=>{n(S=>{const R=S.length===0?g:li(g,S,v);return di(S,R)?S:R})},[]),p=a.useCallback(()=>o(!0),[]),j=a.useMemo(()=>({injectEntries:h,markLoaded:p,getIdes:()=>m.current}),[h,p]),u=s,b=a.useMemo(()=>({ides:r,updateIdeChats:x,initialLoaded:i,toasts:c,setToasts:d,wsStatus:(u==null?void 0:u.wsStatus)??"connected",isConnected:(u==null?void 0:u.isConnected)??!0,connectionStates:(u==null?void 0:u.connectionStates)??{},connectionTransports:(u==null?void 0:u.connectionTransports)??{},showReconnected:(u==null?void 0:u.showReconnected)??!1,retryConnection:u==null?void 0:u.retryConnection,isP2PActive:(u==null?void 0:u.isP2PActive)??!1,p2pStates:(u==null?void 0:u.p2pStates)??{},userRole:u==null?void 0:u.userRole,userName:l,setUserName:f}),[r,x,i,c,u==null?void 0:u.wsStatus,u==null?void 0:u.isConnected,u==null?void 0:u.connectionStates,u==null?void 0:u.connectionTransports,u==null?void 0:u.showReconnected,u==null?void 0:u.retryConnection,u==null?void 0:u.isP2PActive,u==null?void 0:u.p2pStates,u==null?void 0:u.userRole,l]);return e.jsx(Tn.Provider,{value:j,children:e.jsx(In.Provider,{value:b,children:t})})}function Xt(){return a.useContext(In)}function Dr(){return a.useContext(Tn)}function _n(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(),f=i(d),m=d.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return l&&m.searchParams.set("token",l),!d.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(d,l={}){const f={"Content-Type":"application/json",...l.headers||{}},m=r==null?void 0:r();m&&(f.Authorization=`Bearer ${m}`);const x=i(d),h=await fetch(x,{...l,headers:f});if(h.status===401)throw n==null||n(),new Error("Unauthorized");if(!h.ok){const p=await h.json().catch(()=>({error:h.statusText}));throw new Error(p.error||`API Error: ${h.status}`)}return h.json()}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,l,f={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:l,payload:f})}),execTerminal:(d,l,f)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:l,name:f})}),sendAgentMessage:(d,l,f)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:l,message:f})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,l,f)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:l,action:f?"approve":"reject"})}),getMuxState:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/state`),getMuxSocketInfo:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/socket-info`),controlMux:(d,l,f={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:l,payload:f})}),getMuxEventsUrl:d=>o(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>o(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const pi=_n({baseUrl:"http://localhost:3847"}),mi=a.createContext(pi);function fi({client:t,children:s}){return e.jsx(mi.Provider,{value:t,children:s})}const xi={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},An=a.createContext(xi);function hi({value:t,children:s}){return e.jsx(An.Provider,{value:t,children:s})}function jt(){return a.useContext(An)}const Le={size:18};function Mn({size:t=Le.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 ur({size:t=Le.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 Cs({size:t=Le.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 bi({size:t=Le.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 gi({size:t=Le.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 yi({size:t=Le.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 Is({size:t=Le.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 vi({size:t=Le.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 Ps({size:t=Le.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 Pn({size:t=Le.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 Ln({size:t=Le.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 gt({size:t=Le.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 st({size:t=Le.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 pr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),e.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function wi({size:t=Le.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 Wt({size:t=Le.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 mr({size:t=Le.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 fr({size:t=Le.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 _t({size:t=Le.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 Rn({size:t=Le.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 ji({size:t=Le.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 En({size:t=Le.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 ki({size:t=Le.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 xr({size:t=Le.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 hr({size:t=Le.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 Ni({size:t=Le.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 At({size:t=Le.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 $n({size:t=Le.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 Si({size:t=Le.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 Ci({size:t=Le.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 Ii({size:t=Le.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 Ls({size:t=Le.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 Ti({size:t=Le.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 _i({size:t=Le.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 Ai({size:t=Le.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 Mi({size:t=Le.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 Pi(t){var l,f;const s=m=>m.replace(/^\d+;/,"").replace(/\u0007/g,"").trim(),n=t.split(`
3
+ `).map(m=>{if(!m.includes("\r"))return m;const x=m.split("\r").map(j=>j.trim()).filter(Boolean);if(x.length===0)return"";const h=x.filter(j=>j.startsWith("⏺"));if(h.length>0)return h[h.length-1];const p=x.filter(j=>!(/^[❯›>]\s*$/.test(j)||/^[^a-zA-Z0-9\s]\s*\S+[…\.]{1,3}\s*$/.test(j)&&j.length<40||/^[╭╰│├╮╯─═]+$/.test(j)));return p.length>0?p[p.length-1]:x[x.length-1]}).join(`
4
+ `).split(`
5
+ `),i={},o=[];let c=!1;for(const m of n){const x=s(m);if(x===""){c=!1,o.push("");continue}if(/^❯\s*$/.test(x)||/^>\s*$/.test(x)||/^[✡-✩✪-✿⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏◆◇◐◑◒◓]\s*\S+[…\.]{1,3}\s*$/.test(x)||/^◐\s/.test(x)||/\/effort/.test(x)||/^⎿\s+(Tip|Note|Hint):/.test(x)||/^\?\s*(for\s*shortcuts|shortcuts)/.test(x)||/esc\s+to\s+interrupt|shift\+tab\s+to\s+cycle|accept\s+edits\s+on/i.test(x)||/Brewing[…\.]{0,3}\s*\d*$/i.test(x)||/^[✢✳✶✻⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏◆◇✦\s]+$/.test(x)||/^Auto-updating/i.test(x)||/^✳\s*Debug (?:Claude Code|Codex) CLI/i.test(x)||/^(?:─|═|╭|╰|│|├|╮|╯|┌|┐|└|┘|┬|┴|┼)+$/.test(x))continue;if(/^[⏺●·⏵]/.test(m)){const p=m.match(/^[⏺●·]\s*([A-Za-z][A-Za-z0-9_]*)\s*[\(\[]/);if(p)i[p[1]]=(i[p[1]]||0)+1;else{const j=m.replace(/^[⏺●·⏵]\s*/,"").trim().slice(0,40);j&&(i[j]=(i[j]||0)+1)}c=!0;continue}if(/^(?:Bash|Read|Write|Edit|MultiEdit|Task|Glob|Grep|LS|NotebookEdit|Exact output)(?:\(|:)/.test(x)){const p=((f=(l=x.match(/^([A-Za-z][A-Za-z0-9_ ]+)/))==null?void 0:l[1])==null?void 0:f.trim())||"Tool";i[p]=(i[p]||0)+1,c=!0;continue}if(/^Read\s+\d+\s+files?(?:\s+\(.*\))?$/i.test(x)){i.Read=(i.Read||0)+1,c=!0;continue}if(/^[\s]*[╭╰│├╮╯]/.test(m)||/^[╭╰│├╮╯─]+/.test(x)||/^\s+[⊙✓✗○◎▸►✦]/.test(m)||c&&/^\s{2,}/.test(m))continue;c=!1;const h=x.replace(/^❯\s+/,"");o.push(h)}const d=o.join(`
6
+ `).replace(/\n{3,}/g,`
7
+
8
+ `).trim();return{toolCounts:i,textContent:d,hasTools:Object.keys(i).length>0}}function tr(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Li(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function $t(t,s){const r=t,n=typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(o=>(o==null?void 0:o.text)||"").join(`
9
+ `):String(r.content||"");return[r.id?`id:${r.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof r.index=="number"?`msgIndex:${r.index}`:"",r.timestamp?`ts:${r.timestamp}`:"",r.role?`role:${r.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const Br=700,Ri=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(Sn,{remarkPlugins:[Cn],children:s.text}),e.jsx("span",{className:"action-time",children:tr(s.timestamp)})]})},(t,s)=>t.log===s.log),Ei=a.memo(function({message:s,receivedAt:r,agentName:n,userName:i,isCliMode:o,isExpanded:c,isTextExpanded:d,onToggleExpanded:l,onToggleTextExpanded:f}){var R;const m=(s.role||"").toLowerCase(),x=m==="user"||m==="human",h=s.kind||(m==="tool"?"tool":"standard"),p=typeof s.content=="string"?s.content:(s.content||[]).map(w=>w.text||"").join(`
10
+ `);if(h==="thought"){const w=((R=s.meta)==null?void 0:R.label)||"Thought";return e.jsxs("div",{className:"self-start chat-msg-thought",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx(Ci,{size:13}),e.jsx("span",{children:w})]}),e.jsx("div",{className:"chat-msg-body",children:p})]})}if(h==="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:p.split(`
11
+ `)[0].slice(0,80)})]});if(h==="terminal"){const w=s.meta||{},N=w.isRunning?"⏳":"✅",y=w.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:N}),e.jsx("span",{children:y})]}),e.jsx("pre",{className:"chat-msg-body",children:p})]})}if(h==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:p.slice(0,100)});const j=!x&&o?Pi(p):null,u=j?j.textContent:p,b=j?Object.entries(j.toolCounts):[],g=o&&!x&&!c&&u.length>Br,v=c?p:g&&!d?u.slice(0,Br):u,S=Li(v);return e.jsxs("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${x?"self-end":"self-start"}`,children:[b.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 items-center mb-0.5",children:[b.map(([w,N])=>e.jsxs("span",{className:"chat-tool-badge",children:["⏺ ",w,N>1?` ×${N}`:""]},w)),(j==null?void 0:j.hasTools)&&e.jsx("button",{onClick:l,className:"text-[10px] text-text-muted px-1 py-px opacity-50",children:c?"Collapse":"Original"}),!u&&r!=null&&e.jsx("span",{className:"text-[10px] opacity-35 ml-0.5",children:tr(r)})]}),(u||x)&&e.jsxs("div",{className:`chat-bubble ${x?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${u?"mb-1.5":"mb-0"}`,children:[e.jsx("span",{className:"chat-sender",children:x?i||"You":s.senderName||n}),r!=null&&e.jsx("span",{className:"chat-time",children:tr(r)})]}),u&&e.jsx("div",{className:"chat-markdown",children:S?e.jsx(Sn,{remarkPlugins:[Cn,qa,Ya],children:v}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),g&&e.jsx("button",{onClick:f,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:d?"Collapse ↑":`Show more (${Math.round(u.length/100)*100} chars) ↓`})]})]})},(t,s)=>t.message===s.message&&t.receivedAt===s.receivedAt&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isExpanded===s.isExpanded&&t.isTextExpanded===s.isTextExpanded),$i=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:i,isCliMode:o=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:l={},emptyState:f,onLoadMore:m,isLoadingMore:x,hasMoreHistory:h,hiddenLiveCount:p=0,loadError:j,scrollToBottomRequestNonce:u},b){var Se;const g=a.useRef(null),v=a.useRef(null),S=a.useRef(null),R=a.useRef(0),w=a.useRef(""),N=a.useRef(!1),y=a.useRef(null),k=a.useRef(!1),E=a.useRef(null),P=a.useRef(!1),[B,L]=a.useState(new Set),[A,W]=a.useState(new Set),z=a.useRef(!1),D=()=>{const F=g.current;return F?F.scrollHeight-F.scrollTop-F.clientHeight<200:!0},U=a.useCallback((F="auto")=>{const oe=g.current;oe&&oe.scrollTo({top:oe.scrollHeight,behavior:F})},[]),T=a.useCallback(()=>{var V;const F=g.current,oe=(V=window.getSelection)==null?void 0:V.call(window);if(!F||!oe||oe.rangeCount===0||oe.isCollapsed){P.current=!1;return}const ee=oe.anchorNode,xe=oe.focusNode;P.current=!!(ee&&xe&&F.contains(ee)&&F.contains(xe))},[]),M=a.useCallback((F="auto")=>{y.current!=null&&cancelAnimationFrame(y.current),y.current=requestAnimationFrame(()=>{y.current=null,U(F)})},[U]),_=s.length>0?`${s.length}:${(((Se=s[s.length-1])==null?void 0:Se.content)||"").length}`:"0:0";a.useEffect(()=>{const F=!N.current,oe=w.current!==d;if(w.current=d,F||oe){N.current=!0,z.current=!1,k.current=!0,P.current||M("auto"),R.current=s.length;return}s.length>R.current?!z.current&&!P.current&&M("auto"):D()&&!z.current&&!P.current&&M("auto"),R.current=s.length},[_,d,c,s.length,M]),a.useEffect(()=>{u&&(z.current=!1,k.current=!0,E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{k.current=!1,E.current=null},180),P.current||M("auto"))},[M,u]),a.useEffect(()=>()=>{y.current!=null&&cancelAnimationFrame(y.current),E.current!=null&&window.clearTimeout(E.current)},[]),a.useEffect(()=>{const F=v.current;if(!F)return;const oe=()=>{E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{k.current=!1,E.current=null},180)},ee=new ResizeObserver(()=>{k.current&&(P.current||(M("auto"),oe()))});return ee.observe(F),()=>{ee.disconnect(),E.current!=null&&(window.clearTimeout(E.current),E.current=null)}},[M,d]),a.useImperativeHandle(b,()=>({scrollToBottom:(F="smooth")=>{U(F)}}),[U]),a.useEffect(()=>{const F=g.current;if(!F)return;let oe;const ee=()=>{clearTimeout(oe),oe=setTimeout(()=>{z.current=!D()},50)};return F.addEventListener("scroll",ee,{passive:!0}),()=>{F.removeEventListener("scroll",ee),clearTimeout(oe)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",T),()=>document.removeEventListener("selectionchange",T)),[T]);const H=a.useRef(0),q=a.useRef(!1);a.useEffect(()=>{const F=g.current;if(!F||!q.current||H.current===0)return;const oe=F.scrollHeight-H.current;oe>0&&(F.scrollTop=oe),H.current=0,q.current=!1},[s.length]);const ce=()=>{const F=g.current;F&&(H.current=F.scrollHeight),q.current=!0,m==null||m()},he=a.useMemo(()=>{const F=s.map((V,Y)=>({type:"message",data:V,index:Y,ts:V.receivedAt||l[$t(V,Y)]||0}));if(!r||r.length===0)return F;const oe=[...r].sort((V,Y)=>V.timestamp-Y.timestamp).map((V,Y)=>({type:"action",data:V,index:Y,ts:V.timestamp})),ee=[];let xe=0;for(const V of F){for(;xe<oe.length&&V.ts>0&&oe[xe].ts<V.ts;)ee.push(oe[xe++]);ee.push(V)}for(;xe<oe.length;)ee.push(oe[xe++]);return ee},[s,r,l]),we=p>0||!!h,se=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:j?`↻ ${j}`:"↑ Load older messages";return e.jsx("div",{ref:g,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:v,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..."}),we&&!x&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${j&&p===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:se})}),he.length===0&&!we&&(f||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),he.map(F=>{if(F.type==="action"){const ae=F.data;return e.jsx(Ri,{log:ae},`action-${F.index}`)}const oe=F.data,ee=F.index,xe=$t(oe,ee),V=oe.receivedAt||l[xe],Y=`${d}-${xe}`,re=B.has(Y),de=A.has(Y);return e.jsx(Ei,{message:oe,receivedAt:V,agentName:n,userName:i,isCliMode:o,isExpanded:re,isTextExpanded:de,onToggleExpanded:()=>L(ae=>{const Q=new Set(ae);return re?Q.delete(Y):Q.add(Y),Q}),onToggleTextExpanded:()=>W(ae=>{const Q=new Set(ae);return de?Q.delete(Y):Q.add(Y),Q})},`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:S})]})})}),Di=a.memo($i,(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);let Kr=!1;const Dn=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([]),f=a.useRef(!1),m=a.useRef(!1),x=a.useRef(!1),h=()=>{const p=o.current;if(p){f.current&&(p.clear(),f.current=!1);for(const j of l.current)p.write(j);l.current=[],m.current&&(p.fit(),m.current=!1),x.current&&(p.bumpResize(),x.current=!1)}};return a.useImperativeHandle(i,()=>({write:p=>{o.current?o.current.write(p):l.current.push(p)},clear:()=>{o.current?o.current.clear():(l.current=[],f.current=!0)},reset:()=>{o.current&&"reset"in o.current&&typeof o.current.reset=="function"?o.current.reset():(l.current=[],f.current=!0)},resize:(p,j)=>{o.current&&"resize"in o.current&&typeof o.current.resize=="function"&&o.current.resize(p,j)},fit:()=>{o.current?o.current.fit():m.current=!0},bumpResize:()=>{o.current?o.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const p=requestAnimationFrame(()=>{h()});return()=>cancelAnimationFrame(p)},[c]),a.useEffect(()=>{let p=!1;return oi(()=>import("./terminal-CKqklWLC.js").then(j=>j.i),__vite__mapDeps([0,1,2])).then(j=>{Kr||(Kr=!0,console.info("[CliTerminal] renderer module loaded: ghostty-web")),p||d(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{p=!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"}})});Dn.displayName="CliTerminal";function ps({label:t,value:s,sub:r,icon:n}){return e.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:"text-base flex items-center",children:n}),e.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:t})]}),e.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Wr({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 Bi({cursorPos:t,viewportRef:s,imgRef:r}){var v;if(!t||!r.current)return null;const n=r.current,i=n.getBoundingClientRect(),o=(v=s.current)==null?void 0:v.getBoundingClientRect();if(!o)return null;const c=n.naturalWidth||i.width,d=n.naturalHeight||i.height,l=c/d,f=i.width/i.height;let m,x,h,p;l>f?(m=i.width,x=i.width/l,h=0,p=(i.height-x)/2):(x=i.height,m=i.height*l,h=(i.width-m)/2,p=0);const j=i.left-o.left+h+m*t.nx,u=i.top-o.top+p+x*t.ny,b=Math.max(8,Math.min(o.width-8,j)),g=Math.max(8,Math.min(o.height-8,u));return e.jsxs("div",{style:{position:"absolute",left:b-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 Ki({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:i,setIsMenuOpen:o,imeText:c,setImeText:d,handleImeSubmit:l,isConnActive:f,zoom:m,isMobile:x,mobileFillZoom:h,onZoomOut:p,onZoomReset:j,onZoomIn:u,transportType:b,screenshotUsage:g,lastActionStatus:v}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:S=>S.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(S=>!S),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:S=>S.stopPropagation(),onChange:S=>d(S.target.value),onKeyDown:S=>{l(S)},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(S=>!S),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:f?"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:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),e.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),m>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),b==="relay"&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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`}),v&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:v})]})]}),i&&e.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(x?h:1)+.01?x?"FILL":"FIT":`${Math.round(m*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),p()},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:S=>{S.stopPropagation(),j()},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:S=>{S.stopPropagation(),u()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Wi({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 Oi(){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 Or(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 rs(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!Oi())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,Or(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,Or(s[c])]))}),r.current=s})}function zi({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:i,minZoom:o,zoomRef:c,panXRef:d,panYRef:l,setPanX:f,setPanY:m,setZoom:x,lastWheelTimeRef:h,onAction:p,setLastActionStatus:j,spawnRippleFromNormalized:u,clampPan:b,isMobile:g,mobileFillZoom:v}){const[S,R]=a.useState(null),w=a.useRef(null),N=a.useRef(null),y=a.useRef(null),k=a.useRef(!1),E=a.useRef(null),P=a.useRef(0),B=a.useRef(null),L=a.useRef(1),A=a.useRef({x:0,y:0}),W=a.useRef(!1),z=a.useRef(n),D=a.useRef(p),U=30,T=550,M=18,_=60,H=400,q=12,ce=()=>{if(w.current)return;const se={nx:.5,ny:.5};w.current=se,R(se)};return a.useEffect(()=>{z.current=n,n==="mouse"&&ce()},[n]),a.useEffect(()=>{D.current=p},[p]),a.useEffect(()=>{const se=t.current;if(!se)return;const Se=Y=>{if(!r.current)return null;const re=r.current.getBoundingClientRect();return!re.width||!re.height?null:{nx:Math.max(0,Math.min(1,(Y.clientX-re.left)/re.width)),ny:Math.max(0,Math.min(1,(Y.clientY-re.top)/re.height))}},F=(Y,re)=>{if(!r.current)return{dnx:0,dny:0};const de=r.current,ae=de.getBoundingClientRect(),Q=de.naturalWidth||ae.width,ue=de.naturalHeight||ae.height,C=Q/ue,ne=ae.width/ae.height;let te,$;return C>ne?(te=ae.width,$=ae.width/C):($=ae.height,te=ae.height*C),{dnx:Y/te,dny:re/$}},oe=(Y,re,de)=>{if(de<=1.05)return;const ae=-(Y-.5)*100,Q=-(re-.5)*100,ue=b(ae,Q,de);(Math.abs(ue.x-d.current)>.1||Math.abs(ue.y-l.current)>.1)&&(f(ue.x),m(ue.y),d.current=ue.x,l.current=ue.y)},ee=Y=>{const re=s.current;if(re&&Y.target instanceof Node&&re.contains(Y.target))Y.preventDefault();else return;if(Y.touches.length===1){const de=Y.touches[0];N.current={x:de.clientX,y:de.clientY,time:Date.now()},y.current={x:de.clientX,y:de.clientY},W.current||(k.current=!1),E.current=setTimeout(()=>{if(!k.current&&!W.current)if(k.current=!0,z.current==="mouse"){const ae=w.current||{nx:.5,ny:.5};j("Right Click"),u(ae.nx,ae.ny,"right"),D.current("input_click",{...ae,button:"right"}).catch(()=>{})}else{const ae=Se(de);ae&&(j("Right Click"),u(ae.nx,ae.ny,"right"),D.current("input_click",{...ae,button:"right"}).catch(()=>{}))}},500);return}if(Y.touches.length===2){E.current&&clearTimeout(E.current),k.current=!0,W.current=!0;const de=Y.touches[1].clientX-Y.touches[0].clientX,ae=Y.touches[1].clientY-Y.touches[0].clientY;B.current=Math.sqrt(de*de+ae*ae),L.current=c.current,A.current={x:(Y.touches[0].clientX+Y.touches[1].clientX)/2,y:(Y.touches[0].clientY+Y.touches[1].clientY)/2}}},xe=Y=>{const re=s.current;if(re&&Y.target instanceof Node&&re.contains(Y.target)&&Y.preventDefault(),Y.touches.length===1&&y.current){const de=Y.touches[0],ae=de.clientX-y.current.x,Q=de.clientY-y.current.y;if(!k.current&&N.current){const ue=de.clientX-N.current.x,C=de.clientY-N.current.y;Math.sqrt(ue*ue+C*C)>8&&(k.current=!0,E.current&&clearTimeout(E.current))}if(k.current)if(z.current==="mouse"){const ue=F(ae,Q),C=w.current||{nx:.5,ny:.5},ne=Math.max(0,Math.min(1,C.nx+ue.dnx)),te=Math.max(0,Math.min(1,C.ny+ue.dny));w.current={nx:ne,ny:te},R({nx:ne,ny:te}),j(`Cursor: ${Math.round(ne*100)}%, ${Math.round(te*100)}%`),oe(ne,te,c.current);const $=Date.now();$-h.current>=30&&(h.current=$,D.current("input_mouseMoved",{nx:ne,ny:te}).catch(()=>{}))}else if(c.current>1){const ue=s.current;if(ue){const C=ue.clientWidth,ne=ue.clientHeight,te=d.current+ae/C*100,$=l.current+Q/ne*100,G=b(te,$,c.current);f(G.x),m(G.y),d.current=G.x,l.current=G.y}}else{const ue=Se(de);if(ue){const C=Date.now();C-h.current>=40&&(h.current=C,j("Scroll"),D.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-ae*2.5),deltaY:Math.round(-Q*2.5)}).catch(()=>{}))}}y.current={x:de.clientX,y:de.clientY};return}if(Y.touches.length===2&&B.current!==null){const de=Y.touches[1].clientX-Y.touches[0].clientX,ae=Y.touches[1].clientY-Y.touches[0].clientY,ue=Math.sqrt(de*de+ae*ae)/B.current,C=(Y.touches[0].clientX+Y.touches[1].clientX)/2,ne=(Y.touches[0].clientY+Y.touches[1].clientY)/2,te=C-A.current.x,$=ne-A.current.y,G=Math.abs(ue-1)>.03;if(z.current==="mouse"){if(G){const Z=Math.max(o,Math.min(5,L.current*ue));x(Z),c.current=Z}else if(Math.abs(te)>2||Math.abs($)>2){const Z=w.current||{nx:.5,ny:.5},ge=Date.now();ge-h.current>=30&&(h.current=ge,j("Scroll"),D.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-te*3),deltaY:Math.round(-$*3)}).catch(()=>{}))}}else{const Z=Math.max(o,Math.min(5,L.current*ue));x(Z),c.current=Z;const ge=s.current;if(ge&&Z>1){const ye=ge.clientWidth,Ee=ge.clientHeight,$e=d.current+te/ye*100,Re=l.current+$/Ee*100,De=b($e,Re,Z);f(De.x),m(De.y),d.current=De.x,l.current=De.y}}A.current={x:C,y:ne}}},V=Y=>{var re;if(E.current&&clearTimeout(E.current),B.current=null,Y.touches.length===1&&W.current){const de=Y.touches[0];N.current={x:de.clientX,y:de.clientY,time:Date.now()},y.current={x:de.clientX,y:de.clientY},k.current=!0;return}if(Y.touches.length===0){if(W.current){W.current=!1,k.current=!1;return}if(Y.changedTouches.length===1){const de=Y.changedTouches[0],ae=Date.now(),Q=ae-(((re=N.current)==null?void 0:re.time)||0),ue=N.current?de.clientX-N.current.x:0,C=N.current?de.clientY-N.current.y:0,ne=Math.sqrt(ue*ue+C*C);if(z.current==="mouse"){if(Q<U||Q>T||ne>M){k.current=!1;return}const te=w.current||Se(de);te&&(j(`Click: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),u(te.nx,te.ny,"left"),D.current("input_click",{...te}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(Q<_||Q>H||ne>q){k.current=!1;return}const te=Se(de);if(!te)return;ae-P.current<300?(j("Double tap"),u(te.nx,te.ny,"double"),D.current("input_click",{...te,clickCount:2}).catch(()=>{}),P.current=0):(j(`Tap: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),u(te.nx,te.ny,"left"),D.current("input_click",{...te}).catch(()=>{}),P.current=ae)}}k.current=!1}};return se.addEventListener("touchstart",ee,{passive:!1}),se.addEventListener("touchmove",xe,{passive:!1}),se.addEventListener("touchend",V,{passive:!1}),()=>{se.removeEventListener("touchstart",ee),se.removeEventListener("touchmove",xe),se.removeEventListener("touchend",V),E.current&&clearTimeout(E.current)}},[t,s,r,o,c,d,l,f,m,x,h,j,u,b]),{cursorPos:S,cursorPosRef:w,handleToggleInputMode:()=>{i(se=>{const Se=se==="touch"?"mouse":"touch";return Se==="mouse"&&ce(),Se})},handleZoomReset:()=>{const se=g?v:1;x(se),c.current=se,f(0),m(0),d.current=0,l.current=0}}}function Bn({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),[f,m]=a.useState(null),[x,h]=a.useState(""),[,p]=a.useState(!1),[j,u]=a.useState([]),b=a.useRef(0),[g,v]=a.useState(!1),[S,R]=a.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[N,y]=a.useState(w?"mouse":"touch"),[k,E]=a.useState(1),P=a.useRef(!1),[B,L]=a.useState(1),[A,W]=a.useState(0),[z,D]=a.useState(0);rs("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:N,zoom:B,panX:A,panY:z,isMenuOpen:g,isImeOpen:S});const U=a.useRef(0),T=a.useRef(B),M=a.useRef(A),_=a.useRef(z);a.useEffect(()=>{T.current=B},[B]),a.useEffect(()=>{M.current=A},[A]),a.useEffect(()=>{_.current=z},[z]),a.useEffect(()=>{var Q;(Q=c.current)==null||Q.focus()},[]);const H=r==="connected",q=n,ce=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!w||P.current||!q)return;const Q=l.current,ue=d.current;if(!Q||!ue)return;const C=()=>{const ne=ue.clientWidth,te=ue.clientHeight,$=Q.naturalWidth,G=Q.naturalHeight;if(!$||!G||!ne||!te)return;const Z=Math.min(ne/$,te/G),ye=Math.max(ne/$,te/G)/Z;ye>1.01&&(E(ye),L(ye),T.current=ye),P.current=!0};Q.complete&&Q.naturalWidth?C():Q.addEventListener("load",C,{once:!0})},[q,w]);const we=.5;a.useEffect(()=>{B<=we&&(W(0),D(0))},[B,we]);const se=(Q,ue,C)=>{if(C<=we)return{x:0,y:0};const ne=(C-1)/(2*C)*100,te=(C-1)/(2*C)*100;return{x:Math.max(-ne,Math.min(ne,Q)),y:Math.max(-te,Math.min(te,ue))}},Se=(Q,ue)=>{if(!l.current)return null;const C=l.current.getBoundingClientRect();return!C.width||!C.height?null:{nx:Math.max(0,Math.min(1,(Q-C.left)/C.width)),ny:Math.max(0,Math.min(1,(ue-C.top)/C.height))}},F=(Q,ue,C)=>{const ne=d.current;if(!ne)return;const te=ne.getBoundingClientRect(),$=++b.current;u(G=>[...G,{id:$,x:Q-te.left,y:ue-te.top,type:C}]),setTimeout(()=>u(G=>G.filter(Z=>Z.id!==$)),600)},oe=(Q,ue,C)=>{const ne=l.current,te=d.current;if(!ne||!te)return;const $=ne.getBoundingClientRect(),G=te.getBoundingClientRect(),Z=ne.naturalWidth||$.width,ge=ne.naturalHeight||$.height,ye=Z/ge,Ee=$.width/$.height;let $e,Re,De,Ye;ye>Ee?($e=$.width,Re=$.width/ye,De=0,Ye=($.height-Re)/2):(Re=$.height,$e=$.height*ye,De=($.width-$e)/2,Ye=0);const nt=$.left-G.left+De+$e*Q,Qe=$.top-G.top+Ye+Re*ue,pe=++b.current;u(_e=>[..._e,{id:pe,x:nt,y:Qe,type:C}]),setTimeout(()=>u(_e=>_e.filter(Ce=>Ce.id!==pe)),600)},ee=async Q=>{var C;const ue=Se(Q.clientX,Q.clientY);if(ue){m(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),F(Q.clientX,Q.clientY,"left"),(C=c.current)==null||C.focus();try{const ne=await t("input_click",{nx:ue.nx,ny:ue.ny});ne!=null&&ne.success||s(`❌ Click failed: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ Click error: ${ne.message||ne}`)}}},xe=async(Q,ue,C,ne=0)=>{try{await t("input_key",{type:C?"char":"keyDown",key:Q,code:ue,text:C?Q:void 0,unmodifiedText:C?Q:void 0,modifiers:ne})}catch(te){s(`❌ Key error: ${te.message||te}`)}},V=async Q=>{if(Q.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Q.key)&&Q.preventDefault();let C=0;Q.altKey&&(C|=1),Q.ctrlKey&&(C|=2),Q.metaKey&&(C|=4),Q.shiftKey&&(C|=8),m(`Key: ${Q.key}`),await xe(Q.key,Q.code,Q.key.length===1,C)},Y=async Q=>{if(Q.key==="Enter"){if(Q.nativeEvent.isComposing)return;if(x){const ue=x;h(""),m(`IME Sent: ${ue}`);try{const C=await t("input_type",{text:ue});C!=null&&C.success||s(`❌ IME error: ${C==null?void 0:C.error}`)}catch(C){s(`❌ IME error: ${C.message}`)}}else m("Key: Enter"),await xe("Enter","Enter",!1)}};a.useEffect(()=>{const Q=c.current;if(!Q)return;const ue=C=>{var ne;if((ne=l.current)!=null&&ne.contains(C.target)){C.preventDefault();const te=Date.now();if(te-U.current<40)return;U.current=te;const $=Se(C.clientX,C.clientY);if(!$)return;m(`Scroll: ${Math.round(C.deltaY)}`),t("input_wheel",{nx:$.nx,ny:$.ny,deltaX:Math.round(C.deltaX),deltaY:Math.round(C.deltaY)}).catch(()=>{})}};return Q.addEventListener("wheel",ue,{passive:!1}),()=>Q.removeEventListener("wheel",ue)},[t]);const{cursorPos:re,handleToggleInputMode:de,handleZoomReset:ae}=zi({containerRef:c,viewportRef:d,imgRef:l,inputMode:N,setInputMode:y,minZoom:we,zoomRef:T,panXRef:M,panYRef:_,setPanX:W,setPanY:D,setZoom:L,lastWheelTimeRef:U,onAction:t,setLastActionStatus:m,spawnRippleFromNormalized:oe,clampPan:se,isMobile:w,mobileFillZoom:k});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:V,onContextMenu:Q=>Q.preventDefault(),onFocus:()=>p(!0),onBlur:()=>p(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[q?e.jsx("img",{ref:l,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${B}) translate(${A}%, ${z}%)`,transformOrigin:"center center",cursor:N==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ee,onContextMenu:Q=>Q.preventDefault(),onDragStart:Q=>Q.preventDefault()}):e.jsx(Wi,{waitingLabel:ce,waitingHint:he,transportType:o}),N==="mouse"&&q&&e.jsx(Bi,{cursorPos:re,viewportRef:d,imgRef:l}),j.map(Q=>{const C={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Q.type];return e.jsxs("div",{style:{position:"absolute",left:Q.x,top:Q.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${C}, 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(${C}, 0.9)`,boxShadow:`0 0 12px rgba(${C}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Q.id)})]}),e.jsx(Ki,{inputMode:N,onToggleInputMode:de,isImeOpen:S,setIsImeOpen:R,isMenuOpen:g,setIsMenuOpen:v,imeText:x,setImeText:h,handleImeSubmit:Y,isConnActive:H,zoom:B,isMobile:w,mobileFillZoom:k,onZoomOut:()=>L(Q=>Math.max(.5,Q-.25)),onZoomReset:ae,onZoomIn:()=>L(Q=>Math.min(5,Q+.25)),transportType:o,screenshotUsage:i,lastActionStatus:f}),e.jsx("style",{children:`
12
+ @keyframes slideUp {
13
+ from { opacity: 0; transform: translateY(6px); }
14
+ to { opacity: 1; transform: translateY(0); }
15
+ }
16
+ @keyframes slideUpSidebar {
17
+ from { opacity: 0; transform: translateY(6px); }
18
+ to { opacity: 1; transform: translateY(0); }
19
+ }
20
+ @keyframes click-ripple-ring {
21
+ 0% { transform: scale(0.3); opacity: 1; }
22
+ 100% { transform: scale(2.2); opacity: 0; }
23
+ }
24
+ @keyframes click-ripple-dot {
25
+ 0% { transform: scale(1); opacity: 0.9; }
26
+ 50% { transform: scale(1.8); opacity: 0.6; }
27
+ 100% { transform: scale(0.5); opacity: 0; }
28
+ }
29
+ @keyframes remote-float {
30
+ 0% { transform: translateY(0px); }
31
+ 50% { transform: translateY(-7px); }
32
+ 100% { transform: translateY(0px); }
33
+ }
34
+ `})]})}function Ui(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 f=Math.floor(l/24);return f<7?`${f}d${r}`:new Date(t).toLocaleDateString()}const Kn=t=>Ui(t);function Hi(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function Rs(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 ns(t){const s=new Map,r=(n,i)=>{n&&s.set(n,{sessionId:n,...Hi(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 Jt(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 Zt(t,s,r){const n=Jt(t,s),i=Rs(t),o=i.isReconnecting,c=i.isConnecting,d=i.isGenerating,l=i.isWaiting,f=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||l,m=n.inboxBucket==="working"||d,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:f,isWorking:m,isReconnecting:o,isConnecting:c,isGenerating:d,isWaiting:l,inboxBucket:f?"needs_attention":m?"working":x?"task_complete":"idle"}}function Fi(t,s,r){return Zt(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Vi(t,s,r){return Jt(t,r||new Map).surfaceHidden}function Wn({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!Rs(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(fr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((d,l)=>{const f=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),h=r===d,p=r!==null;return e.jsx("button",{onClick:()=>o(d),disabled:p,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"bg-white font-extrabold":x?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${p&&!h?"opacity-40":"opacity-100"} ${p?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)"}:void 0,children:h?"⏳ ...":c(d)},l)})})]})]})}const zr=new Map,Gi={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",antigravity:"#f97316",windsurf:"#34d399"};function qi({ideId:t,sessionId:s,ideType:r,providerType:n,displayLabel:i,controls:o,controlValues:c,serverModel:d,serverMode:l}){const{sendCommand:f}=jt(),m=`${t}:${s||n}`,x=Gi[n]||"#94a3b8",[h,p]=a.useState({}),j=a.useRef(0),u={...d?{model:d}:{},...l?{mode:l}:{},...c||{},...Date.now()<j.current?h:{}};a.useEffect(()=>{c&&Date.now()>j.current&&p({})},[c]);const[b,g]=a.useState(zr.get(m)||{}),[v,S]=a.useState(null),[R,w]=a.useState(null),N=a.useCallback(async(A,W={})=>{const z={...W,...s&&{targetSessionId:s}};return await f(t,A,z)},[t,s,f]);if(!o||o.length===0)return null;const y=o.filter(A=>A.placement==="bar").sort((A,W)=>(A.order??50)-(W.order??50));if(y.length===0)return null;const k=async A=>{var z,D,U;if(v===A.id){S(null);return}if((((z=A.options)==null?void 0:z.map(T=>T.value))||b[A.id]||[]).length>0){S(A.id);return}if(A.dynamic&&A.listScript){w(A.id);try{const T=await N(A.listScript==="listModels"?"list_extension_models":A.listScript==="listModes"?"list_extension_modes":A.listScript,{agentType:n,ideType:r}),_=((T==null?void 0:T.models)||(T==null?void 0:T.modes)||((D=T==null?void 0:T.result)==null?void 0:D.models)||((U=T==null?void 0:T.result)==null?void 0:U.modes)||(T==null?void 0:T.options)||[]).map(H=>typeof H=="string"?H:(H==null?void 0:H.name)||(H==null?void 0:H.id)||(H==null?void 0:H.value)||String(H));g(H=>{const q={...H,[A.id]:_};return zr.set(m,q),q}),S(A.id)}catch{}finally{w(null)}}},E=async(A,W)=>{S(null),p(z=>({...z,[A.id]:W})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const z=Us(A.setScript,n);await N(z,{agentType:n,ideType:r,model:A.id==="model"?W:void 0,mode:A.id==="mode"?W:void 0,value:W})}catch{}},P=async A=>{var M;const W=((M=A.options)==null?void 0:M.map(_=>_.value))||b[A.id]||[];if(W.length===0)return;const z=String(u[A.id]||""),U=(W.indexOf(z)+1)%W.length,T=W[U];if(typeof T=="string"){p(_=>({..._,[A.id]:T})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const _=Us(A.setScript,n);await N(_,{agentType:n,ideType:r,value:T})}catch{}}},B=async A=>{const z=!u[A.id];p(D=>({...D,[A.id]:z})),j.current=Date.now()+5e3;try{if(!A.setScript)return;const D=Us(A.setScript,n);await N(D,{agentType:n,ideType:r,value:z})}catch{}},L=async A=>{if(A.invokeScript)try{await N("invoke_extension_script",{agentType:n,ideType:r,scriptName:A.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:"│"}),y.map(A=>{var T;const W=String(u[A.id]||""),z=v===A.id,D=R===A.id,U=((T=A.options)==null?void 0:T.map(M=>M.value))||b[A.id]||[];switch(A.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:z?`${x}55`:"transparent",border:"1px solid",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>k(A),children:[A.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:A.icon}),D?"...":W||A.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),z&&U.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(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:A.label.toUpperCase()}),U.map(M=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:M===W?`${x}18`:"transparent",color:M===W?x:"var(--text-secondary)",fontWeight:M===W?600:400,borderLeft:M===W?`2px solid ${x}`:"2px solid transparent"},onMouseEnter:_=>{_.currentTarget.style.background=`${x}12`},onMouseLeave:_=>{_.currentTarget.style.background=M===W?`${x}18`:"transparent"},onClick:()=>E(A,M),children:M},M))]})]})]},A.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:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>P(A),title:`Click to cycle: ${U.join(" → ")}`,children:[A.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:A.icon}),W||A.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},A.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:W?`${x}44`:"transparent",background:W?`${x}14`:"var(--surface-tertiary)",color:W?x:"var(--text-muted)"},onClick:()=>B(A),children:[A.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:A.icon}),A.label]},A.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:()=>L(A),children:[A.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:A.icon}),A.label]},A.id);default:return null}})]})}function Us(t,s){return{setModel:"set_extension_model",setMode:"set_extension_mode",setThinkingLevel:"set_thought_level"}[t]||t}const Yi=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:i,isActive:o=!0}){const c=a.useRef(null),[d,l]=a.useState("");a.useEffect(()=>{l("")},[s]),a.useEffect(()=>{var m;o&&((m=c.current)==null||m.focus())},[s,o]);const f=()=>{const m=d.trim();!m||n||(l(""),i(m))};return e.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:o?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:o?72:0,opacity:o?1:0,transform:o?"translateY(0)":"translateY(10px)",padding:o?"10px 12px":"0 12px",pointerEvents:o?"auto":"none"},"aria-hidden":!o,children:e.jsxs("div",{className:"flex gap-2.5 items-center",title:o?`Send message to ${r}`:void 0,children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:m=>l(m.target.value),onPaste:m=>{const x=m.clipboardData.getData("text");x&&l(h=>h+x),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),f()}},onBlur:m=>{if(window.innerWidth<768){const x=m.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:f,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 Xi=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Ji(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function rt(t,s){if(Ji(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Xi.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 On(t){return rt(t)==="generating"}function ze(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Zi(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 Ur(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function Es(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 Qi(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 eo(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function to(t){return Qi(t.trim().replace(/\.local$/i,""))}function so(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function zn(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&&!eo(c));if(r&&r!=="Unknown")return to(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function ct(t,s={}){return so(t)||zn(t,s)}function Qt(t){return t.transport==="pty"}function Bt(t){return t.transport==="acp"}function Hr(t,s){return ze(t)}function Fr(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const i=(s||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),c=ze(r||"").trim().toLowerCase();return n===i||n===o||n===c}function ro(t){return rt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function no(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 Hs(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 ao(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&&(Hs(s.timestamp)||Hs(s.receivedAt)||Hs(s.createdAt))||0}function io(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function sr(t){return Math.max(io(t),ao(t.activeChat))}function oo(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 br(t,s){return oo(sr(t),sr(s),ct(t,{fallbackId:t.id}),ct(s,{fallbackId:s.id}),t.id,s.id)}function Un({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:i=!0}){var j;const o=zt(),c=t.daemonId||((j=t.ideId)==null?void 0:j.split(":")[0])||t.ideId,d=t.transport==="cdp-page"||t.transport==="cdp-webview",l=t.streamSource==="agent-stream"&&!!t.agentName,f=!l&&(t.transport==="pty"||t.transport==="acp"),m=t.agentName||ze(t.agentType||t.ideType||""),x=(()=>{var u,b;if(t.streamSource==="agent-stream"){const g=(b=(u=t.displaySecondary)==null?void 0:u.split("·")[0])==null?void 0:b.trim();if(g)return g}return ze(t.ideType||"")})(),h=a.useCallback(()=>{if(n){n();return}c&&o("/dashboard",{state:{openMachineId:c}})},[c,o,n]),p=a.useCallback(()=>{if(r){r();return}const u=t.streamSource==="agent-stream"?t.nativeSessionId:t.sessionId;u&&o(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[t.nativeSessionId,t.sessionId,t.streamSource,o,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[d&&(i?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:x,children:[e.jsx(st,{size:12}),e.jsx("span",{children:x})]}):e.jsxs("span",{className:"conversation-meta-chip",title:x,children:[e.jsx(st,{size:12}),e.jsx("span",{children:x})]})),l&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:t.agentName,children:[e.jsx(_t,{size:12}),e.jsx("span",{children:t.agentName})]}),f&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:m,children:[e.jsx(_t,{size:12}),e.jsx("span",{children:m})]}),t.machineName&&(i?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:h,title:t.machineName,children:[e.jsx(Cs,{size:12}),e.jsx("span",{children:t.machineName})]}):e.jsxs("span",{className:"conversation-meta-chip",title:t.machineName,children:[e.jsx(Cs,{size:12}),e.jsx("span",{children:t.machineName})]}))]})}const Ue=t=>t.transport==="pty",Ot=(t,s)=>Ue(t)?s||t.mode||"terminal":"chat",Hn=(t,s)=>Ue(t)&&Ot(t,s)==="terminal",Ke=t=>t.transport==="acp";function Ts(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():Array.isArray(t)?t.map(s=>typeof s=="string"?s:s&&typeof s=="object"&&"text"in s?String(s.text||""):"").join(`
35
+ `).replace(/\s+/g," ").trim():t&&typeof t=="object"&&"text"in t?String(t.text||"").replace(/\s+/g," ").trim():String(t||"").replace(/\s+/g," ").trim()}function rr(t){const s=Number((t==null?void 0:t.timestamp)||(t==null?void 0:t.receivedAt)||(t==null?void 0:t.createdAt)||0);return Number.isFinite(s)?s:0}function co(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==null?void 0:t.role)||"").toLowerCase(),n=String((s==null?void 0:s.role)||"").toLowerCase();if(r!==n)return!1;const i=Ts(t==null?void 0:t.content),o=Ts(s==null?void 0:s.content);if(!i||i!==o)return!1;const c=rr(t),d=rr(s);return c&&d?Math.abs(c-d)<=15e3:!!(t!=null&&t._localId)!=!!(s!=null&&s._localId)}function Vr(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),rr(t)&&(s+=1),s}function lo(t,s){const r=Vr(t),n=Vr(s);return n!==r?n>r?s:t:Ts(s==null?void 0:s.content).length>=Ts(t==null?void 0:t.content).length?s:t}function Gr(t){const s=[];for(const r of t){const n=s.findIndex(i=>co(i,r));if(n>=0){s.splice(n,1,lo(s[n],r));continue}s.push(r)}return s}const uo=60,po=60;function nr({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:i,isFocusingAgent:o,actionLogs:c,userName:d,showMetaChips:l=!1,scrollToBottomRequestNonce:f,isInputActive:m=!0}){const x=a.useRef(new Map),{sendCommand:h}=jt();rs("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const p=Ve.useMemo(()=>Rs(t),[t.status,t.connectionState]),j=a.useRef(new Map),u=a.useCallback(D=>(j.current.has(D)||j.current.set(D,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:uo}),j.current.get(D)),[]),b=a.useCallback((D,U)=>{const T=u(D);j.current.set(D,{...T,...U}),g(M=>M+1)},[u]),[,g]=a.useState(0),v=t.tabKey,S=u(v),R=S.messages,w=S.hasMore,N=S.error,y=Math.max(0,t.messages.length-S.visibleLiveCount),[k,E]=a.useState(!1),P=a.useCallback(async()=>{var T,M;if(k)return;const D=t.tabKey,U=u(D);if(t.messages.length>U.visibleLiveCount){b(D,{visibleLiveCount:Math.min(t.messages.length,U.visibleLiveCount+po),error:null});return}E(!0),b(D,{error:null});try{const _=(s==null?void 0:s.daemonId)||((T=t.ideId)==null?void 0:T.split(":")[0])||"";if(!_){b(D,{hasMore:!1});return}const H=t.ideType||t.agentType||"",q=await h(_,"chat_history",{agentType:H,offset:U.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),ce=(q==null?void 0:q.result)??q;if(((M=ce.messages)==null?void 0:M.length)>0){const he=u(D);b(D,{messages:[...ce.messages,...he.messages],offset:he.offset+ce.messages.length,hasMore:!!ce.hasMore})}else b(D,{hasMore:!!ce.hasMore})}catch(_){const H=(_==null?void 0:_.message)||"";H.includes("P2P not available")||H.includes("channel not open")||H.includes("P2P not connected")||H.includes("timeout")?b(D,{error:"Connection not ready — tap to retry"}):b(D,{hasMore:!1,error:"Failed to load history"})}finally{E(!1)}},[k,s,t,h,u,b]),{allMessages:B,receivedAtMap:L}=a.useMemo(()=>{const D=y>0?t.messages.slice(-S.visibleLiveCount):t.messages;if(R.length===0){const H=Gr(D),q={};return H.forEach((ce,he)=>{const we=`${t.tabKey}:${$t(ce,he)}`;let se=ce.receivedAt||x.current.get(we)||0;se||(se=Date.now(),x.current.set(we,se)),q[$t(ce,he)]=se}),{allMessages:H,receivedAtMap:q}}const U=new Set(D.map(H=>`${H.role}:${(H.content||"").slice(0,100)}`)),T=R.filter(H=>!U.has(`${H.role}:${(H.content||"").slice(0,100)}`)),M=Gr([...T,...D]),_={};return M.forEach((H,q)=>{const ce=`${t.tabKey}:${$t(H,q)}`;let he=H.receivedAt||x.current.get(ce)||0;he||(he=Date.now(),x.current.set(ce,he)),_[$t(H,q)]=he}),{allMessages:M,receivedAtMap:_}},[t.messages,t.tabKey,y,R,S.visibleLiveCount]),A=a.useMemo(()=>c.filter(D=>D.ideId===t.tabKey).sort((D,U)=>D.timestamp-U.timestamp),[c,t.tabKey]),W=t.displayPrimary||t.agentName||"Agent",z=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((p.isGenerating||t.status==="streaming")&&E(!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(_t,{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(Wt,{size:14})," Open ",W," 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(Rn,{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(Wt,{size:14})," Open ",W," 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"&&!k)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,k,W,p.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[l&&e.jsx(Un,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(Di,{messages:B,actionLogs:A,agentName:t.agentName||t.displayPrimary||"Agent",userName:d,isCliMode:Ue(t)||Ke(t),isWorking:p.isGenerating,contextKey:t.tabKey,receivedAtMap:L,onLoadMore:P,isLoadingMore:k,hasMoreHistory:w,hiddenLiveCount:y,loadError:N??void 0,emptyState:z,scrollToBottomRequestNonce:f}),m&&!Hn(t)&&(()=>{const D=t.streamSource!=="agent-stream",U=D?t.ideType:t.agentType,T=D?s!=null&&s.type?ze(s.type):ze(t.ideType||""):t.agentName||ze(t.agentType||""),M=!D&&(s!=null&&s.childSessions)&&s.childSessions.find(q=>q.id===t.sessionId||q.providerType===t.agentType)||s,_=M==null?void 0:M.providerControls,H=M==null?void 0:M.controlValues;return e.jsx(qi,{ideId:t.ideId,sessionId:t.sessionId,ideType:t.ideType,providerType:U,displayLabel:T,controls:_,controlValues:H,serverModel:(M==null?void 0:M.currentModel)||void 0,serverMode:(M==null?void 0:M.currentPlan)||void 0,acpConfigOptions:Ke(t)?M==null?void 0:M.acpConfigOptions:void 0,acpModes:Ke(t)?M==null?void 0:M.acpModes:void 0})})(),e.jsx(Yi,{contextKey:t.tabKey,panelLabel:W,isSending:n,onSend:r,isActive:m})]})}let Fn=Xt;function gr(){return Fn()}class mo{constructor(){qe(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 Vn=new mo;class fo{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 fo;function xo(t){t.dashboardWS&&(Vn=t.dashboardWS),t.connectionManager&&(He=t.connectionManager),t.useDaemonsHook&&(Fn=t.useDaemonsHook)}function ho({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:i=!1,isVisible:o=!0}){var U;const c=a.useRef(null),{sendCommand:d,sendData:l}=jt(),[f,m]=a.useState(""),[x,h]=a.useState(!1),[p,j]=a.useState(1),u=a.useRef(!1),b=a.useRef(0),g=a.useRef(!1),v=a.useRef(""),S=a.useRef(null),R=a.useRef(!1),w=a.useRef(null),N=t.tabKey,y=t.sessionId||"",k=t.daemonId||((U=t.ideId)==null?void 0:U.split(":")[0])||t.ideId||"",E=.6,P=1.15,B=()=>{if(typeof window>"u")return 1;const T=window.innerWidth||0;return T<=360?.68:T<=390?.74:T<=430?.82:T<=480?.9:1},L=()=>{var T,M;b.current=0,g.current=!1,v.current="",S.current=null,R.current=!1,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),h(!1),(M=(T=r.current)==null?void 0:T.reset)==null||M.call(T)},A=()=>{var T,M;b.current=0,g.current=!1,v.current="",S.current=null,R.current=!1,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),h(!0),(M=(T=r.current)==null?void 0:T.reset)==null||M.call(T)},W=()=>{var M;if(w.current=null,!o)return;const T=v.current;T&&(v.current="",(M=r.current)==null||M.write(T))},z=T=>{T&&(v.current+=T,o&&w.current===null&&(w.current=requestAnimationFrame(W)))},D=(T,M=0,_,H)=>{var q,ce,he,we,se;M>0&&b.current>=M||M===0&&g.current||(b.current=M,h(!0),typeof _=="number"&&typeof H=="number"&&_>0&&H>0&&((ce=(q=r.current)==null?void 0:q.resize)==null||ce.call(q,_,H)),(we=(he=r.current)==null?void 0:he.reset)==null||we.call(he),T&&((se=r.current)==null||se.write(T)))};return a.useEffect(()=>{L()},[y]),a.useEffect(()=>{var M;if(!y)return;const T=((M=He.onRuntimeEvent)==null?void 0:M.call(He,y,_=>{if(!(!_||_.sessionId!==y)){if(_.type==="runtime_snapshot"){if(!o){S.current={text:_.text||"",seq:_.seq||0,cols:_.cols,rows:_.rows};return}D(_.text||"",_.seq||0,_.cols,_.rows);return}if(_.type==="session_output"){g.current=!0,typeof _.seq=="number"&&(b.current=Math.max(b.current,_.seq)),x||h(!0),typeof _.data=="string"&&z(_.data);return}if(_.type==="session_cleared"){if(!o){R.current=!0,v.current="",S.current=null;return}A()}}}))||(()=>{});return()=>{T()}},[k,y,r,o,x]),a.useEffect(()=>{var M,_,H;if(!y)return;k&&((M=He.getState)==null?void 0:M.call(He,k))==="connected"&&(h(!0),(_=He.requestRuntimeSnapshot)==null||_.call(He,k,y).catch(()=>{}));const T=(H=He.onStateChange)==null?void 0:H.call(He,(q,ce)=>{var he;q!==k||ce!=="connected"||(h(!0),(he=He.requestRuntimeSnapshot)==null||he.call(He,k,y).catch(()=>{}))});return()=>{T==null||T()}},[k,y,r]),a.useEffect(()=>{s&&L()},[s,N,r]),a.useEffect(()=>{m("")},[t.tabKey]),a.useEffect(()=>{const T=()=>{u.current||j(B())};return T(),window.addEventListener("resize",T),()=>window.removeEventListener("resize",T)},[]),a.useEffect(()=>{var M;if(!o){(M=c.current)==null||M.blur();return}R.current&&(R.current=!1,A());const T=S.current;T&&(S.current=null,D(T.text,T.seq,T.cols,T.rows)),v.current&&w.current===null&&(w.current=requestAnimationFrame(W))},[o]),a.useEffect(()=>()=>{w.current!==null&&(cancelAnimationFrame(w.current),w.current=null)},[]),a.useEffect(()=>{const T=M=>{var H;const _=M.detail;_!=null&&_.sessionId&&_.sessionId!==y||x&&((H=r.current)==null||H.fit())};return window.addEventListener("adhdev:fit-cli-terminal",T),()=>{window.removeEventListener("adhdev:fit-cli-terminal",T)}},[x,y,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:()=>{u.current=!0,j(T=>Math.max(E,Number((T-.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:()=>{u.current=!0,j(T=>Math.min(P,Number((T+.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/p}%`,height:`${100/p}%`,transform:`scale(${p})`,transformOrigin:"top left"},children:e.jsx(Dn,{ref:r,readOnly:!x||!o,onInput:T=>{x&&(l!=null&&l(k,{type:"pty_input",targetSessionId:y,data:T})||d(k,"pty_input",{targetSessionId:y,data:T}).catch(console.error))},onResize:(T,M)=>{x&&(l!=null&&l(k,{type:"pty_resize",targetSessionId:y,cols:T,rows:M})||d(k,"pty_resize",{targetSessionId:y,cols:T,rows:M,force:!0}).catch(()=>{}))}})})}),!x&&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:c,type:"text",placeholder:`Send message to ${t.displayPrimary}...`,value:f,disabled:!x||!o||i,onChange:T=>m(T.target.value),onPaste:T=>{const M=T.clipboardData.getData("text");M&&m(_=>_+M),T.preventDefault()},onKeyDown:T=>{if(T.key!=="Enter")return;if(T.nativeEvent.isComposing){T.preventDefault();return}T.preventDefault();const M=f.trim();!x||!M||i||(m(""),n(M))},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 T=f.trim();!x||!T||i||(m(""),n(T))},disabled:!x||!o||!f.trim()||i,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!i?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.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:f.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function bo({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 go({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 yr({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(xr,{size:n}):e.jsx(gt,{size:n})})}function qr({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const i=[t.displaySecondary,t.machineName].filter(Boolean);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:t.displayPrimary}),(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 yo({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:i,onOpenHistory:o,onOpenRemote:c,onStopCli:d,activeCliViewMode:l,onSetCliViewMode:f,onOpenConversation:m,onHideConversation:x,hiddenConversations:h=[],onShowConversation:p,onShowAllHidden:j,inboxOpen:u,onInboxOpenChange:b,hiddenOpen:g,onHiddenOpenChange:v,onOpenNewSession:S}){const R=gr(),w=R.p2pStates||{},N=R.ides||[],y=!!t&&Ue(t)&&!Ke(t),k=l||(t?Hn(t)?"terminal":"chat":null),[E,P]=a.useState(!1),B=a.useRef(null),L=a.useRef(null),A=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",W=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",z=N.filter(F=>F.type==="adhdev-daemon"),D=a.useMemo(()=>ns(N),[N]),U=Object.values(w),T=U.filter(F=>F==="connected").length,M=U.filter(F=>F==="connecting"||F==="new"||F==="checking").length,H=r!=="connected"||z.length===0?null:M>0&&T===0?"P2P connecting...":T>0&&s===0?"Waiting for IDE...":null,q=a.useMemo(()=>i.filter(F=>!Vi(F,i,D)),[i,D]),ce=a.useMemo(()=>q.filter(F=>Zt(F,D).requiresAction),[q,D]),he=a.useMemo(()=>q.filter(F=>{const oe=(t==null?void 0:t.tabKey)===F.tabKey;return Zt(F,D,{hideOpenTaskCompleteUnread:!0,isOpenConversation:oe}).unread}),[t,q,D]),we=a.useMemo(()=>[...ce,...he].slice(0,9),[ce,he]),se=ce.length+he.length;a.useEffect(()=>{if(!u)return;const F=oe=>{var ee;(ee=B.current)!=null&&ee.contains(oe.target)||b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[u,b]),a.useEffect(()=>{if(!g)return;const F=oe=>{var ee;(ee=L.current)!=null&&ee.contains(oe.target)||v(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[g,v]),a.useEffect(()=>{if(!g&&!u)return;const F=oe=>{if(!oe.altKey)return;const ee=oe.code.match(/^Digit([1-9])$/);if(!ee)return;const xe=Number(ee[1])-1,V=g?h[xe]:void 0,Y=u?we[xe]:void 0,re=V||Y;if(re){if(oe.preventDefault(),oe.stopPropagation(),V){p==null||p(V),v(!1);return}m==null||m(re),b(!1)}};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[h,g,u,we,v,b,m,p]);const Se=F=>{if(!F)return;const oe=i.find(ee=>ee.tabKey===F);oe&&(x==null||x(oe))};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(gt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:(t==null?void 0:t.displayPrimary)||"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:A,boxShadow:W}})})]}),e.jsxs("div",{className:"header-subtitle",children:[e.jsxs("span",{className:"header-subtitle-copy",children:[s," agent",s!==1?"s":""," active"]}),e.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:A,boxShadow:W}}),H&&e.jsxs("span",{className:"header-subtitle-status",children:["· ",H]})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[S&&e.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(Ni,{size:14})}),t&&(y||!Ke(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:t.displaySecondary||t.displayPrimary,children:t.displayPrimary}),y&&d&&e.jsxs(e.Fragment,{children:[f&&k&&e.jsx(yr,{mode:k,onChange:f,compact:!0}),e.jsx("button",{onClick:()=>d(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(At,{size:14})})]}),!Ke(t)&&e.jsx("button",{onClick:()=>o(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(pr,{size:14})}),!y&&!Ke(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(st,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:B,children:[e.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:L,onDragEnter:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),P(!0))},onDragOver:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),F.dataTransfer.dropEffect="move",P(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||P(!1)},onDrop:F=>{const oe=F.dataTransfer.getData("text/tab-key");F.preventDefault(),P(!1),Se(oe)},children:[e.jsxs("button",{type:"button",onClick:()=>v(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx(ji,{size:16}),h.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:h.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"}),h.length>0&&j&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{j(),v(!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:t.displayPrimary})]}),h.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:h.map(F=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(F),v(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:F.displayPrimary}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[h.indexOf(F)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",h.indexOf(F)+1]}):null,[F.displaySecondary,F.machineName].filter(Boolean).join(" · ")]})]},F.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>b(!u),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(Ls,{size:16}),se>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:se})]}),u&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ce.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),ce.map(F=>e.jsx(qr,{conversation:F,isAttention:!0,shortcutIndex:we.indexOf(F)>=0?we.indexOf(F)+1:void 0,onClick:()=>{m==null||m(F),b(!1)}},F.tabKey))]}),he.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),he.map(F=>e.jsx(qr,{conversation:F,shortcutIndex:we.indexOf(F)>=0?we.indexOf(F)+1:void 0,onClick:()=>{m==null||m(F),b(!1)}},F.tabKey))]}),se===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function vo(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 wo({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:i=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:l,onSwitchSession:f,onRefreshHistory:m,onResumeSavedSession:x}){var b;const h=s.find(g=>g.id===t.ideId),p=(h==null?void 0:h.chats)||[],j=(b=h==null?void 0:h.activeChat)==null?void 0:b.id,u=Ue(t)&&!Ke(t);return e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[e.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?"Saved Sessions":"Chat History"}),e.jsxs("div",{className:"text-xs text-text-muted mt-0.5",children:[t.displayPrimary," — ",ze(t.ideType)]})]}),e.jsx("button",{onClick:d,className:"bg-transparent border-none text-xl text-text-muted cursor-pointer",children:"✕"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&e.jsx("button",{onClick:l,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?e.jsx(e.Fragment,{children:i.map(g=>{const v=t.providerSessionId===g.providerSessionId,S=v||!g.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{S||!x||x(g)},disabled:S,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${v?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${S?"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 ${v?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:vo(g.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.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:[g.workspace||"Workspace unknown",g.currentModel?` · ${g.currentModel}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:v?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})}):p.map(g=>e.jsxs("div",{onClick:()=>{f(t.ideId,g.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===g.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 ${j===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.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:[g.id.substring(0,12),"..."]}),j===g.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(u&&!o&&i.length===0||!u&&p.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(Ii,{size:32})}),e.jsx("div",{className:"text-[13px]",children:u?"No saved sessions found yet.":"No recent chat sessions found."})]}),u&&o&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:m,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(mr,{size:13})," ",u?"Refresh Sessions":"Refresh History"]})})})]})]})}const Yr={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 Gn({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=Yr[n.type]||Yr.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),s(n.id))},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${i.accent}, color-mix(in srgb, ${i.accent} 55%, transparent))`}}),e.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors text-[13px] leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:"×"}),e.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[e.jsx("div",{className:"flex items-center gap-2 pr-8",children:e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:i.chipBg,color:i.chipText,border:`1px solid color-mix(in srgb, ${i.accent} 22%, transparent)`},children:i.label})}),e.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&e.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,c)=>e.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),o.onClick(),s(n.id)},children:o.label},c))})]})]},n.id)})})}function vr(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():Array.isArray(t)?t.map(s=>typeof s=="string"?s:s&&typeof s=="object"&&"text"in s?String(s.text||""):"").join(" ").replace(/\s+/g," ").trim():t&&typeof t=="object"&&"text"in t?String(t.text||"").replace(/\s+/g," ").trim():String(t||"").replace(/\s+/g," ").trim()}const jo=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function ko(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function No(t){return t.sessionId||t.instanceId||t.agentType}function Fs(t,s){return t||s}function Xr(t){return vr(t)}function Jr(t){const s=Number((t==null?void 0:t.timestamp)||(t==null?void 0:t.receivedAt)||(t==null?void 0:t.createdAt)||0);return Number.isFinite(s)?s:0}function Zr(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=Xr(t.content),o=Xr(s.content);if(!i||i!==o)return!1;const c=Jr(t),d=Jr(s);return c&&d?Math.abs(c-d)<=15e3:!!t._localId!=!!s._localId}function Qr(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 qn(t=[]){const s={};for(const r of t){const n=r;(n.type==="adhdev-daemon"||n.daemonMode)&&(s[n.id]=ct(n,{fallbackId:n.id}))}return s}function Yn(t,s,r={}){var h,p,j,u,b,g;const n=[],i=r.machineName,o=r.connectionState,c=ko(t),d=ze(t.type),l=Array.isArray(t.childSessions)?t.childSessions.map(v=>{var S,R;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,agentType:v.providerType,agentName:v.providerName,status:v.status,title:v.title,messages:((S=v.activeChat)==null?void 0:S.messages)||[],activeModal:((R=v.activeChat)==null?void 0:R.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],f=jo(t),m=t.activeChat||{title:""},x=m.title&&String(m.title).trim()?String(m.title).trim():"";if(f){const v=t.sessionId||t.instanceId,S=Hr(t.type),R=(h=t.activeChat)==null?void 0:h.activeModal,w=R&&Array.isArray(R.buttons)&&R.buttons.length>0,N=rt((p=t.activeChat)==null?void 0:p.status,{activeModal:(j=t.activeChat)==null?void 0:j.activeModal})||rt((b=(u=t.agents)==null?void 0:u[0])==null?void 0:b.status)||"idle",y=t.activeChat||{title:"",messages:[]};let k=y.title&&String(y.title).trim()?String(y.title).trim():"";const E=(g=t.activeChat)==null?void 0:g.id,P=t.chats;if(E&&Array.isArray(P)&&P.length>0){const U=P.find(T=>T.id===E||T.id&&String(T.id)===String(E));U!=null&&U.title&&String(U.title).trim()&&(k=String(U.title).trim())}const B=(Ue(t)||Ke(t))&&(t.cliType||t.acpType)||t.type,L=(Ue(t)||Ke(t))&&Fr(k,S,B)?"":k,A=y.messages||[],W=Qr(s,[t.id,v]),z=A.filter(U=>String((U==null?void 0:U.role)||"").toLowerCase()==="user").slice(),D=W.filter(U=>{const T=z.findIndex(M=>Zr(M,U));return T>=0?(z.splice(T,1),!1):!0});n.push({ideId:t.id,sessionId:v,providerSessionId:t.providerSessionId,nativeSessionId:v,transport:t.transport,daemonId:t.daemonId||void 0,mode:Ue(t)?t.mode||"terminal":"chat",agentName:S,agentType:B,status:N,title:L,messages:[...A,...D],resume:t.resume,ideType:B,workspaceName:c,displayPrimary:c||L||(Ue(t)?t.mode==="chat"?S:"Terminal":S),displaySecondary:d,cdpConnected:t.cdpConnected,modalButtons:w?R.buttons:void 0,modalMessage:w?R.message:void 0,streamSource:"native",tabKey:Fs(v,t.id),machineName:i,connectionState:o})}if(f&&(Ue(t)||Ke(t)))return n;for(const v of l){const S=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,R=ro(v),w=No(v),N=`${t.id}:${w}`,y=v.title&&String(v.title).trim()||"",k=Fr(y,v.agentName,v.agentType)?"":y,E=v.messages||[],P=Qr(s,[N,v.sessionId,v.instanceId]),B=E.filter(W=>String((W==null?void 0:W.role)||"").toLowerCase()==="user").slice(),L=P.filter(W=>{const z=B.findIndex(D=>Zr(D,W));return z>=0?(B.splice(z,1),!1):!0});(E.length>0||L.length>0||S||k||!["idle","panel_hidden","disconnected","not_monitored"].includes(R))&&n.push({ideId:t.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:v.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:R,title:k,messages:[...E,...L],ideType:v.agentType,workspaceName:c,displayPrimary:k||x||c||d,displaySecondary:`${d}·${v.agentName}`,cdpConnected:t.cdpConnected,modalButtons:S?v.activeModal.buttons:void 0,modalMessage:S?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Fs(v.sessionId||v.instanceId,N),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:Hr(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:Fs(t.sessionId||t.instanceId,t.id),connectionState:o}),n}function So(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 Co(t,s){const r=[],{daemonId:n,existingDaemon:i,timestamp:o}=s,c=o||t.timestamp||Date.now(),d=t.sessions||[],{topLevel:l,childrenByParent:f}=So(d),m=l.filter(p=>p.kind==="workspace"&&p.transport==="cdp-page"),x=l.filter(p=>p.kind==="agent"&&p.transport==="pty"),h=l.filter(p=>p.kind==="agent"&&p.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.recentLaunches&&{recentLaunches:t.recentLaunches},...t.terminalBackend&&{terminalBackend:t.terminalBackend},...t.detectedIdes&&{detectedIdes:t.detectedIdes},...t.availableProviders&&{availableProviders:t.availableProviders},cdpConnected:m.some(p=>!!p.cdpConnected)});for(const p of m){const j=f.get(p.id)||[];r.push({id:`${n}:ide:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId,parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,ideType:p.providerType,status:p.cdpConnected?"online":"detected",daemonId:n,instanceId:p.id,workspace:p.workspace,terminals:0,childSessions:j,agents:j.map(u=>({id:u.id,name:u.providerName,type:u.providerType,status:u.status})),activeChat:p.activeChat,chats:[],cdpConnected:p.cdpConnected,currentModel:p.currentModel,currentPlan:p.currentPlan,currentAutoApprove:p.currentAutoApprove,lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,controlValues:p.controlValues,providerControls:p.providerControls,timestamp:c})}for(const p of x)r.push({id:`${n}:cli:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId,parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,ideType:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:p.id,cliName:p.providerName,mode:p.mode||"terminal",workspace:p.workspace||"",activeChat:p.activeChat,resume:p.resume,runtimeKey:p.runtimeKey,runtimeDisplayName:p.runtimeDisplayName,runtimeWorkspaceLabel:p.runtimeWorkspaceLabel,runtimeWriteOwner:p.runtimeWriteOwner??null,runtimeAttachedClients:p.runtimeAttachedClients??[],lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,controlValues:p.controlValues,providerControls:p.providerControls,timestamp:c,_isCli:!0});for(const p of h)r.push({id:`${n}:acp:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId,parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,ideType:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:p.id,cliName:p.providerName,mode:"chat",workspace:p.workspace||"",activeChat:p.activeChat,runtimeKey:p.runtimeKey,runtimeDisplayName:p.runtimeDisplayName,runtimeWorkspaceLabel:p.runtimeWorkspaceLabel,runtimeWriteOwner:p.runtimeWriteOwner??null,runtimeAttachedClients:p.runtimeAttachedClients??[],currentModel:p.currentModel,currentPlan:p.currentPlan,lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,acpConfigOptions:p.acpConfigOptions,acpModes:p.acpModes,controlValues:p.controlValues,providerControls:p.providerControls,timestamp:c,_isAcp:!0});return r}function Io(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 To(t,s){const r=Io(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Xn=[{id:"vscode",name:"VS Code",icon:"💙"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"windsurf",name:"Windsurf",icon:"🏄"},{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"trae",name:"Trae",icon:"🔮"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"vscodium",name:"VSCodium",icon:"💚"}],Jn=[{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose CLI",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Zn=[{id:"copilot",name:"GitHub Copilot",icon:"🤖"},{id:"cline",name:"Cline",icon:"🧠"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"continue",name:"Continue",icon:"▶️"}],Qn="adhdev_notification_prefs",en={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0,chatTaskCompletionBubble:!1};function _o(){try{const t=localStorage.getItem(Qn);if(t){const s=JSON.parse(t);return{...en,...s}}}catch{}return{...en}}function Ao(t){try{localStorage.setItem(Qn,JSON.stringify(t))}catch{}}let mt=_o(),vs=[];function Mo(){vs.forEach(t=>t())}function Po(){return{...mt}}function Lo(t){mt={...mt,...t},Ao(mt),Mo()}function Ro(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return vs.push(r),()=>{vs=vs.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Lo(r)},[]);return[{...mt},s]}function Gt(t){if(!mt.globalEnabled)return!1;switch(t){case"disconnect":return mt.disconnectAlert;case"completion":return mt.completionAlert;case"approval":return mt.approvalAlert;case"browser":return mt.browserNotifications;default:return!0}}const Eo={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function $o(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ea(){return"Notification"in window&&Notification.permission==="granted"}let Nt=null;async function Do(){if(Nt!==null)return Nt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Nt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Nt=!!await t.pushManager.getSubscription(),Nt):(Nt=!1,!1)}catch{return Nt=!1,!1}}function ar(t,s,r){if(ea())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 Bo(t,s={}){const r={...Eo,...s},n=a.useRef(new Map),i=a.useRef(0),o=a.useRef(null);a.useEffect(()=>{Do().then(d=>{o.current=d})},[]);const c=a.useCallback((d,l,f)=>{const m=Date.now();m-i.current<r.throttleMs||(i.current=m,ar(d,l,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!ea())&&Gt("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 f=n.current.get(l.id),m=rt(l.status,{activeModal:l.activeModal}),x=l.name||l.id;if(r.onApproval&&Gt("approval")&&m==="waiting_approval"&&f!=="waiting_approval"){const h=((d=l.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,h.slice(0,120),`approval-${l.id}`)}r.onComplete&&Gt("completion")&&On(f)&&m==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${l.id}`),r.onError&&m==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${l.id}`),n.current.set(l.id,m)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}class Ko{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(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)}emitClearSystemMessage(s,r){for(const n of this.clearSystemMessageCallbacks)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 m,x,h;if(!s.ideId&&s.instanceId){for(const p of this.ides)if(p.id.endsWith(`:ide:${s.instanceId}`)||p.id.endsWith(`:cli:${s.instanceId}`)){s.ideId=p.id;break}}const n=this.resolveConversationKey(s),o=`${n||s.instanceId||s.ideType||s.providerType||""}:${s.event}:${s.chatTitle||""}`;if(this.isDuplicate(o))return;let c=ze(s.ideType||"");const d=this.resolveOwningDaemon(s);if(d){const p=ct(d,{fallbackId:d.id});p&&(c=s.ideType==="adhdev-daemon"?p:`${p}/${c}`)}let l="",f="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";l=`✅ ${c} agent task completed${p}`,f="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}n&&Po().chatTaskCompletionBubble&&this.emitSystemMessage(n,{role:"system",timestamp:Date.now(),content:`✅ Task completed${p}`,_localId:`sys_complete_${Date.now()}`})}else if(s.event==="agent:generating_started")n&&this.emitClearSystemMessage(n,"sys_complete_");else if(s.event==="agent:waiting_approval"){if(l=`⚡ ${c} approval needed`,f="warning",n&&!((m=s.modalButtons)!=null&&m.length)){const p=s.modalMessage||"Approval requested",j=(x=s.modalButtons)!=null&&x.length?s.modalButtons.map(u=>`[${u}]`).join(" "):"[Approve] [Reject]";this.emitSystemMessage(n,{role:"system",timestamp:Date.now(),content:`⚡ Approval requested: ${p}
36
+ ${j}`,_localId:`sys_approval_${Date.now()}`})}if((h=s.modalButtons)!=null&&h.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const j=s.agentType||s.ideType||"",u=s.ideType||"",b=s.modalButtons,g=N=>N.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim(),v=this.resolveActionFn,S=b.map((N,y)=>{const k=g(N).toLowerCase(),E=/^(run|approve|accept|yes|allow|always)/.test(k),P=/^(reject|deny|delete|remove|abort|cancel|no)/.test(k);return{label:g(N),variant:E?"primary":P?"danger":"default",onClick:()=>{const B=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k);v(p,"resolve_action",{action:B?"approve":"reject",button:N,buttonIndex:y,agentType:j,ideType:u,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}}}),R=s.modalMessage?`⚡ ${c}: ${s.modalMessage.replace(/[\n\r]+/g," ").slice(0,80)}`:l,w=Date.now();this.emitToast({id:w,message:R,type:f,timestamp:w,targetKey:n||p,actions:S,duration:15e3}),l=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";l=`⚠️ ${c} agent is taking a long time${p}`,f="warning",Gt("browser")&&!document.hasFocus()&&ar(`⚠️ ${c} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.ideId||s.agentType}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",j=s.requestId,u=s.orgId;if(l=`👁️ ${p} wants to view your session`,f="warning",j&&u&&this.viewRequestRespondFn){const b=this.viewRequestRespondFn,g=Date.now(),v=[{label:"Approve",variant:"primary",onClick:()=>{b(u,j,"approve").catch(S=>console.error("[EventManager] approve view request failed:",S))}},{label:"Decline",variant:"danger",onClick:()=>{b(u,j,"reject").catch(S=>console.error("[EventManager] reject view request failed:",S))}}];this.emitToast({id:g,message:l,type:f,timestamp:g,actions:v,duration:3e4}),l=""}Gt("browser")&&!document.hasFocus()&&ar("👁️ View Request",`${p} wants to view your session`,`view-request-${j}`)}else s.event==="team:view_request_approved"?(l="✅ View request approved",f="success"):s.event==="team:view_request_rejected"&&(l=`❌ ${s.targetName||"Team member"} declined your view request`,f="warning");if(l){const p=Date.now();this.emitToast({id:p,message:l,type:f,timestamp:p,targetKey:n||s.ideId,duration:5e3})}}}const vt=new Ko;function Mt(...t){return Xa(Ja(t))}function Wo({icon:t,title:s,subtitle:r,badge:n,actions:i,className:o}){return e.jsxs("div",{className:Mt("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 _s({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(Wo,{icon:t,title:s,subtitle:r,badge:n,actions:i}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:Mt("mx-auto flex w-full flex-col gap-4",o,c),children:d})})]})}function tt({title:t,icon:s,description:r,accentColor:n,className:i,children:o}){return e.jsxs("div",{className:Mt("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 wr({icon:t,title:s,description:r,action:n,className:i}){return e.jsxs("div",{className:Mt("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 Oo={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"},zo={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Uo({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:Mt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Oo[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:zo[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 Ho={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"},Fo={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Vo({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:Mt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ho[t],r),children:[e.jsx("span",{className:Mt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Fo[t])}),n]})}function Go(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ir(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"dark"}function ws(t){return t==="system"?Go():t}function qo(){typeof document>"u"||document.documentElement.setAttribute("data-theme",ws(ir()))}function ta(){const[t,s]=a.useState(ir),[r,n]=a.useState(()=>ws(ir()));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(ws(c));try{localStorage.setItem("theme",c)}catch{}},[]),o=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark";n(ws(d));try{localStorage.setItem("theme",d)}catch{}return d})},[]);return{theme:r,preference:t,setPreference:i,cycleTheme:o,isDark:r==="dark"}}function wt({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 Yo({onPrefChange:t}){const[s,r]=Ro(),n=(i,o)=>{r({[i]:o}),t==null||t(i,o)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ls,{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(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(st,{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(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ti,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:i=>n("completionAlert",i)}),e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_i,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:i=>n("approvalAlert",i)}),e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_t,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:i=>n("disconnectAlert",i)})]}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-2"}),s.globalEnabled&&e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gt,{size:15})," Task Completion Bubble"]}),description:"Show a system message bubble in chat when an agent finishes a task",checked:s.chatTaskCompletionBubble,onChange:i=>n("chatTaskCompletionBubble",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 Xo({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(wr,{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(Zo,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i},c.id))})}function tn({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 Za.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 Jo(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Xn,...Jn,...Zn].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 Zo({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:i}){var W,z;const[o,c]=a.useState("idle"),[d,l]=a.useState(""),[f,m]=a.useState(null),[x,h]=a.useState("idle"),[p,j]=a.useState(""),u=t,b=u.version||u.daemonVersion||null,g=((W=u.machine)==null?void 0:W.platform)||((z=u.system)==null?void 0:z.platform)||"",v=ct(u,{fallbackId:t.id}),S=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",R=s.filter(D=>D.daemonId===t.id&&D.transport==="cdp-page"),w=s.filter(D=>D.daemonId===t.id&&D.transport==="pty"),N=s.filter(D=>D.daemonId===t.id&&D.transport==="acp"),y=u.p2p,k=async()=>{var D,U,T,M;if(r){c("upgrading"),l("Starting upgrade...");try{const _=await r(t.id,"daemon_upgrade",{});(D=_==null?void 0:_.result)!=null&&D.alreadyLatest?(c("done"),l(`Already on v${_.result.version||"latest"}.`)):(U=_==null?void 0:_.result)!=null&&U.upgraded||(T=_==null?void 0:_.result)!=null&&T.success?(c("done"),l(`Upgrade to v${_.result.version||"latest"} started. Daemon is restarting...`)):(c("error"),l(((M=_==null?void 0:_.result)==null?void 0:M.error)||"Upgrade failed"))}catch(_){c("error"),l((_==null?void 0:_.message)||"Connection lost during upgrade")}}},E=async()=>{if(m(null),!!n){h("loading");try{await n(t.id),h("done"),j("Machine disconnected.")}catch(D){h("error"),j((D==null?void 0:D.message)||"Failed to disconnect")}}},P=async()=>{if(m(null),!!i){h("loading");try{await i(t.id),h("done"),j('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(D){h("error"),j((D==null?void 0:D.message)||"Failed to revoke token")}}},B="0.8.20",L=!b||b!==B,A=R.length+w.length+N.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:S}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),b&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",b,!L&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&e.jsx("button",{onClick:k,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,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${B}`}`}),n&&e.jsx("button",{onClick:()=>m("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:()=>m("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(Vo,{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:[y&&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 ${y.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${y.state==="connecting"||y.state==="new"?"animate-pulse":""}`,style:y.state==="connecting"||y.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",y.state==="connected"?"connected":y.state==="connecting"||y.state==="new"?"connecting...":y.state||"off"]}),y.peers!==void 0&&y.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",y.peers," peer",y.peers!==1?"s":"",")"]})]}),y&&A>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),A>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[R.map(D=>{const U=Jo(D.type),T=D.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:U.icon}),e.jsx("span",{children:U.name}),T!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T?"bg-green-400":"animate-pulse"}`,style:T?void 0:{background:"var(--status-warning)"},title:T?"CDP connected":"CDP connecting..."})]},D.id)}),w.map(D=>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:D.cliName||"CLI"})]},D.id)),N.map(D=>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:D.cliName||"ACP"})]},D.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||p)&&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:p||d})]}),f==="disconnect"&&e.jsx(tn,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
37
+
38
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
39
+
40
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:E,onCancel:()=>m(null)}),f==="revoke"&&e.jsx(tn,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
41
+
42
+ This will:
43
+ • Immediately disconnect the machine
44
+ • Delete the machine registration
45
+ • Require restarting "adhdev-standalone" on that machine
46
+
47
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:P,onCancel:()=>m(null)})]})}const Qo=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ec(){const{preference:t,setPreference:s}=ta();return e.jsx("div",{className:"flex gap-2",children:Qo.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 tc(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 sc(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Vs(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function sn(t){const{r:s,g:r,b:n}=sc(t);return .2126*Vs(s)+.7152*Vs(r)+.0722*Vs(n)}function rn(t,s){const r=sn(t),n=sn(s),i=Math.max(r,n),o=Math.min(r,n);return(i+.05)/(o+.05)}function jr(t){const s=tc(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return rn(s,r)>=rn(s,n)?r:n}const sa="adhdev-accent-color",or="#cf7a45";function rc(t){const s=parseInt(t.slice(1,3),16)/255,r=parseInt(t.slice(3,5),16)/255,n=parseInt(t.slice(5,7),16)/255,i=Math.max(s,r,n),o=Math.min(s,r,n);let c=0,d=0;const l=(i+o)/2;if(i!==o){const f=i-o;switch(d=l>.5?f/(2-i-o):f/(i+o),i){case s:c=((r-n)/f+(r<n?6:0))/6;break;case r:c=((n-s)/f+2)/6;break;case n:c=((s-r)/f+4)/6;break}}return{h:Math.round(c*360),s:Math.round(d*100),l:Math.round(l*100)}}function nn(t,s){const{h:r,s:n,l:i}=rc(t),o=Math.min(100,i+s);return`hsl(${r}, ${n}%, ${o}%)`}function Gs(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 nc(){return typeof window>"u"?or:localStorage.getItem(sa)||or}function ac(){if(typeof window>"u")return!1;try{return localStorage.getItem(sa)!=null}catch{return!1}}function ic(t){const s=document.documentElement;s.style.setProperty("--accent-primary",t),s.style.setProperty("--accent-primary-light",nn(t,15)),s.style.setProperty("--accent-on-primary",jr(t)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t}, ${nn(t,20)})`),s.style.setProperty("--border-accent",Gs(t,.4)),s.style.setProperty("--nav-active-bg",Gs(t,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t}, 0 0 12px ${Gs(t,.06)}`)}function oc(){const t=nc();t!==or&&ic(t)}const cr={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},lr={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},cc=[{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"}}}],ra="adhdev-chat-theme",na="adhdev-chat-theme-custom";function js(){if(typeof window>"u")return"ember";try{return localStorage.getItem(ra)||"ember"}catch{return"ember"}}function ot(t){try{const s=localStorage.getItem(na);if(s){const r=JSON.parse(s);return{...t==="dark"?cr:lr,...r[t]}}}catch{}return t==="dark"?cr:lr}function ms(t,s){try{localStorage.setItem(na,JSON.stringify({dark:t,light:s}))}catch{}}function at(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 As(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 lc={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function qt(t,s){var i;if(ac())return;const r=(i=lc[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",As(r,24)),n.style.setProperty("--accent-on-primary",jr(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${As(r,18)})`),n.style.setProperty("--border-accent",at(r,.35)),n.style.setProperty("--nav-active-bg",at(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${at(r,.06)}`)}function Ct(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",at(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",at(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",at(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",at(t.borderSubtle,.5)),s.style.setProperty("--border-default",at(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",As(t.accentColor,30)),s.style.setProperty("--accent-on-primary",jr(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${As(t.accentColor,40)})`),s.style.setProperty("--border-accent",at(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",at(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${at(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 ${at(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 kr(){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 dc(t){try{localStorage.setItem(ra,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=It()?"dark":"light";Ct(ot(s))}else kr(),qt(t,It()?"dark":"light")}function uc(){const t=js();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=It()?"dark":"light";Ct(ot(s))}else kr(),qt(t,It()?"dark":"light")}function It(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function et({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 Ht({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 pc({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,i]=a.useState(()=>ot(r));a.useEffect(()=>{i(ot(r))},[r]);const o=a.useCallback((c,d)=>{i(l=>{const f={...l,[c]:d},x=ot(r==="dark"?"light":"dark");return r==="dark"?ms(f,x):ms(x,f),Ct(f),s(f),f})},[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(Ht,{title:"App Background",children:[e.jsx(et,{label:"Background",value:n.bgPrimary,onChange:c=>o("bgPrimary",c)}),e.jsx(et,{label:"Surface",value:n.bgSecondary,onChange:c=>o("bgSecondary",c)}),e.jsx(et,{label:"Card",value:n.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),e.jsxs(Ht,{title:"App Text",children:[e.jsx(et,{label:"Primary",value:n.textPrimary,onChange:c=>o("textPrimary",c)}),e.jsx(et,{label:"Secondary",value:n.textSecondary,onChange:c=>o("textSecondary",c)}),e.jsx(et,{label:"Muted",value:n.textMuted,onChange:c=>o("textMuted",c)})]}),e.jsxs(Ht,{title:"Borders & Accent",children:[e.jsx(et,{label:"Border subtle",value:n.borderSubtle,onChange:c=>o("borderSubtle",c)}),e.jsx(et,{label:"Border default",value:n.borderDefault,onChange:c=>o("borderDefault",c)}),e.jsx(et,{label:"Accent",value:n.accentColor,onChange:c=>o("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(Ht,{title:"Chat Bubbles",children:[e.jsx(et,{label:"User bubble",value:n.userBubble,onChange:c=>o("userBubble",c)}),e.jsx(et,{label:"User text",value:n.userText,onChange:c=>o("userText",c)}),e.jsx(et,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>o("assistantBubble",c)}),e.jsx(et,{label:"Agent text",value:n.assistantText,onChange:c=>o("assistantText",c)})]}),e.jsxs(Ht,{title:"Chat Layout",children:[e.jsx(et,{label:"Chat BG",value:n.containerBg,onChange:c=>o("containerBg",c)}),e.jsx(et,{label:"Send button",value:n.sendButton,onChange:c=>o("sendButton",c)}),e.jsx(et,{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?cr:lr,l=ot(t?"light":"dark");t?ms(c,l):ms(l,c),i(c),Ct(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 mc(){const[t,s]=a.useState(js),[r,n]=a.useState(!0),[i,o]=a.useState(()=>ot("dark"));a.useEffect(()=>{n(It());const l=new MutationObserver(()=>{const x=It();n(x);const h=js();h==="custom"?Ct(ot(x?"dark":"light")):qt(h,x?"dark":"light")});l.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const x=It();n(x);const h=js();h==="custom"?Ct(ot(x?"dark":"light")):qt(h,x?"dark":"light")};return f.addEventListener("change",m),()=>{l.disconnect(),f.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ct(ot(r?"dark":"light")):(kr(),qt(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{o(ot(r?"dark":"light"))},[r]);const c=l=>{s(l),dc(l)},d=[...cc,{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 f=t===l.id,m=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:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color: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:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&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(pc,{dark:r,onColorsChange:l=>o(l)})]})}const aa="adhdev_mobileDashboardMode_v1";function ia(){try{return localStorage.getItem(aa)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fc(t){try{localStorage.setItem(aa,t)}catch{}}function xc(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(ia()==="chat")},[]),e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gt,{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),fc(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}const oa="adhdev_hiddenTabs";function hc(){try{const t=localStorage.getItem(oa);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function Rt(t){try{localStorage.setItem(oa,JSON.stringify([...t]))}catch{}}function bc(){const[t,s]=a.useState(hc),r=a.useCallback(f=>{s(m=>{const x=new Set(m);return x.has(f)?x.delete(f):x.add(f),Rt(x),x})},[]),n=a.useCallback(f=>{s(m=>{if(m.has(f))return m;const x=new Set(m);return x.add(f),Rt(x),x})},[]),i=a.useCallback(f=>{s(m=>{if(!m.has(f))return m;const x=new Set(m);return x.delete(f),Rt(x),x})},[]),o=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const m=new Set;return Rt(m),m})},[]),c=a.useCallback((f,m)=>{s(x=>{const h=new Set(x);for(const p of m)h.add(p);return Rt(h),h})},[]),d=a.useCallback((f,m)=>{s(x=>{const h=new Set(x);for(const p of m)h.delete(p);return Rt(h),h})},[]),l=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:i,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:d,isHidden:l}}function gc({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{$o()},[]);const i=a.useMemo(()=>t.map(o=>({id:o.tabKey,name:o.title||o.agentName||o.ideId,status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[t]);return Bo(i),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const l=Date.now(),f={};for(const[m,x]of Object.entries(d))l-x<5e3&&(f[m]=x);return Object.keys(f).length===Object.keys(d).length?d:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const l=d.filter(f=>f.timestamp>c).slice(-100);return l.length===d.length?d:l})},6e4);return()=>clearInterval(o)},[n]),null}function qs(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 Dt(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return qs(s==null?void 0:s.timestamp)||qs(s==null?void 0:s.receivedAt)||qs(s==null?void 0:s.createdAt)||0}function ca(t){return Dt(t)}function yc(t,s,r=ca){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 vc(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 fs(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 wc(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 jc(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 kc(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 Nc(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Sc(t){const s=Nc(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=vr(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Cc({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:i}){const o=a.useRef([]),c=a.useRef([]),d=a.useRef([]),l=a.useRef([]),f=a.useMemo(()=>{const w=vc(t);return fs(o.current,w)?o.current:(o.current=w,w)},[t]),m=a.useMemo(()=>qn(t),[t]),x=a.useRef(new Map),h=a.useRef(new Map),p=a.useMemo(()=>{var P;const w=new Map,N=[];for(const B of f){const L=B.daemonId||((P=B.id)==null?void 0:P.split(":")[0])||B.id,A=s[L]||"new",W=B.daemonId&&m[B.daemonId]||void 0,z=jc(B,r),D=x.current.get(B.id);if(D&&D.ide===B&&D.connectionState===A&&D.machineName===W&&kc(D.localRefs,z)){w.set(B.id,D),N.push(...D.conversations);continue}const U=Yn(B,r,{machineName:W,connectionState:A}),T={ide:B,connectionState:A,machineName:W,localRefs:z,conversations:U};w.set(B.id,T),N.push(...U)}x.current=w;const y=new Map,k=B=>{const L=Sc(B),A=h.current.get(B.tabKey);if(A&&A.signature===L)return y.set(B.tabKey,A),A.timestamp;const W={signature:L,timestamp:ca(B)||(A==null?void 0:A.timestamp)||0};return y.set(B.tabKey,W),W.timestamp},E=[...N].sort((B,L)=>yc(B,L,k));return h.current=y,E},[f,r,s,m]),j=a.useMemo(()=>{const w=wc(p,n);return fs(c.current,w)?c.current:(c.current=w,w)},[p,n]),u=a.useMemo(()=>{const w=new Map;for(const N of j)N.sessionId&&w.set(N.sessionId,N);return w},[j]),b=a.useMemo(()=>{const w=new Map;for(const N of j)N.sessionId&&w.set(N.sessionId,N),w.set(N.ideId,N),w.set(N.tabKey,N);return w},[j]),g=a.useCallback(w=>{if(w)return u.get(w)},[u]),v=a.useCallback(w=>{if(w)return b.get(w)},[b]),S=a.useMemo(()=>{const w=j.filter(N=>!i.has(N.tabKey));return fs(d.current,w)?d.current:(d.current=w,w)},[j,i]),R=a.useMemo(()=>{const w=S.map(N=>N.tabKey);return fs(l.current,w)?l.current:(l.current=w,w)},[S]);return{chatIdes:f,conversations:j,visibleConversations:S,visibleTabKeys:R,resolveConversationBySessionId:g,resolveConversationByTarget:v}}function Ic({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 Tc({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:i}){a.useEffect(()=>{vt.setIdes(t)},[t]),a.useEffect(()=>{vt.setResolveAction((o,c,d)=>{s(o,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const o=vt.onToast(l=>{r(m=>m.some(h=>h.message===l.message&&l.timestamp-h.timestamp<3e3)?m:[...m.slice(-4),{id:l.id,message:l.message,type:l.type,timestamp:l.timestamp,targetKey:l.targetKey,actions:l.actions}]);const f=l.duration||5e3;setTimeout(()=>r(m=>m.filter(x=>x.id!==l.id)),f)}),c=vt.onSystemMessage((l,f)=>{var p,j;const m=i(l),x=(p=f._localId)==null?void 0:p.startsWith("sys_approval_"),h=!!(m&&(m.status==="waiting_approval"||(j=m.modalButtons)!=null&&j.length||m.modalMessage));x&&h||n(u=>({...u,[l]:[...u[l]||[],f]}))}),d=vt.onClearSystemMessage((l,f)=>{n(m=>{var x;return(x=m[l])!=null&&x.length?{...m,[l]:m[l].filter(h=>{var p;return!(h.role==="system"&&((p=h._localId)!=null&&p.startsWith(f)))})}:m})});return()=>{o(),c(),d()}},[r,n]),a.useEffect(()=>{const o=Vn.on("status_event",c=>vt.handleRawEvent(c,"ws"));return()=>{o()}},[]),a.useEffect(()=>{var c;const o=d=>{const l=d.data;if((l==null?void 0:l.type)!=="notification_action"||l.action!=="approve"||!(l.ideId||l.targetSessionId||l.targetKey))return;const f=l.targetSessionId||l.targetKey||l.ideId,m=i(f),x=(m==null?void 0:m.ideId)||l.ideId;x&&s(x,"resolve_action",{action:"approve",button:"Approve",...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(h=>console.error("[SW Action] approve failed:",h))};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 _c="adhdev_dashboardLayout_v1",Ac="adhdev_dashboardDockview_v1",Ft={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function la(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function da(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function ua(t){return`${_c}:${t}`}function Mc(t){const s=ua(t);return la(s,null)}function Pc(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=ua(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function pa(t){return`${Ac}:${t}`}function Lc(t){const s=pa(t);return la(s,null)}function Rc(t,s){try{const r=pa(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ec(){return{groupAssignments:[...Ft.groupAssignments],focusedGroup:Ft.focusedGroup,groupActiveTabIds:{...Ft.groupActiveTabIds},groupTabOrders:{...Ft.groupTabOrders},groupSizes:[...Ft.groupSizes]}}function $c(){const[t]=a.useState(()=>da(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({}),[f,m]=a.useState([]),[x,h]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[p,j]=a.useState(!1),u=a.useCallback(()=>{if(p)return;const b=Mc(t)??Ec();r(new Map(b.groupAssignments)),i(b.focusedGroup),c(b.groupActiveTabIds),l(b.groupTabOrders),m(b.groupSizes),j(!0)},[p,t]);return a.useEffect(()=>{p&&Pc(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:d,groupSizes:f})},[p,t,s,n,o,d,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),g=v=>h(v.matches);return b.addEventListener("change",g),()=>b.removeEventListener("change",g)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:i,groupActiveTabIds:o,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:l,groupSizes:f,setGroupSizes:m,isMobile:x,hasHydratedStoredLayout:p,hydrateStoredLayout:u}}function Dc({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:i,hydrateStoredLayout:o,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:l,historyModalOpen:f,activeConv:m,isRefreshingHistory:x,ides:h,handleRefreshHistory:p}){const j=a.useRef(!1),u=a.useRef(!1),b=a.useRef(null),g=a.useRef(!1);a.useEffect(()=>{if(!t||j.current||s.length===0)return;if(!i){o();return}const v=r(t);if(!v)return;const S=n.get(v.tabKey)??0;c(R=>({...R,[S]:v.tabKey})),d(S),j.current=!0,u.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),l(R=>{const w=new URLSearchParams(R);return w.delete("activeTab"),w},{replace:!0})},[t,s,r,n,i,o,c,d,l]),a.useEffect(()=>{if(!(u.current||i)&&s.length!==0){if(!t){o(),u.current=!0;return}if(j.current){u.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(u.current||i)&&(o(),u.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,i,o]),a.useEffect(()=>{if(!f){g.current=!1;return}if(!m||g.current||x)return;const v=h.find(S=>S.id===m.ideId);v&&(!v.chats||v.chats.length===0)&&(g.current=!0,p())},[f,m,x,h,p]),a.useEffect(()=>{if(!m)return;let v=null,S=0,R=-1,w=0;const N=()=>{v=null;const y=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(E=>E.offsetParent!==null);if(y.length===0){S<18&&(S+=1,v=requestAnimationFrame(N));return}let k=0;for(const E of y)E.scrollTop=E.scrollHeight,k+=E.scrollHeight;k===R?w+=1:(w=0,R=k),S+=1,!(w>=2||S>=18)&&(v=requestAnimationFrame(N))};return v=requestAnimationFrame(N),()=>{v!=null&&cancelAnimationFrame(v)}},[m==null?void 0:m.tabKey])}function Bc({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:o,ides:c,resolveConversationByTarget:d}){const[l,f]=a.useState(null),[m,x]=a.useState(null),h=a.useMemo(()=>{if(t||!n)return null;const g=d(n);return g&&!Ue(g)&&!Ke(g)?g:null},[t,n,d]),p=a.useMemo(()=>{const g=l==null?void 0:l.ideId;if(!g)return null;const v=l!=null&&l.tabKey?o.find(S=>S.tabKey===l.tabKey):i?o.find(S=>S.tabKey===i):null;return(v==null?void 0:v.ideId)===g?v:o.find(S=>S.ideId===g&&S.streamSource==="native")||o.find(S=>S.ideId===g)||null},[o,l,i]),j=a.useMemo(()=>{if(p)return c.find(g=>g.id===p.ideId)},[c,p]);a.useEffect(()=>{h&&(f({ideId:h.ideId,tabKey:h.streamSource==="native"?"native":h.tabKey}),x(h),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,h]);const u=a.useCallback(g=>{g&&(f({ideId:g.ideId,tabKey:g.streamSource==="native"?"native":g.tabKey}),x(g))},[]),b=a.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:p,remoteDialogIdeEntry:j,remoteDialogActiveConv:m,setRemoteDialogActiveConv:x,openRemoteDialog:u,closeRemoteDialog:b}}function Kt(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return Ue(t)||Ke(t)?{...s,agentType:t.agentType||t.ideType}:t.streamSource==="agent-stream"?{...s,agentType:t.agentType}:s}function es(t){return t&&(t.ideId||t.daemonId)||""}function xs(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function an({sendDaemonCommand:t,activeConv:s,updateIdeChats:r,setToasts:n,setLocalUserMessages:i,setClearedTabs:o}){const[c,d]=a.useState(!1),[l,f]=a.useState(!1),m=a.useCallback(async j=>{try{await t("standalone","launch_ide",{ideType:j,enableCdp:!0})}catch(u){console.error("Launch failed",u)}},[t]),x=a.useCallback(async(j,u)=>{try{const b=j||(s==null?void 0:s.daemonId)||"",g=await t(b,"switch_chat",{id:u,sessionId:u,...Kt(s)}),v=g==null?void 0:g.result;if((g==null?void 0:g.success)===!0||v==="switched"||v==="switched-by-title")return;v===!1||v==="not_found"?xs(n,"⚠️ Session tab not found — try refreshing history"):typeof v=="string"&&v.startsWith("error:")?xs(n,`⚠️ Switch error: ${v}`):xs(n,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),xs(n,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,t,n]),h=a.useCallback(async()=>{if(!(!s||c)){d(!0);try{const j=es(s);await t(j,"new_chat",{...Kt(s)}),o(u=>({...u,[s.tabKey]:Date.now()})),i(u=>({...u,[s.tabKey]:[]}))}catch(j){console.error("New chat failed",j)}finally{d(!1)}}},[s,c,t,o,i]),p=a.useCallback(async()=>{var j;if(!(!s||l)){f(!0);try{const u=es(s),b=await t(u,"list_chats",{forceExpand:!0,...Kt(s)}),g=(b==null?void 0:b.chats)||((j=b==null?void 0:b.result)==null?void 0:j.chats);b!=null&&b.success&&Array.isArray(g)&&r(s.ideId,g)}catch(u){console.error("Refresh history failed",u)}finally{f(!1)}}},[s,l,t,r]);return{isCreatingChat:c,isRefreshingHistory:l,handleLaunchIde:m,handleSwitchSession:x,handleNewChat:h,handleRefreshHistory:p}}function Kc(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 Wc(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function on(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 hs(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 cn(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 Oc(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 zc(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 ln(t,s){const r={};for(const[n,i]of Object.entries(t)){const o=Number(n);r[o>=s?o+1:o]=i}return r}function dn(t){return Array(t).fill(100/t)}function Uc({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:i,groupSizes:o,setGroupSizes:c,isMobile:d,visibleConversations:l,visibleTabKeys:f}){const m=a.useRef(null),x=a.useMemo(()=>hs(t,f),[t,f]),h=x.assignments,p=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),j=p>1,u=a.useCallback((w,N)=>{s(y=>{const k=new Map(hs(y,f).assignments);return N===0?k.delete(w):k.set(w,N),k}),n(y=>({...y,[N]:w})),r(N)},[s,f,n,r]),b=a.useCallback(w=>{s(N=>{const y=hs(N,f).assignments,k=new Map;for(const[E,P]of y)P!==w&&(P>w?k.set(E,P-1):k.set(E,P));return k}),c(N=>{if(N.length<=1)return[];const y=[...N];y.splice(w,1);const k=y.reduce((E,P)=>E+P,0);return k>0?y.map(E=>E/k*100):[]}),r(0)},[s,f,c,r]),g=a.useCallback((w,N)=>{N.preventDefault();const y=m.current;if(!y)return;const k=N.clientX,E=y.offsetWidth,P=o.length===p?[...o]:dn(p),B=A=>{const z=(A.clientX-k)/E*100,D=[...P];D[w]=Math.max(15,P[w]+z),D[w+1]=Math.max(15,P[w+1]-z),c(D)},L=()=>{document.removeEventListener("mousemove",B),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",B),document.addEventListener("mouseup",L)},[o,p,c]),v=a.useCallback((w,N,y)=>{if(p>=4)return;const k=y==="left"?N:N+1;s(E=>{const P=hs(E,f).assignments,B=new Map;for(const L of l){const A=P.get(L.tabKey)??0,W=A>=k?A+1:A;W>0&&B.set(L.tabKey,W)}return k>0&&B.set(w,k),B}),c(E=>{const P=E.length===p?[...E]:dn(p),B=P[N]??100/p,L=Math.max(15,B/2),A=Math.max(15,B/2),W=[...P];W[N]=L,W.splice(k,0,A);const z=W.reduce((D,U)=>D+U,0);return W.map(D=>D/z*100)}),n(E=>{const P=ln(E,k);return P[k]=w,P}),i(E=>{const P=ln(E,k);return P[k]=[w],P}),r(k)},[p,s,f,l,c,n,i,r]);a.useEffect(()=>{Kc(t,h)||s(h)},[t,h,s]),a.useEffect(()=>{const{mapping:w,usedGroups:N}=x;n(y=>{const k=cn(y,w);return on(y,k)?y:k}),i(y=>{const k=cn(y,w);return on(y,k)?y:k}),r(y=>{const k=d?0:Oc(y,N,w);return y===k?y:k}),c(y=>{const k=d?[]:zc(y,N,x.groupCount);return Wc(y,k)?y:k})},[x,d,n,i,r,c]);const S=a.useMemo(()=>{const w=Array.from({length:p},()=>[]);for(const N of l){const y=h.get(N.tabKey)??0,k=Math.min(y,p-1);w[k].push(N)}return w},[l,h,p]),R=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:h,numGroups:p,isSplitMode:j,groupedConvs:S,moveTabToGroup:u,closeGroup:b,handleResizeStart:g,splitTabRelative:v,clearAllSplits:R}}function Hc({ides:t,sendDaemonCommand:s}){const r="0.8.20",n=a.useMemo(()=>t.filter(f=>{if(f.type!=="adhdev-daemon")return!1;const m=f.version||f.daemonVersion||null;return!m||!r?!1:m!==r}),[r,t]),[i,o]=a.useState(!1),[c,d]=a.useState({}),l=a.useCallback(async f=>{var m,x;d(h=>({...h,[f]:"upgrading"}));try{const h=await s(f,"daemon_upgrade",{});(m=h==null?void 0:h.result)!=null&&m.upgraded||(x=h==null?void 0:h.result)!=null&&x.success?d(p=>({...p,[f]:"done"})):d(p=>({...p,[f]:"error"}))}catch{d(h=>({...h,[f]:"error"}))}},[s]);return{versionMismatchDaemons:n,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:o,upgradingDaemons:c,handleBannerUpgrade:l}}function $s({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:i}){const[o,c]=a.useState(!1),[d,l]=a.useState(!1),f=a.useRef(!1),m=a.useRef(null),x=a.useCallback(async u=>{if(!s)return;const b=u.trim();if(!b||f.current)return;const g=s.tabKey,v=Date.now(),S=m.current;if(S&&S.tabKey===g&&S.message===b&&v-S.timestamp<2e3)return;f.current=!0,l(!0),m.current={tabKey:g,message:b,timestamp:v};const R=`${v}-${Math.random().toString(36).slice(2,8)}`,w={role:"user",content:b,timestamp:v,_localId:R};r(N=>({...N,[g]:[...N[g]||[],w]}));try{const N=es(s);if(!N)return;const y=await t(N,"send_chat",{message:b,text:b,...Kt(s)});if(y!=null&&y.deduplicated||(y==null?void 0:y.sent)===!1){r(k=>({...k,[g]:(k[g]||[]).filter(E=>E._localId!==R)}));return}setTimeout(()=>{const k=Date.now()-6e4;r(E=>{const P=E[g];if(!P)return E;const B=P.filter(L=>L.timestamp>k);return B.length===P.length?E:{...E,[g]:B}})},6e4)}catch(N){console.error("Send failed",N),r(y=>({...y,[g]:(y[g]||[]).filter(k=>k._localId!==R)}))}finally{f.current=!1,l(!1)}},[s,t,r]),h=a.useCallback(async()=>{if(s)try{await t(s.ideId,"launch_ide",{ideType:s.ideType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),p=a.useCallback(async u=>{if(s)try{const g=(s.modalButtons||[]).indexOf(u),v=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v),R=es(s);if(!R)return;(await t(R,"resolve_action",{button:u,action:S?"approve":"reject",...g>=0&&{buttonIndex:g},...Kt(s)})).success||n(N=>[...N,{ideId:s.tabKey,text:`⚠️ **${u}** failed — button not found`,timestamp:Date.now()}])}catch(b){console.error("[ModalButton] Error:",b),n(g=>[...g,{ideId:s.tabKey,text:`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),j=a.useCallback(async()=>{if(!(!s||o)){c(!0);try{await t(s.ideId,"focus_session",{agentType:s.agentType,...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,o,t]);return{isSendingChat:d,isFocusingAgent:o,handleSendChat:x,handleRelaunch:h,handleModalButton:p,handleFocusAgent:j}}const Nr=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:i,terminalRef:o,handleModalButton:c,handleRelaunch:d,handleSendChat:l,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:x,actionLogs:h,userName:p,scrollToBottomRequestNonce:j,isInputActive:u=!0}){return e.jsxs(e.Fragment,{children:[e.jsx(Wn,{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(fr,{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(ho,{activeConv:s,clearToken:r,terminalRef:o,handleSendChat:l,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(nr,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:x,actionLogs:h,userName:p,scrollToBottomRequestNonce:j,isInputActive:u})})]}):e.jsx(nr,{activeConv:s,ideEntry:i,handleSendChat:l,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:x,actionLogs:h,userName:p,scrollToBottomRequestNonce:j,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function Fc({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:i,userName:o,isSendingChat:c,isFocusingAgent:d,onBack:l,onOpenNativeConversation:f,onOpenMachine:m,onOpenHistory:x,onOpenRemote:h,onHideConversation:p,onStopCli:j,cliViewMode:u,onSetCliViewMode:b,handleSendChat:g,handleFocusAgent:v,handleModalButton:S,handleRelaunch:R}){const w=a.useRef(null),N=Ue(t)&&!s,y=N&&u==="terminal",k=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 ${k} 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(ur,{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:t.displayPrimary||t.agentName}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(Un,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&u&&e.jsx(yr,{mode:u,onChange:b,compact:!0}),N&&j&&e.jsx("button",{onClick:()=>{j(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(At,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(t),type:"button",children:e.jsx(pr,{size:14})}),!s&&!N&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(st,{size:14})}),p&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>p(t),type:"button",title:"Close chat",children:e.jsx(At,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Nr,{activeConv:t,clearToken:0,isCliTerminal:y,ideEntry:n,terminalRef:w,handleModalButton:S,handleRelaunch:R,handleSendChat:g,isSendingChat:c,handleFocusAgent:v,isFocusingAgent:d,actionLogs:i,userName:o})})]})}const Ys={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 Vc(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ma(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[i,o]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(Vc())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Ys[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:Ys[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Ys[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 fa({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:st},{key:"chats",label:"Chats",icon:gt}];return e.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:e.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:i,icon:o})=>{const c=t===n;return e.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[e.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:e.jsx(o,{size:15})}),e.jsx("span",{children:i})]},n)})})})}function bs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function Et({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 Vt({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 gs({item:t,type:s,getAvatarText:r,onOpenConversation:n}){const i=s==="needs_attention"||s==="task_complete",o=s==="working",c=s==="earlier";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(t.conversation.displayPrimary)}),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:t.conversation.displayPrimary}),!o&&e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:Kn(t.timestamp)})]}),e.jsxs("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:[t.conversation.displaySecondary,t.conversation.machineName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 opacity-80",children:[e.jsx(st,{size:11})," ",t.conversation.machineName]})]}),s==="needs_attention"&&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 un({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 Gc({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:i,hiddenConversations:o,machineCards:c,getAvatarText:d,onOpenConversation:l,onShowConversation:f,onShowAllHidden:m,onOpenMachine:x,onOpenSettings:h,onSectionChange:p,wsStatus:j="connected",isStandalone:u=!1}){const b=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",g=c.length>0,v=s.length>0||r.length>0||n.length>0||i.length>0,S=t==="machines"?"Machines":"Chats",R=u?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",w=u?"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 ${R}`,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:S}),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(Ls,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:h,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(Ps,{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] ${w}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:b?e.jsx(Vt,{icon:e.jsx(un,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:j==="offline"?"Your device appears to be offline. Waiting for network…":j==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(Vt,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:u?"Waiting for your IDE":"Connect your first machine",subtitle:u?"Open an IDE directly, or choose a workspace before launching CLI or ACP sessions.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!u&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(ma,{})})}):e.jsx(Et,{children:c.map((N,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(N.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(N.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:N.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:N.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[N.unread," new"]}):N.total>0?`${N.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:N.subtitle}),N.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[N.total," chat",N.total!==1?"s":"",N.unread>0?` · ${N.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},N.id))})}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(bs,{title:"Needs attention",className:"mb-0"}),e.jsx(Et,{children:s.map((N,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(gs,{item:N,type:"needs_attention",getAvatarText:d,onOpenConversation:l})},N.conversation.tabKey))})]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(bs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(Et,{children:r.map((N,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(gs,{item:N,type:"task_complete",getAvatarText:d,onOpenConversation:l})},N.conversation.tabKey))})]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(bs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(Et,{children:n.map((N,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(gs,{item:N,type:"working",getAvatarText:d,onOpenConversation:l})},N.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[i.length>0&&e.jsx(bs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),i.length>0?e.jsx(Et,{children:i.map((N,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(gs,{item:N,type:"earlier",getAvatarText:d,onOpenConversation:l})},N.conversation.tabKey))}):v?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):b?e.jsx(Vt,{icon:e.jsx(un,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):g?e.jsx(Vt,{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(gt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are connected. Open the machine screen, choose a workspace, then launch your first IDE, CLI, or ACP session."}):e.jsx(Vt,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),t==="chats"&&o.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(Et,{className:"bg-bg-secondary/25",children:o.map((N,y)=>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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(N),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(N.displayPrimary)}),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:N.displayPrimary}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsxs("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:[N.displaySecondary,N.machineName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 opacity-80",children:[e.jsx(st,{size:11})," ",N.machineName]})]})]}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},N.tabKey))})]})]}),e.jsx(fa,{section:t,onSectionChange:p})]})}function qc(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 Ds(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=qc(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 Yc(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 Sr(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,f)=>/^[A-Za-z]:\\?$/.test(l)?`${l.replace(/\\?$/,"\\")}${f}`:l==="/"||l==="\\"?`${o}${f}`:`${l.replace(/[\\/]+$/,"")}${o}${f}`,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,f)=>l.name.localeCompare(f.name)):[];return{path:i,directories:d}}function Bs({title:t,description:s,currentPath:r,directories:n,busy:i=!1,error:o="",confirmLabel:c="Use this folder",onClose:d,onNavigate:l,onConfirm:f}){const[m,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const h=Yc(r),p=m.trim();return e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:e.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:e.jsx(At,{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:()=>{!h||i||l(h)},disabled:!h||i,children:[e.jsx(ur,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:j=>x(j.target.value),onKeyDown:j=>{j.key!=="Enter"||!p||i||(j.preventDefault(),l(p))},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:()=>{!p||i||l(p)},disabled:!p||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(j=>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(j.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(Wt,{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:j.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:j.path})]})]},j.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:()=>f(p||r),disabled:!p&&!r||i,children:c})]})]})})}function Cr({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:i,onWorkspaceChange:o,confirmLabel:c="Launch",busy:d=!1,onConfirm:l,onCancel:f}){const m=n==null?void 0:n.find(x=>x.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:f,"aria-label":"Close launch confirmation",children:e.jsx(At,{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:x=>o(x.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(x=>e.jsx("option",{value:x.key,children:x.label},x.key))}),(m==null?void 0:m.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:m.description})]}),r.map(x=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:x.value})]},`${x.label}:${x.value}`))]}),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:f,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:l,disabled:d,children:[e.jsx(hr,{size:14}),d?"Launching…":c]})]})]})})}function pn(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Tt(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?"⭐ ":""}${pn(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:pn(c),description:c,workspaceId:null,workspacePath:c}),n){const l=`saved:${n}`;if(o.some(f=>f.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 Xc({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:i,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:d,isStandalone:l,section:f,showBottomNav:m,onBack:x,onSectionChange:h,onOpenConversation:p,onOpenRecent:j,onOpenMachineDetails:u,onMachineUpgrade:b,onLaunchDetectedIde:g,onAddWorkspace:v,onBrowseDirectory:S,onLaunchWorkspaceProvider:R}){var De,Ye,nt,Qe;const w=(pe,_e,Ce)=>pe?"ide":_e>0?"cli":Ce>0?"acp":null,[N,y]=a.useState(!1),k=pe=>pe==="ide"?"IDE":pe==="cli"?"CLI":"ACP",E=r.slice(0,4),P=s.slice(0,3),B=(((De=t.detectedIdes)==null?void 0:De.length)||0)>0,L=a.useMemo(()=>t.workspaces||[],[t]),A=t.defaultWorkspaceId||null,[W,z]=a.useState(A||((Ye=L[0])==null?void 0:Ye.id)||""),[D,U]=a.useState(""),[T,M]=a.useState(""),[_,H]=a.useState([]),[q,ce]=a.useState(!1),[he,we]=a.useState(""),[se,Se]=a.useState(!1),[F,oe]=a.useState(w(B,n.length,i.length)),ee=a.useRef(null),[xe,V]=a.useState(null),Y=a.useRef("__home__"),[re,de]=a.useState("__home__"),[ae,Q]=a.useState(!1),ue=a.useRef(null),C=W==="__custom__"?D.trim():((nt=L.find(pe=>pe.id===W))==null?void 0:nt.path)||"",ne=W==="__custom__"&&!!C&&d.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(d.message),te=W!=="__custom__"&&((Qe=L.find(pe=>pe.id===W))==null?void 0:Qe.path)||"",$=a.useCallback(async pe=>{ce(!0),we("");try{const _e=await S(pe);M(_e.path),U(_e.path),H(_e.directories)}catch(_e){we(_e instanceof Error?_e.message:"Could not load folder")}finally{ce(!1)}},[S]),G=a.useCallback(()=>{var _e,Ce;z("__custom__"),Se(!0);const pe=Ds(t.platform,[D.trim(),te,(_e=L.find(Ne=>Ne.id===A))==null?void 0:_e.path,(Ce=L[0])==null?void 0:Ce.path]);$(pe)},[D,A,$,te,t.platform,L]),Z=a.useCallback((pe,_e)=>{ee.current=_e,Y.current=pe.selectedWorkspaceKey||"__home__",de(pe.selectedWorkspaceKey||"__home__"),V(pe)},[]),ge=a.useCallback(()=>{ee.current&&(Q(!0),ee.current().finally(()=>{ee.current=null,Q(!1),V(null)}))},[]);a.useEffect(()=>{var pe;ue.current!==t.id&&(ue.current=t.id,z(A||((pe=L[0])==null?void 0:pe.id)||"__custom__"),U(""),M(""),H([]),we(""),Se(!1),oe(w(B,n.length,i.length)))},[i.length,n.length,A,B,t.id,L]),a.useEffect(()=>{var pe;W!=="__custom__"&&(W&&L.some(_e=>_e.id===W)||z(A||((pe=L[0])==null?void 0:pe.id)||"__custom__"))},[A,W,L]),a.useEffect(()=>{F==="ide"&&B||F==="cli"&&n.length>0||F==="acp"&&i.length>0||oe(w(B,n.length,i.length))},[F,i.length,n.length,B]);const ye=a.useMemo(()=>{const pe=E.map(Ce=>({key:`recent-launch:${Ce.id}`,type:"session",primary:Ce.label,secondary:`${k(Ce.kind)}${Ce.subtitle?` · ${Ce.subtitle}`:""}`,unread:!1,onClick:()=>{const{options:Ne,selectedKey:O}=Tt({machine:{workspaces:L,defaultWorkspaceId:A},currentWorkspacePath:Ce.workspace});Z({title:`Launch ${Ce.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:Ne,selectedWorkspaceKey:O,details:[{label:"Mode",value:k(Ce.kind)},...Ce.providerType?[{label:"Provider",value:Ce.providerType}]:[]]},async()=>{const K=Ne.find(le=>le.key===Y.current);K!=null&&K.workspaceId?(z(K.workspaceId),U("")):K!=null&&K.workspacePath?(z("__custom__"),U(K.workspacePath)):(z(""),U("")),await j({...Ce,workspace:(K==null?void 0:K.workspacePath)??null})})}})),_e=P.map(Ce=>({key:`recent-chat:${Ce.conversation.tabKey}`,type:"conversation",primary:Ce.conversation.displayPrimary,secondary:`Chat${Ce.conversation.displaySecondary?` · ${Ce.conversation.displaySecondary}`:""}${Ce.timestamp?` · ${Kn(Ce.timestamp)}`:""}`,unread:Ce.unread,onClick:()=>p(Ce.conversation)}));return[...pe,..._e]},[A,p,j,Z,P,E,L]),Ee=N?ye:ye.slice(0,5),$e=ye.length>0,Re=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 ${Re} 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(ur,{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:ct(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:[$e&&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"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:Ee.map(pe=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${pe.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:pe.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:pe.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:pe.secondary})]},pe.key))}),ye.length>5&&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:()=>y(pe=>!pe),children:N?"Show fewer":`Show ${ye.length-5} more`})})]}),(B||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:W,onChange:pe=>{const _e=pe.target.value;if(z(_e),_e==="__custom__"){G();return}U("")},className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:L.length>0?e.jsxs(e.Fragment,{children:[L.map(pe=>e.jsxs("option",{value:pe.id,children:[pe.id===A?"⭐ ":"",Es(pe.path,pe.label)||pe.path]},pe.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),W==="__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(Wt,{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:C||T||"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:G,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:()=>{C&&v(C)},disabled:!C||q,children:"Save as workspace"})]})]}),C&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:C})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[B&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${F==="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:()=>oe("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${F==="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:()=>oe("cli"),children:"CLI"}),i.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${F==="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:()=>oe("acp"),children:"ACP"})]}),F&&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:F==="ide"?"Choose an IDE":F==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:F==="ide"?(t.detectedIdes||[]).slice(0,6).map(pe=>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:_e,selectedKey:Ce}=Tt({machine:{workspaces:L,defaultWorkspaceId:A},currentWorkspaceId:W!=="__custom__"?W:null,currentWorkspacePath:C});Z({title:`Launch ${pe.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:_e,selectedWorkspaceKey:Ce,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:pe.name}]},async()=>{const Ne=_e.find(O=>O.key===Y.current);Ne!=null&&Ne.workspaceId?(z(Ne.workspaceId),U("")):Ne!=null&&Ne.workspacePath?(z("__custom__"),U(Ne.workspacePath)):(z(""),U("")),g(pe.type,{workspacePath:(Ne==null?void 0:Ne.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:pe.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:C||"Use selected workspace"})]},pe.type)):(F==="cli"?n:i).map(pe=>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:_e,selectedKey:Ce}=Tt({machine:{workspaces:L,defaultWorkspaceId:A},currentWorkspaceId:W!=="__custom__"?W:null,currentWorkspacePath:C});Z({title:`Launch ${pe.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${F.toUpperCase()}`,workspaceOptions:_e,selectedWorkspaceKey:Ce,details:[{label:"Mode",value:F.toUpperCase()},{label:"Provider",value:pe.displayName}]},async()=>{const Ne=_e.find(O=>O.key===Y.current);Ne!=null&&Ne.workspaceId?(z(Ne.workspaceId),U("")):Ne!=null&&Ne.workspacePath?(z("__custom__"),U(Ne.workspacePath)):(z(""),U("")),R(F,pe.type,{workspaceId:(Ne==null?void 0:Ne.workspaceId)??null,workspacePath:(Ne==null?void 0:Ne.workspacePath)??null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[pe.icon?`${pe.icon} `:"",pe.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:C||"Use selected workspace"})]},pe.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,ne&&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:()=>v(C,{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:b,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),se&&e.jsx(Bs,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T,directories:_,busy:q,error:he,confirmLabel:"Use this folder",onClose:()=>Se(!1),onNavigate:pe=>{$(pe)},onConfirm:pe=>{U(pe),z("__custom__"),Se(!1)}}),xe&&e.jsx(Cr,{title:xe.title,description:xe.description,details:xe.details,workspaceOptions:xe.workspaceOptions,selectedWorkspaceKey:re,onWorkspaceChange:pe=>{Y.current=pe,de(pe)},confirmLabel:xe.confirmLabel,busy:ae,onConfirm:ge,onCancel:()=>{ee.current=null,V(null)}}),m&&e.jsx(fa,{section:f,onSectionChange:h})]})}function Jc(t){return vr(t)}function mn(t){const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=Jc(s==null?void 0:s.content);return r||(t.title?t.title:t.displaySecondary||"No messages yet")}function Zc(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function ys(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${t}`,s)}catch{}}function Qc(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function fn(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function el(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function tl({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,userName:l,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:x,onRequestedMachineConsumed:h,requestedMobileSection:p,onRequestedMobileSectionConsumed:j,onOpenHistory:u,onOpenRemote:b,onStopCli:g,wsStatus:v,isConnected:S,onShowHiddenConversation:R,onShowAllHiddenConversations:w,onHideConversation:N}){const[y,k]=a.useState(()=>{var O;return((O=t[0])==null?void 0:O.tabKey)||null}),[E,P]=a.useState(()=>t[0]?"chat":"inbox"),[B,L]=a.useState("chats"),[A,W]=a.useState(null),[z,D]=a.useState("inbox"),[U,T]=a.useState("idle"),[M,_]=a.useState(""),[H,q]=a.useState(null),ce=a.useRef(null),he=zt(),we="0.8.20",se=a.useMemo(()=>t.find(O=>O.tabKey===y)||t[0]||null,[t,y]),Se=a.useMemo(()=>se?r.find(O=>O.id===se.ideId):void 0,[r,se]),F=a.useMemo(()=>!se||Ke(se)||!Ue(se)?null:Ot(se),[se]),oe=a.useMemo(()=>r.filter(O=>O.type==="adhdev-daemon"||O.daemonMode).sort(br),[r]),ee=a.useMemo(()=>oe.find(O=>O.id===A)||null,[oe,A]),xe=a.useMemo(()=>ns(r),[r]),V=$s({sendDaemonCommand:i,activeConv:se||void 0,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),Y=a.useCallback(O=>{if(!O||!O.sessionId)return;const K=Jt(O,xe),le=Math.max(Date.now(),Dt(O),K.lastUpdated||0);ys("mark_read:start",{tabKey:O.tabKey,sessionId:O.sessionId,displayPrimary:O.displayPrimary,inboxBucket:K.inboxBucket,unread:K.unread,lastSeenAt:K.lastSeenAt,lastUpdated:K.lastUpdated,activityAt:Dt(O),readAt:le}),i(O.daemonId||O.ideId,"mark_session_seen",{sessionId:O.sessionId,seenAt:le}).then(me=>{ys("mark_read:result",{tabKey:O.tabKey,sessionId:O.sessionId,result:me})}).catch(me=>{ys("mark_read:error",{tabKey:O.tabKey,sessionId:O.sessionId,error:me instanceof Error?me.message:String(me)})})},[xe,i]);a.useEffect(()=>{var K;if(!se){P("inbox"),k(((K=t[0])==null?void 0:K.tabKey)||null),ce.current=null;return}if(E!=="chat"){ce.current=null;return}const O=`${se.tabKey}:${se.sessionId||""}`;ce.current!==O&&(ce.current=O,Y(se))},[t,Y,E,se]),a.useEffect(()=>{if(!f)return;const O=t.find(K=>K.tabKey===f);O&&(k(O.tabKey),P("chat"),m==null||m())},[t,m,f]),a.useEffect(()=>{if(!x)return;const O=oe.find(K=>K.id===x);O&&(W(O.id),T("idle"),_(""),L("machines"),D("inbox"),P("machine"),h==null||h())},[oe,h,x]),a.useEffect(()=>{p&&(L(p),P("inbox"),j==null||j())},[j,p]);const re=a.useMemo(()=>t.map(O=>{const K=E==="chat"&&(se==null?void 0:se.tabKey)===O.tabKey,le=Zt(O,xe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:K}),me=Dt(O),I=mn(O);return{conversation:O,timestamp:me,preview:I,unread:le.unread,requiresAction:le.requiresAction,isWorking:le.isWorking,inboxBucket:le.inboxBucket}}),[t,xe,E,se]);a.useEffect(()=>{const O=re.filter(K=>K.inboxBucket==="task_complete"||K.unread);O.length!==0&&ys("inbox_state",{screen:E,selectedTabKey:y,items:O.map(K=>{const le=Jt(K.conversation,xe);return{liveState:le,tabKey:K.conversation.tabKey,sessionId:K.conversation.sessionId,displayPrimary:K.conversation.displayPrimary,serverBucket:le.inboxBucket,computedBucket:K.inboxBucket,serverUnread:le.unread,computedUnread:K.unread,lastSeenAt:le.lastSeenAt,lastUpdated:le.lastUpdated,activityAt:Dt(K.conversation)}})})},[re,xe,E,y]);const de=a.useMemo(()=>re.filter(O=>O.requiresAction),[re]),ae=a.useMemo(()=>re.filter(O=>O.unread&&!O.requiresAction),[re]),Q=a.useMemo(()=>re.filter(O=>!O.unread&&!O.requiresAction&&O.isWorking),[re]),ue=a.useMemo(()=>re.filter(O=>!O.unread&&!O.requiresAction&&!O.isWorking),[re]),C=a.useMemo(()=>ee?re.filter(O=>O.conversation.daemonId===ee.id||O.conversation.ideId===ee.id):[],[re,ee]),ne=a.useMemo(()=>{if(!ee)return[];const O=ee.recentLaunches||[];return O.length>0?O.map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:K.currentModel||K.workspace||void 0,workspace:K.workspace,currentModel:K.currentModel})):r.filter(K=>!K.daemonMode&&K.daemonId===ee.id).map(K=>{var me,I,J,ie,X;const le=Qt(K)?"cli":Bt(K)?"acp":"ide";return{id:`${le}:${K.type}:${K.workspace||""}`,label:((me=K.activeChat)==null?void 0:me.title)||(Qt(K)?K.cliName||K.type:Bt(K)&&K.cliName||K.type),kind:le,providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Bt(K)?K.currentModel||K.workspace||void 0:K.workspace||void 0,workspace:K.workspace||void 0,currentModel:K.currentModel,timestamp:((X=(ie=(J=(I=K.activeChat)==null?void 0:I.messages)==null?void 0:J.at)==null?void 0:ie.call(J,-1))==null?void 0:X.timestamp)||0}}).sort((K,le)=>le.timestamp-K.timestamp).map(({timestamp:K,...le})=>le)},[r,ee]),te=(ee==null?void 0:ee.version)||(ee==null?void 0:ee.daemonVersion)||null,$=!!ee&&!!te&&!0&&te!==we,G=a.useMemo(()=>(ee==null?void 0:ee.availableProviders)||[],[ee]),Z=a.useMemo(()=>G.filter(O=>O.category==="cli").map(O=>({type:O.type,displayName:O.displayName||O.type,icon:O.icon})),[G]),ge=a.useMemo(()=>G.filter(O=>O.category==="acp").map(O=>({type:O.type,displayName:O.displayName||O.type,icon:O.icon})),[G]),ye=a.useMemo(()=>{const O=new Map;for(const K of re){const le=K.conversation.daemonId||K.conversation.ideId,me=O.get(le);me?me.push(K):O.set(le,[K])}return oe.map(K=>{const le=O.get(K.id)||[],me=[...le].sort((ve,Me)=>Me.timestamp-ve.timestamp)[0]||null,I=(me==null?void 0:me.conversation)||null,J=sr(K),ie=le.filter(ve=>ve.unread||ve.requiresAction).length,X=K.status==="online"?"Connected":K.status||"Unknown",Ie=[K.platform||"machine",X].filter(Boolean);return{id:K.id,label:ct(K,{fallbackId:K.id}),subtitle:Ie.join(" · "),unread:ie,total:le.length,latestConversation:I,latestTimestamp:(me==null?void 0:me.timestamp)||0,fallbackActivityAt:J,preview:I?`${I.displayPrimary} · ${mn(I)}`:"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((K,le)=>{const me=K.latestTimestamp||K.fallbackActivityAt||0,I=le.latestTimestamp||le.fallbackActivityAt||0;return I!==me?I-me:K.label.localeCompare(le.label)})},[re,oe]),Ee=a.useCallback(O=>{k(O.tabKey),P("chat"),Y(O)},[Y]),$e=a.useCallback(O=>{const K=t.find(le=>le.ideId===O.ideId&&le.streamSource==="native");K&&(k(K.tabKey),P("chat"),Y(K))},[t,Y]),Re=a.useCallback(()=>{Y(se),P("inbox")},[Y,se]),De=a.useCallback(O=>{W(O),T("idle"),_(""),q(null),L("machines"),D("inbox"),P("machine")},[]),Ye=a.useCallback(O=>{var le;const K=O.daemonId||((le=O.ideId)==null?void 0:le.split(":")[0])||O.ideId;K&&(W(K),T("idle"),_(""),q(null),L("machines"),D("chat"),P("machine"))},[]),nt=a.useCallback(()=>{q(null),P(z)},[z]),Qe=a.useCallback(async(O,K,le)=>{var me;try{T("loading"),_(`Launching ${K}…`);const I={ideType:K,enableCdp:!0};(me=le==null?void 0:le.workspacePath)!=null&&me.trim()&&(I.workspace=le.workspacePath.trim()),await i(O,"launch_ide",I),T("done"),_(`${K} launch requested`)}catch(I){T("error"),_(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[i]),pe=a.useCallback(async(O,K,le)=>{if(K.trim())try{T("loading"),_(le!=null&&le.createIfMissing?"Creating folder…":"Saving workspace…");const me=await i(O,"workspace_add",{path:K.trim(),createIfMissing:(le==null?void 0:le.createIfMissing)===!0});if(me!=null&&me.success){T("done"),_(le!=null&&le.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}T("error"),_((me==null?void 0:me.error)||"Could not save workspace")}catch(me){T("error"),_(me instanceof Error?me.message:"Could not save workspace")}},[i]),_e=a.useCallback(async O=>{var K,le,me,I,J,ie;try{T("loading"),_("Starting daemon upgrade…");const X=await i(O,"daemon_upgrade",{});if((K=X==null?void 0:X.result)!=null&&K.alreadyLatest){T("done"),_(`Already on v${((le=X==null?void 0:X.result)==null?void 0:le.version)||"latest"}.`);return}if((me=X==null?void 0:X.result)!=null&&me.upgraded||(I=X==null?void 0:X.result)!=null&&I.success){T("done"),_(`Upgrade to v${((J=X==null?void 0:X.result)==null?void 0:J.version)||"latest"} started. Daemon is restarting…`);return}T("error"),_(((ie=X==null?void 0:X.result)==null?void 0:ie.error)||"Upgrade failed")}catch(X){T("error"),_(X instanceof Error?X.message:"Upgrade failed")}},[i]),Ce=a.useCallback(async(O,K,le,me)=>{var ie;const I=Date.now(),J={machineId:O,kind:K,providerType:le,workspaceId:(me==null?void 0:me.workspaceId)||null,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:I};try{T("loading"),_(`Launching ${le}…`),q(J);const X={cliType:le};(ie=me==null?void 0:me.workspacePath)!=null&&ie.trim()?X.dir=me.workspacePath.trim():me!=null&&me.workspaceId&&(X.workspaceId=me.workspaceId),me!=null&&me.resumeSessionId&&(X.resumeSessionId=me.resumeSessionId);const Ie=await i(O,"launch_cli",X),ve=(Ie==null?void 0:Ie.result)||Ie,Me=(ve==null?void 0:ve.sessionId)||(ve==null?void 0:ve.id);if(Ie!=null&&Ie.success&&Me){q(null),T("done"),_(`${le} launched`),he(`/dashboard?activeTab=${encodeURIComponent(Me)}`);return}if(Ie!=null&&Ie.success){T("loading"),_(`${le} launch requested — waiting for session…`);return}q(null),T("error"),_((Ie==null?void 0:Ie.error)||(ve==null?void 0:ve.error)||`Could not launch ${K.toUpperCase()} workspace`)}catch(X){if(el(X)){T("loading"),_(`${le} launch requested — waiting for session…`);return}q(null),T("error"),_(X instanceof Error?X.message:`Could not launch ${K.toUpperCase()} workspace`)}},[he,i]);a.useEffect(()=>{var me;if(!H)return;const O=fn(H.workspacePath),K=r.find(I=>{var Me,Ge,Fe,We;if(!I||I.type==="adhdev-daemon"||I.daemonMode||Qc(I.daemonId||I.id)!==H.machineId||(I.transport==="acp"?"acp":I.transport==="pty"?"cli":null)!==H.kind||String(I.agentType||I.ideType||I.type||"")!==H.providerType)return!1;const Ie=String(I.providerSessionId||"");if(H.resumeSessionId&&Ie)return Ie===H.resumeSessionId;if(O){const lt=fn(I.workspace||I.runtimeWorkspaceLabel);return lt?lt===O:!1}return Number(I.lastUpdated||I._lastUpdate||I.timestamp||((We=(Fe=(Ge=(Me=I.activeChat)==null?void 0:Me.messages)==null?void 0:Ge.at)==null?void 0:Fe.call(Ge,-1))==null?void 0:We.timestamp)||0)>=H.startedAt-5e3});if(!K)return;const le=typeof K.sessionId=="string"&&K.sessionId?K.sessionId:typeof K.instanceId=="string"&&K.instanceId?K.instanceId:(me=t.find(I=>I.ideId===K.id))==null?void 0:me.sessionId;le&&(q(null),T("done"),_(`${H.providerType} launched`),he(`/dashboard?activeTab=${encodeURIComponent(le)}`))},[t,r,he,H]),a.useEffect(()=>{if(!H)return;const O=window.setTimeout(()=>{q(K=>!K||K.startedAt!==H.startedAt?K:(T("error"),_("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(O)},[H]);const Ne=a.useCallback(async O=>{if(ee){if(O.kind==="ide"&&O.providerType){await Qe(ee.id,O.providerType,{workspacePath:O.workspace||null});return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await Ce(ee.id,O.kind,O.providerType,{workspacePath:O.workspace||null,resumeSessionId:O.providerSessionId||null});return}}},[Qe,Ce,ee]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&se?e.jsx(Fc,{selectedConversation:se,isAcp:Ke(se),isStandalone:d,selectedIdeEntry:Se,actionLogs:n,userName:l,isSendingChat:V.isSendingChat,isFocusingAgent:V.isFocusingAgent,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,onBack:Re,onOpenNativeConversation:$e,onOpenMachine:Ye,onHideConversation:N,onOpenHistory:u,onOpenRemote:b,onStopCli:g,cliViewMode:F,onSetCliViewMode:async O=>{if(se&&F!==O)try{await i(se.daemonId||se.ideId,"set_cli_view_mode",{targetSessionId:se.sessionId,cliType:se.ideType||se.agentType,mode:O})}catch(K){console.error("Failed to switch CLI view mode:",K)}},handleSendChat:V.handleSendChat,handleFocusAgent:V.handleFocusAgent}):E==="machine"&&ee?e.jsx(Xc,{selectedMachineEntry:ee,selectedMachineConversations:C,selectedMachineRecentLaunches:ne,cliProviders:Z,acpProviders:ge,selectedMachineNeedsUpgrade:$,appVersion:we,machineAction:{state:U,message:M},isStandalone:d,section:B,showBottomNav:z==="inbox",onBack:nt,onSectionChange:O=>{L(O),P("inbox")},onOpenConversation:Ee,onOpenRecent:Ne,onOpenMachineDetails:()=>he(`/machines/${ee.id}`),onMachineUpgrade:()=>_e(ee.id),onLaunchDetectedIde:(O,K)=>Qe(ee.id,O,K),onAddWorkspace:(O,K)=>pe(ee.id,O,K),onBrowseDirectory:async O=>{const K=await i(ee.id,"file_list_browse",{path:O});if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Could not browse folder");const le=typeof(K==null?void 0:K.path)=="string"?K.path:O,me=le.includes("\\")?"\\":"/",I=(ie,X)=>/^[A-Za-z]:\\?$/.test(ie)?`${ie.replace(/\\?$/,"\\")}${X}`:ie==="/"||ie==="\\"?`${me}${X}`:`${ie.replace(/[\\/]+$/,"")}${me}${X}`,J=Array.isArray(K==null?void 0:K.files)?K.files.filter(ie=>(ie==null?void 0:ie.type)==="directory"&&typeof(ie==null?void 0:ie.name)=="string").map(ie=>({name:ie.name,path:I(le,ie.name)})).sort((ie,X)=>ie.name.localeCompare(X.name)):[];return{path:le,directories:J}},onLaunchWorkspaceProvider:(O,K,le)=>Ce(ee.id,O,K,le)}):e.jsx(Gc,{section:B,attentionItems:de,unreadItems:ae,workingItems:Q,completedItems:ue,hiddenConversations:s,machineCards:ye,getAvatarText:Zc,onOpenConversation:Ee,onShowConversation:R,onShowAllHidden:w,onOpenMachine:De,onOpenSettings:()=>he("/settings"),onSectionChange:L,wsStatus:v,isConnected:S,isStandalone:d})})}function Xs(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function sl({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:i,onClearPreviewOrder:o}){const c=a.useRef(0),[d,l]=a.useState(!1),[f,m]=a.useState(null),x=a.useCallback(()=>{c.current=0,l(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const h=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,l(!0))},[]),p=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Xs(s,r)){m("merge");return}const g=b.currentTarget.getBoundingClientRect(),v=b.clientX-g.left,S=g.width/3;v<S?m("split-left"):v>S*2?m("split-right"):m("merge")},[s,r]),j=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,l(!1),m(null))},[]),u=a.useCallback(b=>{c.current=0,l(!1);const g=b.dataTransfer.getData("text/tab-key"),v=g?t.some(R=>R.tabKey===g):!1,S=f;if(m(null),o(),!!g){if(b.preventDefault(),S==="split-left"&&Xs(s,r)){r==null||r(g,"split-left");return}if(S==="split-right"&&Xs(s,r)){r==null||r(g,"split-right");return}if(v){i(g);return}n==null||n(g)}},[t,f,s,r,n,i,o]);return{dragOver:d,dropAction:f,resetDragState:x,handleDragEnter:h,handleDragOver:p,handleDragLeave:j,handleDrop:u}}function rl(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 nl({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:i}){const[o,c]=a.useState(s??null),[d,l]=a.useState(r??[]),[f,m]=a.useState(null),x=a.useRef(null),h=a.useRef(null),p=a.useRef(n),j=a.useRef(i);a.useEffect(()=>{p.current=n},[n]),a.useEffect(()=>{j.current=i},[i]),a.useEffect(()=>{s&&s!==o&&c(s)},[s,o]),a.useEffect(()=>{l(y=>{const k=rl(y,t);return k.length===y.length&&k.every((E,P)=>E===y[P])?y:k})},[t]);const u=a.useMemo(()=>{const y=f??d;if(y.length===0)return t;const k=new Map(y.map((E,P)=>[E,P]));return[...t].sort((E,P)=>{const B=k.get(E.tabKey)??999,L=k.get(P.tabKey)??999;return B-L})},[t,f,d]);a.useEffect(()=>{var k,E;if(u.length===0){o!==null&&(c(null),(k=p.current)==null||k.call(p,null));return}if(o&&u.some(P=>P.tabKey===o))return;const y=u[0].tabKey;y!==o&&(c(y),(E=p.current)==null||E.call(p,y))},[u,o]);const b=a.useMemo(()=>u.find(y=>y.tabKey===o),[u,o]),g=a.useCallback(y=>{var k;c(y),(k=p.current)==null||k.call(p,y)},[]),v=a.useCallback((y,k,E)=>{l(P=>{var W;const B=P.filter(z=>z!==y),L=B.indexOf(k);if(L<0)return P;const A=E==="left"?L:L+1;return B.splice(A,0,y),(W=j.current)==null||W.call(j,B),B}),m(null)},[]),S=a.useCallback((y,k,E)=>{const B=(d.length>0?d:t.map(W=>W.tabKey)).filter(W=>W!==y),L=B.indexOf(k);if(L<0)return;const A=E==="left"?L:L+1;B.splice(A,0,y),x.current=B,m(B)},[d,t]),R=a.useCallback(()=>{var k;const y=x.current;y&&(l(y),(k=j.current)==null||k.call(j,y))},[]),w=a.useCallback(()=>{x.current=null,m(null)},[]),N=a.useCallback(y=>{l(k=>{var P;const E=k.filter(B=>B!==y);return E.push(y),(P=j.current)==null||P.call(j,E),E})},[]);return{activeTabId:o,activeConv:b,sortedConversations:u,previewOrderRef:x,draggingTabRef:h,selectTab:g,handleTabReorder:v,updatePreviewOrder:S,commitPreviewOrder:R,clearPreviewOrder:w,moveTabToEnd:N,setDraggingTabKey:y=>{h.current=y}}}function al({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 Ir({conversationsCount:t,isSplitMode:s,isStandalone:r,detectedIdes:n,handleLaunchIde:i}){return t===0&&!s&&n&&i?e.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[e.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),e.jsxs("div",{className:"text-center max-w-lg",children:[e.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:"Waiting for your IDE"}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:r?"Open an IDE directly, or choose a workspace first before launching CLI or ACP sessions.":"Install the ADHDev daemon and link your dashboard to start."}),!r&&e.jsx(ma,{}),r&&n.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:n.map(o=>e.jsxs("button",{className:"btn btn-sm bg-accent/10 border border-accent/25 text-accent text-xs font-medium px-4 py-2.5 rounded-lg cursor-pointer flex items-center gap-2 transition-all hover:bg-accent/20 hover:scale-105 active:scale-95",onClick:()=>i(o.type),children:[e.jsx($n,{size:14,className:"opacity-70"})," Open ",o.name]},o.type))})]}),!r&&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 xa="adhdev-tab-shortcuts";function il(){try{return JSON.parse(localStorage.getItem(xa)||"{}")}catch{return{}}}function ha({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const i=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,c]=a.useState(()=>il()),[d,l]=a.useState(null),f=a.useCallback(x=>{const h=[];return x.metaKey&&h.push(i?"⌘":"Meta"),x.ctrlKey&&h.push("Ctrl"),x.altKey&&h.push(i?"⌥":"Alt"),x.shiftKey&&h.push(i?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(h.push(x.key.length===1?x.key.toUpperCase():x.key),h.join("+"))},[i]),m=a.useCallback(x=>{c(x);try{localStorage.setItem(xa,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const x=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){l(null);return}const p=f(h);if(!p)return;const j={...o};for(const[u,b]of Object.entries(j))b===p&&delete j[u];j[d]=p,m(j),l(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[t,d,o,m,f]),a.useEffect(()=>{if(!t)return;const x=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[p,j]of Object.entries(o))if(s.includes(p)&&f(h)===j){h.preventDefault(),r(),n(p);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,o,s,r,n,f]),{isMac:i,tabShortcuts:o,shortcutListening:d,setShortcutListening:l,saveShortcuts:m}}const ol=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:i,shortcut:o,conversationKeys:c,draggingTabRef:d,onFocus:l,onSelectTab:f,onConversationActivated:m,onPreviewReorder:x,onReorderTab:h,onCommitPreviewOrder:p,onClearPreviewOrder:j,onDragStateReset:u,onDragTabKeyChange:b,onReceiveTab:g,onOpenContextMenu:v,longPressTimer:S,isGroupActive:R}){const w=Rs(s),N=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",y=w.isReconnecting,k=a.useCallback(U=>{d.current=s.tabKey,b(s.tabKey),U.dataTransfer.setData("text/tab-key",s.tabKey),U.dataTransfer.effectAllowed="move"},[s.tabKey,d,b]),E=a.useCallback(()=>{d.current=null,b(null),p(),j(),u()},[d,b,p,j,u]),P=a.useCallback(U=>{const T=d.current;if(!(!T||T===s.tabKey)&&U.dataTransfer.types.includes("text/tab-key")){U.preventDefault(),U.stopPropagation();const M=U.currentTarget.getBoundingClientRect(),_=U.clientX<M.left+M.width/2?"left":"right";x(T,s.tabKey,_)}},[s.tabKey,d,x]),B=a.useCallback(U=>{U.preventDefault(),U.stopPropagation();const T=U.dataTransfer.getData("text/tab-key");if(T&&T!==s.tabKey){const M=U.currentTarget.getBoundingClientRect(),_=U.clientX<M.left+M.width/2?"left":"right";c.includes(T)?h(T,s.tabKey,_):g&&g(T)}j()},[s.tabKey,c,h,g,j]),L=a.useCallback(U=>{U.stopPropagation(),l(),f(s.tabKey),m(s)},[s,m,l,f]),A=a.useCallback(U=>{U.preventDefault(),v(U.clientX,U.clientY,s.tabKey)},[s.tabKey,v]),W=a.useCallback(U=>{const T=U.touches[0];S.current=setTimeout(()=>{v(T.clientX,T.clientY,s.tabKey)},600)},[s.tabKey,S,v]),z=a.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),D=["adhdev-dockview-tab",N,r&&"is-active",R&&"is-group-active",y&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:D,draggable:!0,onDragStart:k,onDragEnd:E,onDragOver:P,onDrop:B,onClick:L,onContextMenu:A,onTouchStart:W,onTouchEnd:z,onTouchMove:z,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:w.isGenerating?e.jsx("div",{className:"tab-spinner"}):w.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):y?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.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:s.displayPrimary,children:s.displayPrimary}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:y?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"Reconnecting…"}):w.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:["Connecting",e.jsx("span",{className:"connecting-dots"})]}):e.jsxs(e.Fragment,{children:[s.displaySecondary,s.machineName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsxs("span",{className:"adhdev-dockview-tab-machine",children:["🖥 ",s.machineName]})]})]})})]}),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 cl({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:x,onDragStateReset:h,onDragTabKeyChange:p,onReceiveTab:j,onHideTab:u,isGroupActive:b,allowTabShortcuts:g=!0}){const[v,S]=a.useState(null),R=a.useRef(null),w=a.useRef(null),N=a.useMemo(()=>t.map(A=>A.tabKey),[t]);rs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(v==null?void 0:v.tabKey)||null});const{isMac:y,tabShortcuts:k,shortcutListening:E,setShortcutListening:P,saveShortcuts:B}=ha({enabled:g,sortedTabKeys:t.map(A=>A.tabKey),onFocus:o,onSelectTab:c});a.useEffect(()=>{if(!v)return;const A=W=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(W.target)||S(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[v]),a.useEffect(()=>{const A=w.current;if(!A)return;const W=z=>{Math.abs(z.deltaY)>Math.abs(z.deltaX)&&(z.preventDefault(),A.scrollLeft+=z.deltaY)};return A.addEventListener("wheel",W,{passive:!1}),()=>A.removeEventListener("wheel",W)},[]);const L=a.useCallback((A,W,z)=>{S({x:A,y:W,tabKey:z})},[]);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:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(A=>e.jsx(ol,{conv:A,isActive:s===A.tabKey,isDraggedTab:i.current===A.tabKey,isTaskCompleteUnread:n.has(A.tabKey),shortcut:g?k[A.tabKey]:void 0,conversationKeys:N,draggingTabRef:i,onFocus:o,onSelectTab:c,onConversationActivated:d,onPreviewReorder:l,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:x,onDragStateReset:h,onDragTabKeyChange:p,onReceiveTab:j,onOpenContextMenu:L,longPressTimer:R,isGroupActive:b},A.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),v&&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:v.x,top:v.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:A=>{A.stopPropagation(),P(v.tabKey),S(null)},children:["⌨ ",k[v.tabKey]?`Change shortcut (${k[v.tabKey]})`:"Set shortcut"]}),k[v.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={...k};delete A[v.tabKey],B(A),S(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[g&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(v.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),g&&E&&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:()=>P(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. ",y?"⌘+1":"Ctrl+1",", ",y?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function ll({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,userName:l,groupIndex:f,onFocus:m,isSplitMode:x,numGroups:h,onMoveTab:p,onReceiveTab:j,style:u,detectedIdes:b,handleLaunchIde:g,onActiveTabChange:v,initialActiveTabId:S,initialTabOrder:R,onTabOrderChange:w,onHideTab:N,isFocused:y,allowTabShortcuts:k=!0}){const{sendCommand:E}=jt(),P=a.useRef(null),{activeTabId:B,activeConv:L,sortedConversations:A,draggingTabRef:W,selectTab:z,handleTabReorder:D,updatePreviewOrder:U,commitPreviewOrder:T,clearPreviewOrder:M,moveTabToEnd:_,setDraggingTabKey:H}=nl({conversations:t,initialActiveTabId:S,initialTabOrder:R,onActiveTabChange:v,onTabOrderChange:w}),q=$s({sendDaemonCommand:i,activeConv:L,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),{dragOver:ce,dropAction:he,resetDragState:we,handleDragEnter:se,handleDragOver:Se,handleDragLeave:F,handleDrop:oe}=sl({conversations:t,numGroups:h,onMoveTab:p,onReceiveTab:j,onOwnTabDrop:_,onClearPreviewOrder:M}),ee=L&&!Ke(L)&&Ot(L)==="terminal",xe=a.useMemo(()=>L?s.find(ae=>ae.id===L.ideId):void 0,[s,L]),V=a.useMemo(()=>L?n.filter(ae=>ae.ideId===L.tabKey):[],[n,L]),Y=a.useMemo(()=>ns(s),[s]),re=a.useMemo(()=>new Set(A.filter(ae=>Fi(ae,Y,{isOpenConversation:ae.tabKey===B})).map(ae=>ae.tabKey)),[B,Y,A]);rs("PaneGroup",{groupIndex:f,conversationCount:t.length,activeTabId:B,dragOver:ce});const de=a.useCallback(ae=>{ae.streamSource==="agent-stream"&&ae.agentType&&E(ae.ideId,"focus_session",{agentType:ae.agentType,...ae.sessionId&&{targetSessionId:ae.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...u,outline:ce?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(cl,{conversations:A,activeTabId:B,groupIndex:f,numGroups:h,unreadTabKeys:re,draggingTabRef:W,onFocus:m,onSelectTab:z,onConversationActivated:de,onPreviewReorder:U,onReorderTab:D,onCommitPreviewOrder:T,onClearPreviewOrder:M,onDragStateReset:we,onDragTabKeyChange:H,onMoveTab:p,onReceiveTab:j,onHideTab:N,isGroupActive:y??!1,allowTabShortcuts:k}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:se,onDragOver:Se,onDragLeave:F,onDrop:oe,children:[ce&&e.jsx(al,{dropAction:he,canSplit:!!(h<4&&p)}),L?e.jsx(Nr,{activeConv:L,clearToken:r[L.tabKey]||0,isCliTerminal:!!ee,ideEntry:xe,terminalRef:P,handleModalButton:q.handleModalButton,handleRelaunch:q.handleRelaunch,handleSendChat:q.handleSendChat,isSendingChat:q.isSendingChat,handleFocusAgent:q.handleFocusAgent,isFocusingAgent:q.isFocusingAgent,actionLogs:V,userName:l,isInputActive:!x||!!y}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Ir,{conversationsCount:t.length,isSplitMode:x,isStandalone:d,detectedIdes:b,handleLaunchIde:g})})]})]})}function dl({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:i,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:f,setActionLogs:m,isStandalone:x,userName:h,focusedGroup:p,setFocusedGroup:j,moveTabToGroup:u,splitTabRelative:b,closeGroup:g,handleResizeStart:v,detectedIdes:S,handleLaunchIde:R,groupActiveTabIds:w,setGroupActiveTabIds:N,groupTabOrders:y,setGroupTabOrders:k,toggleHiddenTab:E,allowTabShortcuts:P=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:i.map((B,L)=>{const A=s&&n.length===r?`${n[L]}%`:void 0;return e.jsxs(Ve.Fragment,{children:[s&&L>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:W=>v(L-1,W),onDoubleClick:()=>g(L),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(ll,{style:s?{flexBasis:A??`${100/r}%`,flexGrow:A?0:1,flexShrink:A?0:1}:void 0,conversations:B,clearedTabs:o,ides:c,actionLogs:d,sendDaemonCommand:l,setLocalUserMessages:f,setActionLogs:m,isStandalone:x,userName:h,groupIndex:L,isFocused:s&&p===L,onFocus:()=>j(L),isSplitMode:s,numGroups:r,onMoveTab:(W,z)=>{z==="left"&&L>0?u(W,L-1):z==="right"&&L<r-1?u(W,L+1):z==="split-left"&&r<4?b(W,L,"left"):z==="split-right"&&r<4&&b(W,L,"right")},onReceiveTab:W=>u(W,L),detectedIdes:L===0?S:void 0,handleLaunchIde:L===0?R:void 0,onActiveTabChange:W=>N(z=>(z[L]??null)===(W??null)?z:{...z,[L]:W}),initialActiveTabId:w[L],initialTabOrder:y[L],onTabOrderChange:W=>k(z=>{const D=z[L]||[];return D.length===W.length&&D.every((U,T)=>U===W[T])?z:{...z,[L]:W}}),onHideTab:E,allowTabShortcuts:P})]},L)})})}function ba({doId:t,ideId:s,ideType:r,connState:n,viewMode:i,instanceId:o}){const[c,d]=a.useState(null),[l,f]=a.useState(null),m=a.useMemo(()=>{if(!s)return r;const h=s.split(":");return h.length>=3&&h[1]==="ide"?h.slice(2).join(":"):r},[s,r]);a.useEffect(()=>t?He.onScreenshot("ide-page",(p,j)=>{if(p!==t)return;const u=new FileReader;u.onload=()=>d(u.result),u.readAsDataURL(j)}):void 0,[t]),a.useEffect(()=>{n!=="connected"&&d(null)},[n]),a.useEffect(()=>{var p;return t?((p=He.onStatus)==null?void 0:p.call(He,(j,u)=>{j===t&&u!=null&&u.screenshotUsage&&f(u.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{d(null)},[t,s,m]),a.useEffect(()=>{const h=t?He.get(t):null;if(!(!h||n!=="connected"))return i!=="chat"&&m?h.startScreenshots(m):h.stopScreenshots(m),()=>{h.stopScreenshots(m)}},[i,n,m,t]);const x=a.useCallback(async(h,p)=>{const j=t?He.get(t):null;return!j||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):j.sendInput(h,p,o||m)},[t,n,o,m]);return{connScreenshot:c,screenshotUsage:l,handleRemoteAction:x}}const ga=a.createContext(null);function Ks(){const t=a.useContext(ga);if(!t)throw new Error("DashboardDockviewContext missing");return t}function ks(t){return t.displayPrimary||t.title||t.agentName||t.tabKey}function ul(t){return`remote:${t}`}function ts(t){return t.startsWith("remote:")}function ss(t,s){return t.find(r=>r.ideId===s&&r.streamSource==="native")??t.find(r=>r.ideId===s)??null}function pl(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 ml(t,s,r){var d;const n=[s];let i;for(const l of n){let f;for(const m of l){const x=t.addPanel({id:m.tabKey,component:"conversation",title:ks(m),params:{kind:"conversation",tabKey:m.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:i?{position:{referencePanel:i,direction:"right"},inactive:!0}:{}});f||(f=x.id)}i=f??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 xn(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])ts(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!==ks(n)&&i.api.setTitle(ks(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:ks(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 hn(t,s,r){var l,f;const n=r?ul(r):null;for(const m of[...t.panels])ts(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const i=ss(s,r);if(!i&&t.totalPanels===0)return;const o=t.getPanel(n),c=i?`Remote · ${i.displayPrimary||i.workspaceName||i.agentName}`:"Remote";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)??((f=t.panels.find(m=>!ts(m.id)))==null?void 0:f.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",ideId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function fl({params:t,api:s}){var x;const r=Ks(),n=a.useRef(null),[i,o]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=$s({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{o(s.isActive);const h=[s.onDidActiveChange(p=>o(p.isActive)),s.onDidActiveGroupChange(p=>{if(!s.isActive&&!p.isActive){o(!1);return}o(s.isActive)})];return()=>{for(const p of h)p.dispose()}},[s]);const l=a.useMemo(()=>c?r.ides.find(h=>h.id===c.ideId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(h=>h.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(Ir,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!Ke(c)&&Ot(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Nr,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:l,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:i})})}function xl({params:t}){var l;const s=Ks(),r=a.useMemo(()=>ss([...s.conversationsByTabKey.values()],t.ideId),[s.conversationsByTabKey,t.ideId]),n=a.useMemo(()=>s.ides.find(f=>f.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}=ba({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(Bn,{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 hl(){const t=Ks();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Ir,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function bl(t){var p,j;pl(t);const s=Ks(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=ss([...s.conversationsByTabKey.values()],t.params.ideId),b=((p=t.api.group.activePanel)==null?void 0:p.id)===t.api.id,g=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${g?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const i=((j=t.api.group.activePanel)==null?void 0:j.id)===t.api.id,o=t.api.isGroupActive,c=Zt(n,s.liveSessionInboxState,{isOpenConversation:i}),d=c.isReconnecting,l=c.isConnecting,f=c.isGenerating,m=c.isWaiting,x=c.unread,h=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${i?" is-active":""}${o?" is-group-active":""}${d?" is-reconnecting":""}`,title:n.displayPrimary,"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey})},children:[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:f?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):l?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:n.displayPrimary}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"Reconnecting…"}):l?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:"Connecting…"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:n.displaySecondary}),n.machineName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsxs("span",{className:"adhdev-dockview-tab-machine",children:["🖥 ",n.machineName]})]})]})})]}),h&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:h,children:h})]})}function gl({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,initialDataLoaded:l,userName:f,detectedIdes:m,handleLaunchIde:x,toggleHiddenTab:h,registerActionHandlers:p,onActiveTabChange:j,requestedActiveTabKey:u,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:g,scrollToBottomRequest:v}){const{theme:S}=ta(),{sendCommand:R}=jt(),w=a.useRef(null),N=a.useRef(null),y=a.useRef(!1),k=a.useRef(!1),E=a.useRef(!1),P=a.useRef(null),[B,L]=a.useState(null),[A,W]=a.useState(!1),[z,D]=a.useState(!1),U=a.useRef(null),T=a.useMemo(()=>da(typeof window<"u"?window.innerWidth:1280),[]),M=a.useMemo(()=>new Map(t.map($=>[$.tabKey,$])),[t]),_=a.useMemo(()=>ns(r),[r]),H=a.useCallback(()=>{var $;($=w.current)==null||$.focus()},[]),q=a.useCallback($=>{const G=w.current;if(!G)return;const Z=G.getPanel($);Z&&(Z.group.model.openPanel(Z),Z.api.setActive())},[]),ce=a.useCallback($=>{const G=w.current,Z=G==null?void 0:G.activePanel,ge=(G==null?void 0:G.activeGroup)||(Z==null?void 0:Z.group);if(!G||!Z||!ge)return;const ye=ge.panels||[];if(ye.length<=1)return;const Ee=ye.findIndex(De=>De.id===Z.id);if(Ee<0)return;const $e=(Ee+$+ye.length)%ye.length,Re=ye[$e];Re&&(Re.group.model.openPanel(Re),Re.api.setActive())},[]),he=a.useCallback($=>{var Re;const G=w.current,Z=(G==null?void 0:G.activeGroup)||((Re=G==null?void 0:G.activePanel)==null?void 0:Re.group);if(!G||!Z)return;const ge=G.groups||[],ye=ge.findIndex(De=>De.id===Z.id);if(ye<0)return;const Ee=ge[ye+$];if(!Ee)return;const $e=Ee.activePanel||Ee.panels[0];$e&&(Ee.model.openPanel($e),$e.api.setActive())},[]),we=a.useCallback(($,G)=>{const Z=w.current,ge=Z==null?void 0:Z.activePanel,ye=(Z==null?void 0:Z.activeGroup)||(ge==null?void 0:ge.group);if(!Z||!ge||!ye)return;const Ee=Z.groups||[],$e=Ee.findIndex(De=>De.id===ye.id);if($e<0)return;let Re=Ee[$e+$];!Re&&(G!=null&&G.createGroupIfMissing)&&(Re=Z.addGroup({referenceGroup:ye,direction:$<0?"left":"right"})),Re&&(ge.api.moveTo({group:Re,position:"center"}),ge.group.model.openPanel(ge),ge.api.setActive())},[]),{isMac:se,tabShortcuts:Se,shortcutListening:F,setShortcutListening:oe,saveShortcuts:ee}=ha({sortedTabKeys:t.map($=>$.tabKey),onFocus:H,onSelectTab:q}),xe=a.useCallback(()=>{var Z;const $=w.current;if(!$)return;const G=$.activePanel;if(G){if(ts(G.id)){const ge=((Z=G.params)==null?void 0:Z.ideId)||G.id.slice(7),ye=ss(t,ge);ye!=null&&ye.tabKey&&oe(ye.tabKey);return}M.has(G.id)&&oe(G.id)}},[M,oe,t]);a.useEffect(()=>(p==null||p({setShortcutForActiveTab:xe,activatePreviousTabInGroup:()=>ce(-1),activateNextTabInGroup:()=>ce(1),splitActiveTabRight:()=>we(1,{createGroupIfMissing:!0}),focusLeftPane:()=>he(-1),focusRightPane:()=>he(1),moveActiveTabToLeftPane:()=>we(-1),moveActiveTabToRightPane:()=>we(1)}),()=>p==null?void 0:p(null)),[ce,he,we,p,xe]),a.useEffect(()=>{if(!B)return;const $=G=>{const Z=document.querySelector("[data-dockview-tab-context-menu]");Z&&Z.contains(G.target)||L(null)};return window.addEventListener("mousedown",$,!0),()=>window.removeEventListener("mousedown",$,!0)},[B]);const V=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:M,detectedIdes:m,handleLaunchIde:x,ides:r,isStandalone:d,liveSessionInboxState:_,sendDaemonCommand:i,setActionLogs:c,setLocalUserMessages:o,toggleHiddenTab:h,userName:f,scrollToBottomRequest:v,tabShortcuts:Se,openTabContextMenu:({x:$,y:G,tabKey:Z})=>L({x:$,y:G,tabKey:Z})}),[n,s,M,m,x,r,d,_,i,c,o,h,f,v,Se]),Y=a.useCallback($=>{if(!$)return!1;const G=w.current;if(!G)return!1;const Z=G.getPanel($);return Z?(Z.group.model.openPanel(Z),Z.api.setActive(),g==null||g(),!0):!1},[g]),re=a.useCallback(()=>{if(E.current)return!1;const $=Y(P.current);return $&&(E.current=!0),$},[Y]),de=a.useCallback(()=>{var G;const $=w.current;$&&Rc(T,{activeTabId:((G=$.activePanel)==null?void 0:G.id)??null,layout:$.toJSON()})},[T]),ae=a.useCallback(()=>{const $=N.current;if(!$)return;const G=$.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 $=N.current;if(!$)return;const G=$.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const Z of G)Z.removeAttribute("data-adhdev-force-hidden")},[]),ue=a.useCallback(()=>{const $=N.current;if(!$)return;const G=$.querySelectorAll(".dv-drop-target-container");for(const ye of G)ye.remove();const Z=$.querySelectorAll(".dv-drop-target-dropzone");for(const ye of Z)ye.remove();const ge=$.querySelectorAll(".dv-drop-target");for(const ye of ge)ye.classList.remove("dv-drop-target")},[]),C=a.useCallback(()=>{W(!1),D(!1),Q(),ae(),ue(),!(typeof window>"u")&&(U.current!=null&&window.clearTimeout(U.current),window.requestAnimationFrame(()=>{ae(),ue()}),U.current=window.setTimeout(()=>{ae(),ue(),U.current=null},80))},[Q,ae,ue]),ne=a.useCallback($=>{var Z;w.current=$.api;const G=Lc(T);P.current=(G==null?void 0:G.activeTabId)??null,G!=null&&G.layout&&$.api.fromJSON(G.layout,{reuseExistingPanels:!1}),k.current=!!(G!=null&&G.layout)&&!l&&t.length===0,k.current||(xn($.api,t),hn($.api,t,b)),$.api.totalPanels===0&&t.length>0?ml($.api,t,u):!k.current&&!Y(u)&&re(),y.current=!0,$.api.onDidActivePanelChange(ge=>{var Ee;if(P.current=(ge==null?void 0:ge.id)??null,E.current=!0,ge&&ts(ge.id)){const $e=((Ee=ge.params)==null?void 0:Ee.ideId)||ge.id.slice(7),Re=ss(t,$e);j((Re==null?void 0:Re.tabKey)??null),de();return}if(j((ge==null?void 0:ge.id)??null),de(),!ge)return;const ye=M.get(ge.id);(ye==null?void 0:ye.streamSource)==="agent-stream"&&ye.agentType&&R(ye.ideId,"focus_session",{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.sessionId}}).catch(()=>{})}),$.api.onDidLayoutChange(()=>{de()}),$.api.onWillDragPanel(()=>{W(!0),D(!1),ae()}),$.api.onWillDragGroup(()=>{W(!0),D(!1),ae()}),$.api.onWillShowOverlay(()=>{Q(),D(!0)}),$.api.onDidMovePanel(C),$.api.onDidDrop(C),j(((Z=$.api.activePanel)==null?void 0:Z.id)??null)},[Y,C,Q,M,l,T,ae,ue,j,de,u,b,R,t]);a.useEffect(()=>{const $=w.current;if(!$||!y.current||k.current&&!l||(k.current&&(k.current=!1),xn($,t),hn($,t,b),u&&Y(u)))return;!$.activePanel&&$.panels[0]&&($.panels[0].group.model.openPanel($.panels[0]),$.panels[0].api.setActive()),!!($.activePanel&&$.getPanel($.activePanel.id))||re()},[Y,re,l,u,b,t]),a.useEffect(()=>{y.current&&Y(u)},[Y,u]),a.useEffect(()=>{if(!A||typeof window>"u")return;const $=()=>C();return window.addEventListener("pointerup",$),window.addEventListener("mouseup",$),window.addEventListener("dragend",$),()=>{window.removeEventListener("pointerup",$),window.removeEventListener("mouseup",$),window.removeEventListener("dragend",$)}},[C,A]),a.useEffect(()=>()=>{typeof window>"u"||U.current!=null&&window.clearTimeout(U.current)},[]),a.useEffect(()=>{const $=G=>{const Z=G.target;if(!Z)return;const ge=Z.querySelector("[data-tab-key]")||Z.closest("[data-tab-key]");if(ge){const ye=ge.getAttribute("data-tab-key");ye&&G.dataTransfer&&G.dataTransfer.setData("text/tab-key",ye)}};return window.addEventListener("dragstart",$),()=>window.removeEventListener("dragstart",$)},[]);const te=S==="light"?ei:ti;return e.jsxs(ga.Provider,{value:V,children:[e.jsx("div",{ref:N,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Qa,{className:`h-full min-h-0 min-w-0 adhdev-dockview${A?" is-dragging-dockview":""}${z?" is-showing-dockview-overlay":""}`,components:{conversation:fl,remote:xl},defaultTabComponent:bl,watermarkComponent:hl,onReady:ne,singleTabMode:"default",tabAnimation:"smooth",theme:te})}),B&&e.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:B.x,top:B.y},children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors",onClick:$=>{$.stopPropagation(),oe(B.tabKey),L(null)},children:["⌨ ",Se[B.tabKey]?`Change shortcut (${Se[B.tabKey]})`:"Set shortcut"]}),Se[B.tabKey]&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{const $={...Se};delete $[B.tabKey],ee($),L(null)},children:"✕ Remove shortcut"})]}),F&&e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>oe(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:$=>$.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",se?"⌘+1":"Ctrl+1",", ",se?"⌥+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 Js(t){var n;if(!t)return null;const s=(((n=t.detectedIdes)==null?void 0:n.length)||0)>0,r=t.availableProviders||[];return s?"ide":r.some(i=>i.category==="cli")?"cli":r.some(i=>i.category==="acp")?"acp":null}function yl({machines:t,onClose:s,onBrowseDirectory:r,onSaveWorkspace:n,onLaunchIde:i,onLaunchProvider:o}){var ee,xe;const c=a.useMemo(()=>[...t].sort(br),[t]),[d,l]=a.useState(((ee=c[0])==null?void 0:ee.id)||""),f=a.useMemo(()=>c.find(V=>V.id===d)||c[0],[d,c]),m=a.useMemo(()=>(f==null?void 0:f.workspaces)||[],[f]),x=(f==null?void 0:f.defaultWorkspaceId)||null,[h,p]=a.useState(""),[j,u]=a.useState(""),[b,g]=a.useState(Js(c[0])),[v,S]=a.useState(""),[R,w]=a.useState(!1),[N,y]=a.useState(""),[k,E]=a.useState(!1),[P,B]=a.useState(""),[L,A]=a.useState([]),[W,z]=a.useState(!1),[D,U]=a.useState(""),[T,M]=a.useState(!1),_=a.useRef(null);a.useEffect(()=>{var V;!d&&((V=c[0])!=null&&V.id)&&l(c[0].id)},[d,c]);const H=a.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(V=>V.category==="cli"),[f]),q=a.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(V=>V.category==="acp"),[f]),ce=a.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(V=>({id:V.type,label:V.name||V.type,meta:V.running?"Detected locally":"Available to open"})),[f]),he=a.useMemo(()=>b==="cli"?H.map(V=>({id:V.type,label:V.displayName||V.type,meta:"CLI provider"})):b==="acp"?q.map(V=>({id:V.type,label:V.displayName||V.type,meta:"ACP provider"})):ce,[q,b,H,ce]);a.useEffect(()=>{var Y;if(!f)return;if(_.current!==f.id){_.current=f.id,p(x||((Y=m[0])==null?void 0:Y.id)||"__home__"),u(""),g(Js(f)),S(""),y("");return}p(re=>{var de;return re==="__custom__"||re==="__home__"||m.some(ae=>ae.id===re)?re:x||((de=m[0])==null?void 0:de.id)||"__home__"}),g(re=>re==="ide"&&ce.length>0||re==="cli"&&H.length>0||re==="acp"&&q.length>0?re:Js(f))},[q.length,H.length,x,ce.length,f,m]),a.useEffect(()=>{var V;b&&(he.some(Y=>Y.id===v)||S(((V=he[0])==null?void 0:V.id)||""))},[b,he,v]);const we=h==="__custom__"?j.trim():h==="__home__"?"":((xe=m.find(V=>V.id===h))==null?void 0:xe.path)||"",se=a.useCallback(()=>{var Y,re;if(!f)return;p("__custom__"),E(!0),U("");const V=Ds(f.platform,[j.trim(),we,(Y=m.find(de=>de.id===x))==null?void 0:Y.path,(re=m[0])==null?void 0:re.path]);z(!0),r(f.id,V).then(de=>{B(de.path),u(de.path),A(de.directories)}).catch(de=>{U(de instanceof Error?de.message:"Could not load folder")}).finally(()=>z(!1))},[j,x,r,we,f,m]),Se=a.useCallback(V=>{f&&(z(!0),U(""),r(f.id,V).then(Y=>{B(Y.path),u(Y.path),A(Y.directories)}).catch(Y=>{U(Y instanceof Error?Y.message:"Could not load folder")}).finally(()=>z(!1)))},[r,f]),F=a.useCallback(async()=>{if(!f||!we)return;M(!0),y("");const V=await n(f.id,we);if(M(!1),!V.ok){y(V.error||"Could not save workspace");return}y("Workspace saved. It will appear in the list once the machine state refreshes.")},[n,we,f]),oe=a.useCallback(async()=>{if(!f||!b||!v)return;w(!0),y("");const V=b==="ide"?await i(f.id,v,{workspacePath:we||null}):await o(f.id,b,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&we||null});if(w(!1),!V.ok){y(V.error||"Could not start session");return}s()},[b,s,i,o,we,f,v,h]);return f?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:s,"aria-label":"Close new session dialog",children:e.jsx(At,{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:f.id,onChange:V=>l(V.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:R,children:c.map(V=>e.jsx("option",{value:V.id,children:ct(V,{fallbackId:V.id})},V.id))})]}),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:se,disabled:R,children:"Browse…"})]}),e.jsxs("select",{value:h,onChange:V=>{const Y=V.target.value;p(Y),Y==="__custom__"?se():y("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:R,children:[e.jsx("option",{value:"__home__",children:"Home directory"}),m.map(V=>e.jsxs("option",{value:V.id,children:[V.id===x?"⭐ ":"",Es(V.path,V.label)||V.path]},V.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":we||"Select a workspace folder."}),h==="__custom__"&&we&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:se,disabled:R,children:[e.jsx(Wt,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:F,disabled:R||T,children:T?"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:"ide",label:"IDE",enabled:ce.length>0},{id:"cli",label:"CLI",enabled:H.length>0},{id:"acp",label:"ACP",enabled:q.length>0}].map(V=>e.jsx("button",{type:"button",className:`btn btn-sm ${b===V.id?"btn-primary":"btn-secondary"}`,onClick:()=>g(V.id),disabled:!V.enabled||R,children:V.label},V.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:b==="ide"?"Choose IDE":b==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[he.map(V=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===V.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>S(V.id),disabled:R,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:V.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:V.meta})]},V.id)),he.length===0&&e.jsx("div",{className:"text-sm text-text-muted",children:"Nothing available for this category on the selected machine."})]})]}),N&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${N.includes("saved")||N.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:N})]}),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:s,disabled:R,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:oe,disabled:R||!b||!v||h==="__custom__"&&!we,children:[e.jsx(hr,{size:14}),R?"Starting…":"Start session"]})]})]})}),k&&e.jsx(Bs,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:P,directories:L,busy:W,error:D,onClose:()=>E(!1),onNavigate:Se,onConfirm:V=>{u(V),B(V),p("__custom__"),E(!1)}})]}):null}const ya="adhdev-dashboard-action-shortcuts",vl=1200,wl={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function jl(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Ze(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"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"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 va(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Ze("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Ze("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Ze("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Ze("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Ze("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:Ze("splitActiveTabRight",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Ze("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Ze("focusRightPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Ze("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Ze("moveActiveTabToRightPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Ze("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Ze("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Ze("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Ze("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Ze("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Ze("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Ze("toggleCliView",t)}]}function kl(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function bn(t){const s=Object.fromEntries(va(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ya)||"{}"),n={...s,...r};for(const[i,o]of Object.entries(wl))n[i]===o&&(n[i]=s[i]);return n}catch{return s}}function Nl(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Sl({enabled:t=!0,onTrigger:s}){const r=jl(),[n,i]=a.useState(()=>bn(r)),[o,c]=a.useState(null),[d,l]=a.useState([]),f=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const b=[];return u.metaKey&&b.push(r?"⌘":"Meta"),u.ctrlKey&&b.push("Ctrl"),u.altKey&&b.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(b.push(Nl(u.key)),b.join("+"))},[r]),x=a.useCallback(u=>{i(u);try{localStorage.setItem(ya,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=bn(r),b=Object.entries(n),g=Object.entries(u);b.length===g.length&&b.every(([v,S])=>u[v]===S)||x(u)},[n,r,x]);const h=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),p=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},vl))},[]);a.useEffect(()=>{if(!o)return;const u=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),l([]);return}const g=m(b);if(!g)return;const S=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(g);if(d.length===0&&S){l([g]);return}const w=[...d,g].slice(0,2).join(" "),N={...n};for(const[y,k]of Object.entries(N))k===w&&delete N[y];N[o]=w,x(N),c(null),l([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,x,o,d]),a.useEffect(()=>{if(!t||o)return;const u=b=>{if(b.defaultPrevented)return;const g=m(b);if(!g)return;const v=b.metaKey||b.ctrlKey||b.altKey;if(kl(b.target)&&!v)return;const S=f.current.parts,R=v?[g]:[...S.slice(-1),g].slice(-2),w=R.join(" "),N=R[R.length-1],y=Object.entries(n).filter(([,L])=>!!L),k=y.find(([,L])=>L===w);if(k){b.preventDefault(),h(),s(k[0]);return}if(y.some(([,L])=>L.startsWith(`${w} `))){b.preventDefault(),f.current.parts=R,p();return}const P=y.find(([,L])=>L===N);if(P){b.preventDefault(),h(),s(P[0]);return}if(y.some(([,L])=>L.startsWith(`${N} `))){b.preventDefault(),f.current.parts=[N],p();return}h()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,p,t,m,s,h,o]),a.useEffect(()=>()=>h(),[h]);const j=a.useMemo(()=>va(r),[r]);return{isMac:r,actionDefinitions:j,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:l,saveShortcuts:x}}function Cl(t){switch(t.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"focusLeftPane":case"focusRightPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":return"panes";default:return"workspace"}}function Il({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:i,isConnected:o,onOpenHistory:c,onOpenRemote:d,onStopCli:l,activeCliViewMode:f,onSetActiveCliViewMode:m,mobileChatConversations:x,hiddenConversations:h,ides:p,actionLogs:j,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:g,isStandalone:v,initialDataLoaded:S,userName:R,requestedMobileTabKey:w,onRequestedMobileTabConsumed:N,requestedMachineId:y,onRequestedMachineConsumed:k,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,containerRef:B,isSplitMode:L,numGroups:A,groupSizes:W,groupedConvs:z,clearedTabs:D,focusedGroup:U,setFocusedGroup:T,moveTabToGroup:M,splitTabRelative:_,closeGroup:H,handleResizeStart:q,detectedIdes:ce,handleLaunchIde:he,groupActiveTabIds:we,setGroupActiveTabIds:se,groupTabOrders:Se,setGroupTabOrders:F,toggleHiddenTab:oe,visibleConversations:ee,requestedDesktopTabKey:xe,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:Y,onHideConversation:re,onShowHiddenConversation:de,onShowAllHiddenConversations:ae,scrollToBottomRequest:Q,machineEntries:ue,onBrowseMachineDirectory:C,onSaveMachineWorkspace:ne,onLaunchMachineIde:te,onLaunchMachineProvider:$}){const G=Ve.useRef(null),[Z,ge]=Ve.useState(!1),[ye,Ee]=Ve.useState(!1),[$e,Re]=Ve.useState(!1),[De,Ye]=Ve.useState(!1),[nt,Qe]=Ve.useState(!1),[pe,_e]=Ve.useState("quickstart"),[Ce,Ne]=Ve.useState("workspace"),O=!t&&!s,K=Ve.useCallback(be=>{ge(be),be&&Ee(!1)},[]),le=Ve.useCallback(be=>{Ee(be),be&&ge(!1)},[]),me=Ve.useCallback(()=>{_e(ee.length===0?"quickstart":"shortcuts"),Ne("workspace"),Re(!0),ge(!1),Ee(!1)},[ee.length]),I=Ve.useCallback(async be=>{var xt;if(!r)return;const Be=(xt=r.modalButtons)==null?void 0:xt[be];if(!Be)return;const ft=es(r);if(!ft)return;const kt=Be.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Pt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(kt);try{await u(ft,"resolve_action",{button:Be,action:Pt?"approve":"reject",buttonIndex:be,...Kt(r)})}catch(Lt){console.error("[Shortcut approval] Failed:",Lt)}},[r,u]),{isMac:J,actionDefinitions:ie,actionShortcuts:X,shortcutListening:Ie,shortcutListeningDraft:ve,setShortcutListening:Me,setShortcutListeningDraft:Ge,saveShortcuts:Fe}=Sl({enabled:O&&!$e,onTrigger:be=>{var Be,ft,kt,Pt,xt,Lt,is,Oe;if(be==="openShortcutHelp"){me();return}if(be==="hideCurrentTab"){r&&re(r);return}if(be==="toggleHiddenTabs"){le(!ye);return}if(be==="openHistoryForActiveTab"){r&&!Ke(r)&&c(r);return}if(be==="openRemoteForActiveTab"){r&&!Ue(r)&&!Ke(r)&&d(r);return}if(be==="splitActiveTabRight"){(Be=G.current)==null||Be.splitActiveTabRight();return}if(be==="focusLeftPane"){(ft=G.current)==null||ft.focusLeftPane();return}if(be==="focusRightPane"){(kt=G.current)==null||kt.focusRightPane();return}if(be==="moveActiveTabToLeftPane"){(Pt=G.current)==null||Pt.moveActiveTabToLeftPane();return}if(be==="moveActiveTabToRightPane"){(xt=G.current)==null||xt.moveActiveTabToRightPane();return}if(be==="triggerPrimaryApprovalAction"){I(0);return}if(be==="triggerSecondaryApprovalAction"){I(1);return}if(be==="triggerTertiaryApprovalAction"){I(2);return}if(be==="setActiveTabShortcut"){(Lt=G.current)==null||Lt.setShortcutForActiveTab();return}if(be==="selectPreviousGroupTab"){(is=G.current)==null||is.activatePreviousTabInGroup();return}if(be==="selectNextGroupTab"){(Oe=G.current)==null||Oe.activateNextTabInGroup();return}!r||!Ue(r)||Ke(r)||be==="toggleCliView"&&m(f==="chat"?"terminal":"chat")}}),We=Ve.useCallback(()=>{Re(!1),Me(null),Ge([])},[Me,Ge]),lt=Ve.useMemo(()=>Ce==="all"?ie:ie.filter(be=>Cl(be)===Ce),[ie,Ce]),Pe=Ve.useCallback(()=>{const be=Object.fromEntries(ie.map(Be=>[Be.id,""]));Fe(be)},[ie,Fe]),as=Ve.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const be=Object.fromEntries(ie.map(Be=>[Be.id,Be.defaultShortcut]));Fe(be)},[ie,Fe]);return Ve.useEffect(()=>{const be=Be=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Be.metaKey&&Be.key.toLowerCase()==="w":Be.ctrlKey&&Be.key.toLowerCase()==="w")&&(Be.preventDefault(),r&&re&&re(r))};return window.addEventListener("keydown",be),()=>window.removeEventListener("keydown",be)},[r,re]),Ve.useEffect(()=>{if(!$e||Ie)return;const be=Be=>{Be.key==="Escape"&&(Be.preventDefault(),We())};return window.addEventListener("keydown",be,!0),()=>window.removeEventListener("keydown",be,!0)},[We,$e,Ie]),Ve.useEffect(()=>{if(!O||ee.length>0){Qe(!1);return}Qe(!0);const be=window.setTimeout(()=>{Qe(!1)},1e4);return()=>window.clearTimeout(be)},[O,ee.length]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(yo,{activeConv:r,agentCount:n.length,wsStatus:i,isConnected:o,conversations:ee,hiddenConversations:h,onOpenHistory:c,onOpenConversation:de,onHideConversation:re,onShowConversation:de,onShowAllHidden:ae,inboxOpen:Z,onInboxOpenChange:K,hiddenOpen:ye,onHiddenOpenChange:le,onOpenNewSession:s?void 0:()=>Ye(!0),onOpenRemote:()=>{!r||Ue(r)||Ke(r)||d(r)},onStopCli:l,activeCliViewMode:f,onSetCliViewMode:m}),t?e.jsx(tl,{conversations:x,hiddenConversations:h,ides:p,actionLogs:j,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:g,isStandalone:v,userName:R,requestedActiveTabKey:w,onRequestedActiveTabConsumed:N,requestedMachineId:y,onRequestedMachineConsumed:k,requestedMobileSection:E,onRequestedMobileSectionConsumed:P,onOpenHistory:c,onOpenRemote:d,onStopCli:l,wsStatus:i,isConnected:o,onShowHiddenConversation:de,onShowAllHiddenConversations:ae}):s?e.jsx(dl,{containerRef:B,isSplitMode:L,numGroups:A,groupSizes:W,groupedConvs:z,clearedTabs:D,ides:p,actionLogs:j,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:g,isStandalone:v,userName:R,focusedGroup:U,setFocusedGroup:T,moveTabToGroup:M,splitTabRelative:_,closeGroup:H,handleResizeStart:q,detectedIdes:ce,handleLaunchIde:he,groupActiveTabIds:we,setGroupActiveTabIds:se,groupTabOrders:Se,setGroupTabOrders:F,toggleHiddenTab:oe,allowTabShortcuts:!1}):e.jsx(gl,{visibleConversations:ee,clearedTabs:D,ides:p,actionLogs:j,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:g,isStandalone:v,initialDataLoaded:S,userName:R,detectedIdes:ce,handleLaunchIde:he,toggleHiddenTab:oe,registerActionHandlers:be=>{G.current=be},onActiveTabChange:Y,requestedActiveTabKey:xe,onRequestedActiveTabConsumed:V,scrollToBottomRequest:Q}),De&&e.jsx(yl,{machines:ue,onClose:()=>Ye(!1),onBrowseDirectory:C,onSaveWorkspace:ne,onLaunchIde:te,onLaunchProvider:$}),$e&&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:We,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:be=>be.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:We,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(be=>e.jsx("button",{type:"button",className:`btn btn-sm ${pe===be.id?"btn-primary":"btn-secondary"}`,onClick:()=>_e(be.id),children:be.label},be.id))}),pe==="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 ",J?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),pe==="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."]})]})]})]}),pe==="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(be=>e.jsx("button",{type:"button",className:`btn btn-sm ${Ce===be.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ne(be.id),children:be.label},be.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pe,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:as,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:lt.map(be=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ie===be.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:be.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:be.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:be.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:Ie===be.id?ve.length>0?`${ve.join(" ")} ...`:"Listening...":X[be.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Me(be.id),Ge([])},children:Ie===be.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Be={...X};Be[be.id]="",Fe(Be)},children:"Disable"})]})]})},be.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",J?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&nt&&e.jsxs("button",{type:"button",onClick:me,className:"fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center gap-2 rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur px-2.5 py-2 text-xs text-text-secondary hover:text-text-primary transition-colors",style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),e.jsx("span",{children:"Guide"})]})]})}const Zs=[{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 Tl({onClose:t}){const[s,r]=a.useState(0),n=Zs[s],i=s===Zs.length-1;return e.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.target===o.currentTarget&&t()},children:[e.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[e.jsx("button",{onClick:t,style:{position:"absolute",top:12,right:16,background:"transparent",border:"none",color:"var(--text-muted)",fontSize:"1.2rem",cursor:"pointer"},children:"✕"}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Zs.map((o,c)=>e.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),e.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),e.jsxs("div",{style:{textAlign:"center"},children:[e.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[e.jsx("span",{children:n.icon})," ",n.title]}),e.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&e.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[e.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),i&&e.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"1.5rem"},children:[e.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:"var(--text-muted)",fontSize:"0.85rem",cursor:"pointer"},children:"Skip"}),e.jsx("button",{onClick:()=>i?t():r(o=>o+1),className:"transition-opacity hover:opacity-90",style:{background:"linear-gradient(135deg, #7c3aed, #6366f1)",color:"#fff",border:"none",borderRadius:"0.5rem",padding:"0.55rem 1.5rem",fontSize:"0.9rem",fontWeight:600,cursor:"pointer"},children:i?"Get Started →":"Next →"})]})]}),e.jsx("style",{children:`
48
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
49
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
50
+ `})]})}function _l({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 Al({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:i,preferredTabKey:o}){const[c,d]=a.useState(()=>o||"native"),l=a.useMemo(()=>qn(s),[s]),f=a.useMemo(()=>{var b;if(!t)return[];const u=t.daemonId||((b=t.id)==null?void 0:b.split(":")[0])||t.id;return Yn(t,n,{machineName:t.daemonId&&l[t.daemonId]||void 0,connectionState:r[u]||"new"})},[t,n,l,r]),m=a.useMemo(()=>f.find(u=>u.streamSource==="native"),[f]),x=a.useMemo(()=>f.filter(u=>u.streamSource==="agent-stream"),[f]);a.useEffect(()=>{o&&d(o)},[o]),a.useEffect(()=>{var u;c!=="native"&&(x.some(b=>b.tabKey===c)||d(((u=x[0])==null?void 0:u.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(m||x[0]&&d(x[0].tabKey))},[c,m,x]);const h=a.useMemo(()=>c==="native"&&m?m:x.find(u=>u.tabKey===c)||m||x[0],[c,m,x]),p=a.useMemo(()=>x.map(u=>({tabKey:u.tabKey,title:u.title||u.agentName||i,status:u.status})),[x,i]),j=a.useCallback(u=>{if(u)return f.find(b=>b.sessionId===u||b.ideId===u||b.tabKey===u||b.ideType===u||b.agentType===u)},[f]);return{activeChatTab:c,setActiveChatTab:d,activeConv:h,conversations:f,extensionTabs:p,hasExtensions:p.length>0,resolveConversationByTarget:j}}function Ml({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:i,localUserMessages:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:f,userName:m,onOpenHistory:x,onConversationChange:h,onClose:p}){var z;const[j,u]=a.useState("split"),[b,g]=a.useState(()=>t.streamSource==="native"?"native":t.tabKey),v=a.useMemo(()=>s||r.find(D=>D.id===t.ideId),[t.ideId,s,r]),S=a.useMemo(()=>ze((v==null?void 0:v.type)||""),[v==null?void 0:v.type]),{conversations:R,extensionTabs:w,hasExtensions:N}=Al({ideData:v,allIdes:r,connectionStates:n,localUserMessages:o,ideName:S||"IDE",preferredTabKey:t.streamSource==="native"?"native":t.tabKey});a.useEffect(()=>{g(t.streamSource==="native"?"native":t.tabKey)},[t.streamSource,t.tabKey]);const y=a.useMemo(()=>b==="native"?R.find(D=>D.streamSource==="native")||t:R.find(D=>D.tabKey===b)||t,[t,R,b]),k=y.daemonId||((z=y.ideId)==null?void 0:z.split(":")[0])||y.ideId,E=$s({sendDaemonCommand:c,activeConv:y,setLocalUserMessages:d,setActionLogs:l,isStandalone:f}),{connScreenshot:P,screenshotUsage:B,handleRemoteAction:L}=ba({doId:k,ideId:y.ideId,ideType:y.ideType,connState:y.connectionState||"new",viewMode:j,instanceId:v==null?void 0:v.instanceId}),A=a.useMemo(()=>i.filter(D=>D.ideId===y.tabKey),[i,y.tabKey]);a.useEffect(()=>{h==null||h(y)},[y,h]),a.useEffect(()=>{const D=U=>{U.key==="Escape"&&p()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p]);const W=a.useCallback(D=>{D.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:p,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:W,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(st,{size:16})}),e.jsx("span",{className:"truncate",children:y.displayPrimary||y.agentName||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,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(D=>{const U=j===D;return e.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${U?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>u(D),title:D==="split"?"Split view":"Remote only",children:D==="split"?e.jsx("span",{className:"font-bold text-lg leading-none mb-0.5",children:"⊞"}):e.jsx(st,{size:15})},D)})}),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(y),title:"Chat History",children:[e.jsx(pr,{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:p,children:"Close"})]})]}),e.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${j==="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:[j!=="remote"&&e.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${j==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[e.jsx(_l,{hasExtensions:N,ideName:S||"IDE",activeChatTab:b,extensionTabs:w,onSelectTab:g}),e.jsx(Wn,{activeConv:y,onModalButton:E.handleModalButton}),e.jsx(nr,{activeConv:y,ideEntry:v,showMetaChips:!1,handleSendChat:E.handleSendChat,isSendingChat:E.isSendingChat,handleFocusAgent:E.handleFocusAgent,isFocusingAgent:E.isFocusingAgent,actionLogs:A,userName:m})]}),e.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${j==="split"?"order-1 md:order-2":""}`,children:e.jsx(Bn,{addLog:()=>{},connState:y.connectionState||"new",connScreenshot:P,screenshotUsage:B,transportType:y.transport,onAction:L})})]})]})})}function Pl({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:i}){const o=t.agentName||t.ideType||"CLI";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?"The CLI runtime will stop. Choose whether to stop immediately or ask the provider to save and exit first.":"The CLI runtime will stop immediately. This provider does not expose save-and-stop."})]}),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:"Save and 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:"Stop now"}),e.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Ll({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:i,savedHistorySessions:o,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:l,onNewHistoryChat:f,onSwitchHistorySession:m,onRefreshHistory:x,onResumeSavedHistorySession:h,remoteDialogConv:p,remoteDialogIdeEntry:j,connectionStates:u,actionLogs:b,localUserMessages:g,sendDaemonCommand:v,setLocalUserMessages:S,setActionLogs:R,isStandalone:w,userName:N,onOpenRemoteHistory:y,onRemoteConversationChange:k,onCloseRemoteDialog:E,cliStopDialogOpen:P,cliStopTargetConv:B,onCancelCliStop:L,onStopCliNow:A,onSaveCliAndStop:W,toasts:z,onDismissToast:D,onClickToast:U,showOnboarding:T,onCloseOnboarding:M}){var _;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(wo,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:i,savedSessions:o,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:l,onNewChat:f,onSwitchSession:m,onRefreshHistory:x,onResumeSavedSession:h}),p&&e.jsx(Ml,{activeConv:p,ideEntry:j,ides:r,connectionStates:u,actionLogs:b,localUserMessages:g,sendDaemonCommand:v,setLocalUserMessages:S,setActionLogs:R,isStandalone:w,userName:N,onOpenHistory:y,onConversationChange:k,onClose:E}),P&&B&&Ue(B)&&!Ke(B)&&e.jsx(Pl,{activeConv:B,canSaveAndStop:!!((_=B.resume)!=null&&_.supported),onCancel:L,onStopNow:A,onSaveAndStop:W}),e.jsx(Gn,{toasts:z,onDismiss:D,onClickToast:U}),T&&e.jsx(Tl,{onClose:M})]})}function Rl({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(mr,{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=ct(o,{fallbackId:o.id}),d=r[o.id],l=o.version||o.daemonVersion||"unknown";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 15%, transparent)"},children:[e.jsx("span",{className:"font-medium text-text-primary",children:c}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",l]}),d==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:"var(--status-warning)"},children:"upgrading…"}):d==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>n(o.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},onClick:()=>n(o.id),children:"Upgrade"})]},o.id)})]}),e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors text-sm px-1 shrink-0",onClick:i,title:"Dismiss",children:"✕"})]})}function El(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function gn(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function $l(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Dl(){var Ar,Mr,Pr;const{sendCommand:t}=jt(),s=dr(),r=zt(),[n,i]=si(),o=n.get("activeTab"),c=((Ar=s.state)==null?void 0:Ar.openRemoteForTabKey)||null,d=((Mr=s.state)==null?void 0:Mr.openMachineId)||null,l=((Pr=s.state)==null?void 0:Pr.mobileSection)||null,f=gr(),m=f.ides||[],x=f.initialLoaded??!0,{updateIdeChats:h}=f,[p,j]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),u=f.toasts||[],b=f.setToasts||(()=>{}),g=f.wsStatus||"connected",v=f.isConnected??!0,S=f.connectionStates||{},R=f.showReconnected||!1,{groupAssignments:w,setGroupAssignments:N,focusedGroup:y,setFocusedGroup:k,groupActiveTabIds:E,setGroupActiveTabIds:P,groupTabOrders:B,setGroupTabOrders:L,groupSizes:A,setGroupSizes:W,isMobile:z,hasHydratedStoredLayout:D,hydrateStoredLayout:U}=$c(),[T,M]=a.useState(!1),[_,H]=a.useState(!1),[q,ce]=a.useState(null),[he,we]=a.useState([]),[se,Se]=a.useState(!1),[F,oe]=a.useState(null),[ee]=a.useState(()=>ia()),[xe,V]=a.useState([]),[Y,re]=a.useState({}),[de,ae]=a.useState({}),[Q,ue]=a.useState(null),[C,ne]=a.useState(null),[te,$]=a.useState(null),G=a.useRef(null);rs("Dashboard",{ideCount:m.length,toastCount:u.length,focusedGroup:y,groupCount:Object.keys(w).length,localMessageTabs:Object.keys(Y).length,actionLogCount:xe.length});const Z=m.find(fe=>fe.type==="adhdev-daemon"),ge=(Z==null?void 0:Z.detectedIdes)||[],ye=a.useMemo(()=>m.filter(fe=>fe.type==="adhdev-daemon"||fe.daemonMode).sort(br),[m]),Ee=!!Z,$e=(Z==null?void 0:Z.terminalBackend)||null,Re=Z?ct(Z,{fallbackId:Z.id}):null,De=(Z==null?void 0:Z.id)||null,{hiddenTabs:Ye,hideTab:nt,toggleTab:Qe,showTab:pe,showAllTabs:_e}=bc(),{chatIdes:Ce,conversations:Ne,visibleConversations:O,visibleTabKeys:K,resolveConversationBySessionId:le,resolveConversationByTarget:me}=Cc({ides:m,connectionStates:S,localUserMessages:Y,clearedTabs:de,hiddenTabs:Ye}),I=a.useMemo(()=>ns(m),[m]),J=a.useRef(null),{containerRef:ie,normalizedGroupAssignments:X,numGroups:Ie,isSplitMode:ve,groupedConvs:Me,moveTabToGroup:Ge,closeGroup:Fe,handleResizeStart:We,splitTabRelative:lt}=Uc({groupAssignments:w,setGroupAssignments:N,setFocusedGroup:k,setGroupActiveTabIds:P,setGroupTabOrders:L,groupSizes:A,setGroupSizes:W,isMobile:z,visibleConversations:O,visibleTabKeys:K}),Pe=a.useMemo(()=>{var je,ke;if(!z){if(Q){const Ae=Ne.find(Te=>Te.tabKey===Q);if(Ae)return Ae}return O[0]}const fe=E[y];if(fe){const Ae=Ne.find(Te=>Te.tabKey===fe);if(Ae)return Ae}return((je=Me[y])==null?void 0:je[0])||((ke=Me[0])==null?void 0:ke[0])},[Q,z,E,y,Ne,Me,O]);a.useEffect(()=>{if(z){J.current=null;return}if(!(Pe!=null&&Pe.sessionId)){J.current=null;return}const fe=`${Pe.tabKey}:${Pe.sessionId}`;if(J.current===fe)return;J.current=fe;const je=Jt(Pe,I),ke=Math.max(Date.now(),Dt(Pe),je.lastUpdated||0);t(Pe.daemonId||Pe.ideId,"mark_session_seen",{sessionId:Pe.sessionId,seenAt:ke}).catch(()=>{})},[Pe,z,I,t]);const{requestedDesktopTabKey:as,requestedMobileTabKey:be,consumeRequestedActiveTab:Be}=Ic({isMobile:z,urlActiveTab:o,resolveConversationBySessionId:le,setSearchParams:i}),{remoteDialogConv:ft,remoteDialogIdeEntry:kt,remoteDialogActiveConv:Pt,setRemoteDialogActiveConv:xt,openRemoteDialog:Lt,closeRemoteDialog:is}=Bc({isMobile:z,location:s,navigate:r,requestedRemoteTabTarget:c,requestedDesktopTabKey:as,conversations:Ne,ides:m,resolveConversationByTarget:me}),Oe=Pt||ft||Pe,dt=!!Oe&&Ue(Oe)&&!Ke(Oe),os=a.useMemo(()=>{if(!Oe||!dt)return null;const fe=Oe.daemonId||Oe.ideId||"",je=Oe.agentType||Oe.ideType||"";return`${fe}:${je}`},[Oe,dt]),wa=a.useMemo(()=>O,[O]),cs=z&&ee==="chat",ja=a.useMemo(()=>Ne.filter(fe=>Ye.has(fe.tabKey)),[Ne,Ye]),ls=a.useCallback(fe=>{const je=new URLSearchParams(n);je.set("activeTab",fe),i(je,{replace:!0})},[n,i]),ka=a.useCallback(async(fe,je)=>Sr(t,fe,je),[t]),Na=a.useCallback(async(fe,je)=>{if(!je.trim())return{ok:!1,error:"Choose a workspace path first."};try{const ke=await t(fe,"workspace_add",{path:je.trim()});return ke!=null&&ke.success?{ok:!0}:{ok:!1,error:(ke==null?void 0:ke.error)||"Could not save workspace"}}catch(ke){return{ok:!1,error:ke instanceof Error?ke.message:"Could not save workspace"}}},[t]),Sa=a.useCallback(async(fe,je,ke)=>{var Ae;try{const Te={ideType:je,enableCdp:!0};(Ae=ke==null?void 0:ke.workspacePath)!=null&&Ae.trim()&&(Te.workspace=ke.workspacePath.trim());const Xe=await t(fe,"launch_ide",Te);return!(Xe!=null&&Xe.success)&&(Xe==null?void 0:Xe.success)!==void 0?{ok:!1,error:(Xe==null?void 0:Xe.error)||"Could not launch IDE"}:($({machineId:fe,kind:"ide",providerType:je,workspacePath:(ke==null?void 0:ke.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Te){return{ok:!1,error:Te instanceof Error?Te.message:"Could not launch IDE"}}},[t]),Ca=a.useCallback(async(fe,je,ke,Ae)=>{var Xe;const Te=Date.now();try{const ut={cliType:ke};(Xe=Ae==null?void 0:Ae.workspacePath)!=null&&Xe.trim()?ut.dir=Ae.workspacePath.trim():Ae!=null&&Ae.workspaceId&&(ut.workspaceId=Ae.workspaceId);const Je=await t(fe,"launch_cli",ut),pt=(Je==null?void 0:Je.result)||Je,Ut=(pt==null?void 0:pt.sessionId)||(pt==null?void 0:pt.id);return Je!=null&&Je.success&&Ut?(ls(Ut),{ok:!0}):Je!=null&&Je.success?($({machineId:fe,kind:je,providerType:ke,workspacePath:(Ae==null?void 0:Ae.workspacePath)||null,startedAt:Te}),{ok:!0}):{ok:!1,error:(Je==null?void 0:Je.error)||(pt==null?void 0:pt.error)||`Could not launch ${je.toUpperCase()} session`}}catch(ut){return $l(ut)?($({machineId:fe,kind:je,providerType:ke,workspacePath:(Ae==null?void 0:Ae.workspacePath)||null,startedAt:Te}),{ok:!0}):{ok:!1,error:ut instanceof Error?ut.message:`Could not launch ${je.toUpperCase()} session`}}},[ls,t]);a.useEffect(()=>{var Ae;if(!te)return;const fe=gn(te.workspacePath),je=m.find(Te=>{var Ut,ds,Lr,Rr;if(!Te||Te.type==="adhdev-daemon"||Te.daemonMode||El(Te.daemonId||Te.id)!==te.machineId||(Qt(Te)?"cli":Bt(Te)?"acp":"ide")!==te.kind||String(Te.agentType||Te.ideType||Te.type||"")!==te.providerType)return!1;if(fe){const Er=gn(Te.workspace||Te.runtimeWorkspaceLabel);return Er?Er===fe:!1}return Number(Te.lastUpdated||Te._lastUpdate||Te.timestamp||((Rr=(Lr=(ds=(Ut=Te.activeChat)==null?void 0:Ut.messages)==null?void 0:ds.at)==null?void 0:Lr.call(ds,-1))==null?void 0:Rr.timestamp)||0)>=te.startedAt-5e3});if(!je)return;const ke=typeof je.sessionId=="string"&&je.sessionId?je.sessionId:typeof je.instanceId=="string"&&je.instanceId?je.instanceId:(Ae=Ne.find(Te=>Te.ideId===je.id))==null?void 0:Ae.sessionId;ke&&($(null),ls(ke))},[Ne,ls,m,te]),a.useEffect(()=>{if(!te)return;const fe=window.setTimeout(()=>{$(je=>!je||je.startedAt!==te.startedAt?je:null)},45e3);return()=>window.clearTimeout(fe)},[te]),gc({visibleConversations:O,clearedTabs:de,setClearedTabs:ae,setActionLogs:V}),Tc({ides:m,sendDaemonCommand:t,setToasts:b,setLocalUserMessages:re,resolveConversationByTarget:me});const{isRefreshingHistory:Ia,handleLaunchIde:Ta,handleRefreshHistory:_a}=an({sendDaemonCommand:t,activeConv:Pe,updateIdeChats:h,setToasts:b,setLocalUserMessages:re,setClearedTabs:ae}),{isCreatingChat:Aa,isRefreshingHistory:Ma,handleSwitchSession:Pa,handleNewChat:La,handleRefreshHistory:Ra}=an({sendDaemonCommand:t,activeConv:Oe,updateIdeChats:h,setToasts:b,setLocalUserMessages:re,setClearedTabs:ae}),Ws=a.useCallback(async()=>{if(!(!Oe||!dt||se)){Se(!0);try{const fe=Oe.daemonId||Oe.ideId,je=Oe.agentType||Oe.ideType,ke=await t(fe,"list_saved_sessions",{agentType:je,providerType:je,kind:"cli",limit:50}),Ae=(ke==null?void 0:ke.result)??ke;we(Array.isArray(Ae==null?void 0:Ae.sessions)?Ae.sessions:[])}catch(fe){console.error("Refresh saved sessions failed",fe),we([])}finally{Se(!1)}}},[Oe,se,dt,t]);a.useEffect(()=>{if(!T){G.current=null;return}if(!dt){G.current=null,we([]),Se(!1);return}!os||se||G.current!==os&&(G.current=os,Ws())},[Ws,T,se,dt,os]);const Ea=a.useCallback(async fe=>{if(!Oe||!dt||!fe.providerSessionId||!fe.workspace)return;const je=Oe.daemonId||Oe.ideId,ke=Oe.agentType||Oe.ideType;try{oe(fe.providerSessionId);const Ae=await t(je,"launch_cli",{cliType:ke,dir:fe.workspace,resumeSessionId:fe.providerSessionId,initialModel:fe.currentModel}),Te=(Ae==null?void 0:Ae.result)??Ae,Xe=typeof(Te==null?void 0:Te.sessionId)=="string"?Te.sessionId:typeof(Te==null?void 0:Te.id)=="string"?Te.id:"";Xe&&i(ut=>{const Je=new URLSearchParams(ut);return Je.set("activeTab",Xe),Je},{replace:!0}),M(!1)}catch(Ae){console.error("Resume saved session failed",Ae)}finally{oe(null)}},[Oe,dt,t,i]);Dc({urlActiveTab:z&&!cs?o:null,conversations:Ne,resolveConversationBySessionId:le,normalizedGroupAssignments:X,hasHydratedStoredLayout:z&&!cs?D:!0,hydrateStoredLayout:z&&!cs?U:()=>{},setGroupActiveTabIds:P,setFocusedGroup:k,setSearchParams:i,historyModalOpen:T,activeConv:Pe,isRefreshingHistory:Ia,ides:m,handleRefreshHistory:_a});const Os=a.useCallback(async(fe,je)=>{const ke=je||q||Pe;if(!ke||!Ue(ke)||Ke(ke))return;const Ae=ke.ideType||ke.agentType||"",Te=ke.ideId||ke.daemonId||"";try{await t(Te,"stop_cli",{cliType:Ae,targetSessionId:ke.sessionId,mode:fe})}catch(Xe){console.error("Stop CLI failed:",Xe)}},[Pe,q,t]),$a=a.useCallback(async fe=>{const je=fe||Pe;!je||!Ue(je)||Ke(je)||(ce(je),H(!0))},[Pe,Os]),Da=a.useMemo(()=>!Pe||!Ue(Pe)||Ke(Pe)?null:Ot(Pe),[Pe]),Ba=a.useCallback(async fe=>{if(!(!Pe||!Ue(Pe)||Ke(Pe)||Ot(Pe)===fe))try{await t(Pe.daemonId||Pe.ideId,"set_cli_view_mode",{targetSessionId:Pe.sessionId,cliType:Pe.ideType||Pe.agentType,mode:fe})}catch(ke){console.error("Failed to switch CLI view mode:",ke)}},[Pe,t]),{versionMismatchDaemons:Ka,appVersion:Wa,versionBannerDismissed:Oa,setVersionBannerDismissed:za,upgradingDaemons:Ua,handleBannerUpgrade:Ha}=Hc({ides:m,sendDaemonCommand:t}),Tr=a.useCallback(fe=>{ue(fe.tabKey),i(je=>{const ke=new URLSearchParams(je);return fe.sessionId?ke.set("activeTab",fe.sessionId):ke.delete("activeTab"),ke},{replace:!0})},[i]),_r=a.useCallback(fe=>{pe(fe.tabKey),Tr(fe)},[Tr,pe]),Fa=a.useCallback(fe=>{nt(fe.tabKey)},[nt]);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(bo,{wsStatus:g,showReconnected:R}),e.jsx(go,{terminalBackend:$e,isStandalone:Ee,machineLabel:Re,machineKey:De}),!Oa&&e.jsx(Rl,{daemons:Ka,targetVersion:Wa,upgradingDaemons:Ua,onUpgrade:Ha,onDismiss:()=>za(!0)}),e.jsx(Il,{showMobileChatMode:cs,isMobile:z,activeConv:Pe,chatIdes:Ce,wsStatus:g,isConnected:v,onOpenHistory:fe=>{fe&&xt(fe),M(!0)},onOpenRemote:Lt,onStopCli:$a,activeCliViewMode:Da,onSetActiveCliViewMode:Ba,mobileChatConversations:wa,ides:m,actionLogs:xe,sendDaemonCommand:t,setLocalUserMessages:re,setActionLogs:V,isStandalone:Ee,initialDataLoaded:x,userName:f.userName,requestedMobileTabKey:be,onRequestedMobileTabConsumed:Be,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:ie,isSplitMode:ve,numGroups:Ie,groupSizes:A,groupedConvs:Me,clearedTabs:de,focusedGroup:y,setFocusedGroup:k,moveTabToGroup:Ge,splitTabRelative:lt,closeGroup:Fe,handleResizeStart:We,detectedIdes:ge,handleLaunchIde:Ta,groupActiveTabIds:E,setGroupActiveTabIds:P,groupTabOrders:B,setGroupTabOrders:L,toggleHiddenTab:Qe,visibleConversations:O,hiddenConversations:ja,requestedDesktopTabKey:as,onRequestedDesktopTabConsumed:Be,onDesktopActiveTabChange:ue,onHideConversation:Fa,onShowHiddenConversation:_r,onShowAllHiddenConversations:_e,scrollToBottomRequest:C,machineEntries:ye,onBrowseMachineDirectory:ka,onSaveMachineWorkspace:Na,onLaunchMachineIde:Sa,onLaunchMachineProvider:Ca}),e.jsx("style",{children:`
51
+ body { overflow: hidden; overscroll-behavior: none; }
52
+ `}),e.jsx(Ll,{historyModalOpen:T,historyTargetConv:Oe,ides:m,isHistoryCreatingChat:Aa,isHistoryRefreshingHistory:dt?!1:Ma,savedHistorySessions:he,isSavedHistoryLoading:se,isResumingSavedHistorySessionId:F,onCloseHistory:()=>M(!1),onNewHistoryChat:La,onSwitchHistorySession:Pa,onRefreshHistory:dt?Ws:Ra,onResumeSavedHistorySession:Ea,remoteDialogConv:ft,remoteDialogIdeEntry:kt,connectionStates:S,actionLogs:xe,localUserMessages:Y,sendDaemonCommand:t,setLocalUserMessages:re,setActionLogs:V,isStandalone:Ee,userName:f.userName,onOpenRemoteHistory:fe=>{fe&&xt(fe),M(!0)},onRemoteConversationChange:xt,onCloseRemoteDialog:is,cliStopDialogOpen:_,cliStopTargetConv:q,onCancelCliStop:()=>{H(!1),ce(null)},onStopCliNow:async()=>{H(!1),await Os("hard",q),ce(null)},onSaveCliAndStop:async()=>{H(!1),await Os("save",q),ce(null)},toasts:u,onDismissToast:fe=>b(je=>je.filter(ke=>ke.id!==fe)),onClickToast:fe=>{if(fe.targetKey){const je=me(fe.targetKey);je&&(k(X.get(je.tabKey)??0),_r(je),ne({tabKey:je.tabKey,nonce:Date.now()}))}},showOnboarding:p,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}})]})}function Bl({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:i}){const[o,c]=a.useState([]),[d,l]=a.useState(null),[f,m]=a.useState(null),[x,h]=a.useState(!1),[p,j]=a.useState(null),[u,b]=a.useState(!1),[g,v]=a.useState(""),S=a.useRef(null),R=a.useCallback(M=>{S.current=M},[]),w=a.useCallback((M,_,H=!1)=>{c(q=>[...q.slice(-100),{timestamp:Date.now(),level:M,message:_}]),setTimeout(()=>{var q;return(q=i.current)==null?void 0:q.scrollIntoView({behavior:"smooth"})},100),H&&vt.showToast(_,M==="error"||M==="warn"?"warning":"success")},[i]),N=a.useCallback(M=>{const _=M instanceof Error?M.message:String(M||"");return _.includes("P2P command timeout")||_.includes("P2P not connected")||_.includes("P2P not available")},[]),y=a.useCallback(async(M,_)=>{var H;if(!t||d)return!1;l(M),w("info",`Launching ${ze(M)}${_!=null&&_.workspace?` in ${_.workspace}`:""}...`);try{const q={ideType:M,enableCdp:!0};(H=_==null?void 0:_.workspace)!=null&&H.trim()?q.workspace=_.workspace.trim():_!=null&&_.useDefaultWorkspace&&(q.useDefaultWorkspace=!0);const ce=await r(t,"launch_ide",q);return w(ce!=null&&ce.success?"info":"error",ce!=null&&ce.success?`${ze(M)} launched`:`Failed: ${ce==null?void 0:ce.error}`,!0),!!(ce!=null&&ce.success)}catch(q){return w("error",`Launch error: ${q.message}`,!0),!1}finally{l(null)}},[t,d,w,r]),k=a.useCallback(async M=>{if(!t)return{success:!1};const{cliType:_,dir:H,workspaceId:q,useDefaultWorkspace:ce,useHome:he,argsStr:we,model:se,resumeSessionId:Se}=M;if(!_)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const F=we?we.split(/\s+/).filter(Boolean):void 0,oe=(H==null?void 0:H.trim())||(q?"(saved id)":ce?"(default workspace)":he?"(home)":"");w("info",`Launching ${_}${oe?` in ${oe}`:""}${se?` (model: ${se})`:""}...`),m(_);try{const ee={cliType:_,cliArgs:F,initialModel:se||void 0};H!=null&&H.trim()?ee.dir=H.trim():q?ee.workspaceId=q:ce?ee.useDefaultWorkspace=!0:he&&(ee.useHome=!0),Se&&(ee.resumeSessionId=Se);const xe=await r(t,"launch_cli",ee),V=(xe==null?void 0:xe.result)||xe;return xe!=null&&xe.success?(w("info",`${_} launched`,!0),(V==null?void 0:V.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(V==null?void 0:V.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:V==null?void 0:V.sessionId}):(w("error",`Failed: ${(xe==null?void 0:xe.error)||(V==null?void 0:V.error)}`,!0),(xe==null?void 0:xe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&j({cliType:_,argsStr:we,model:se}),{success:!1,sessionId:V==null?void 0:V.sessionId})}catch(ee){return N(ee)?(w("warn",`${_} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${ee.message}`,!0),{success:!1})}finally{m(null)}},[t,w,N,r]),E=a.useCallback(async(M,_,H,q)=>t?M?_.trim()?k({cliType:M,dir:_,argsStr:H,model:q}):(j({cliType:M,argsStr:H,model:q}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[t,w,k]),P=a.useCallback(async(M,_,H)=>{if(t&&window.confirm(`Stop ${M}?
53
+ This will terminate the process.`))try{const q=await r(t,"stop_cli",{cliType:M,dir:_,targetSessionId:H});q!=null&&q.success?w("info",`${M} stopped`,!0):w("error",`Stop failed: ${(q==null?void 0:q.error)||"Unknown error"}`,!0)}catch(q){w("error",`Stop failed: ${q.message}`,!0)}},[t,w,r]),B=a.useCallback(async M=>{try{await r(M.daemonId,"restart_ide",{ideType:M.type}),w("info",`${ze(M.type)} restart initiated`,!0)}catch(_){w("error",`Restart failed: ${_.message}`,!0)}},[w,r]),L=a.useCallback(async M=>{if(window.confirm(`Stop ${ze(M.type)}?
54
+ This will disconnect CDP and optionally kill the process.`))try{const _=await r(M.daemonId,"stop_ide",{ideType:M.type,killProcess:!0});_!=null&&_.success?w("info",`${ze(M.type)} stopped`,!0):w("error",`Stop failed: ${(_==null?void 0:_.error)||"Unknown error"}`,!0)}catch(_){w("error",`Stop failed: ${_.message}`,!0)}},[w,r]),A=a.useCallback(async()=>{if(t)try{const M=await r(t,"detect_ides",{});w("info",`Found ${((M==null?void 0:M.result)||[]).length} IDE(s)`,!0)}catch(M){w("error",`Detection failed: ${M.message}`,!0)}},[t,w,r]),W=a.useCallback(async M=>{if(!t||!M.trim())return!1;h(!0);try{const _=await r(t,"workspace_add",{path:M.trim()});return _!=null&&_.success?(w("info",`Workspace added: ${M.trim()}`),!0):(w("error",(_==null?void 0:_.error)||"workspace_add failed"),!1)}catch(_){return w("error",_.message),!1}finally{h(!1)}},[t,w,r]),z=a.useCallback(async M=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){h(!0);try{const _=await r(t,"workspace_remove",{id:M});_!=null&&_.success?w("info","Workspace removed",!0):w("error",(_==null?void 0:_.error)||"workspace_remove failed",!0)}catch(_){w("error",_.message,!0)}finally{h(!1)}}},[t,w,r]),D=a.useCallback(async M=>{var _;if(t){h(!0);try{const H=await r(t,"workspace_set_default",M===null?{clear:!0}:{id:M});if(H!=null&&H.success){w("info",M?"Default workspace updated":"Default workspace cleared",!0);const q=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";q&&((_=S.current)==null||_.call(S,q))}else w("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){w("error",H.message,!0)}finally{h(!1)}}},[t,w,r]),U=a.useCallback(async M=>{var H;if(!t||!M.trim())return;const _=M.trim();h(!0);try{const q=await r(t,"workspace_set_default",{path:_});q!=null&&q.success?(w("info","Default workspace set from history"),(H=S.current)==null||H.call(S,_)):w("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){w("error",q.message)}finally{h(!1)}},[t,w,r]),T=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(M){w("warn",`Live nickname updated, but account sync failed: ${M.message}`)}w("info",`Nickname set to "${g||"(cleared)"}"`),b(!1)}catch(M){w("error",`Failed: ${M.message}`)}},[t,g,s,w,n,r]);return{logs:o,launchingIde:d,launchingAgentType:f,workspaceBusy:x,launchPick:p,setLaunchPick:j,editingNickname:u,setEditingNickname:b,nicknameInput:g,setNicknameInput:v,addLog:w,handleLaunchIde:y,runLaunchCliCore:k,handleLaunchCli:E,handleStopCli:P,handleRestartIde:B,handleStopIde:L,handleDetectIdes:A,handleWorkspaceAdd:W,handleWorkspaceRemove:z,handleWorkspaceSetDefault:D,handleWorkspaceResumePath:U,handleSaveNickname:T,setOnDefaultWorkspaceChanged:R}}function Kl({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:i,actions:o,sendDaemonCommand:c}){const{workspaceBusy:d,handleWorkspaceAdd:l,handleWorkspaceRemove:f,handleWorkspaceSetDefault:m}=o,[x,h]=a.useState(!1),[p,j]=a.useState(""),[u,b]=a.useState([]),[g,v]=a.useState(!1),[S,R]=a.useState(""),w=a.useCallback(async P=>{v(!0),R("");try{const B=await Sr(c,t,P);j(B.path),b(B.directories)}catch(B){R(B instanceof Error?B.message:"Could not load folder")}finally{v(!1)}},[t,c]),N=a.useCallback(()=>{var B;h(!0);const P=Ds(s.platform,[s.defaultWorkspacePath,(B=s.workspaces[0])==null?void 0:B.path]);w(P)},[w,s.defaultWorkspacePath,s.platform,s.workspaces]),y=s.availableMem??s.freeMem,k=s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/s.totalMem*100))):0,E=s.loadavg[0]||0;return e.jsxs("div",{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[e.jsx(ps,{icon:e.jsx(En,{size:16}),label:"Uptime",value:Zi(s.uptime)}),e.jsx(ps,{icon:e.jsx(st,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(ps,{icon:e.jsx(xr,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(ps,{icon:e.jsx(Si,{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(Wr,{value:Math.min(Math.round(E/s.cpus*100),100),max:100,label:"CPU Load",color:"#8b5cf6",detail:`${E.toFixed(2)} avg / ${s.cpus} cores`}),e.jsx(Wr,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:`${Ur(s.totalMem-y)} / ${Ur(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(Wt,{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:P=>void m(P.target.value===""?null:P.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(P=>e.jsx("option",{value:P.id,children:P.label||P.path},P.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:N,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(P=>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:[P.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:Es(P.path,P.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:P.path,children:P.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:d,onClick:()=>void f(P.id),children:"Remove"})]},P.id))})]}),x&&e.jsx(Bs,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:p,directories:u,busy:g,error:S,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:P=>{w(P)},onConfirm:P=>{(async()=>{if(!P)return;await l(P)&&h(!1)})()}})]})}const yn=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Wl=[{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 Ol({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[i,o]=a.useState("config"),[c,d]=a.useState("codex-cli"),[l,f]=a.useState([]),[m,x]=a.useState(""),[h,p]=a.useState([]),[j,u]=a.useState(""),b=a.useRef(null),g=a.useRef(null),v=k=>{f(E=>E.includes(k)?E.filter(P=>P!==k):[...E,k])},S=()=>f([...yn]),R=()=>f([]);a.useEffect(()=>{var k;(k=b.current)==null||k.scrollIntoView({behavior:"smooth"})},[h]),a.useEffect(()=>()=>{g.current&&clearInterval(g.current)},[]);const w=a.useCallback(()=>{g.current&&clearInterval(g.current),g.current=setInterval(async()=>{try{const k=await r(t,"provider_auto_fix_status",{providerType:s.type});(k==null?void 0:k.running)===!1&&i==="running"&&(o("done"),p(E=>[...E,`
55
+ ✅ Auto-fix completed!`]),g.current&&clearInterval(g.current))}catch{}},3e3)},[t,s.type,r,i]),N=async()=>{if(l.length!==0){o("running"),p(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${l.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),u("");try{const k=await r(t,"provider_auto_fix",{providerType:s.type,functions:l,agent:c,...m?{comment:m}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(p(E=>[...E,"✅ Agent started. Monitoring progress..."]),w()):(o("error"),u((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){o("error"),u((k==null?void 0:k.message)||"Connection failed")}}},y=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),p(k=>[...k,`
56
+ ⚠️ 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:k=>k.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:Wl.map(k=>e.jsxs("button",{onClick:()=>d(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.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:S,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:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:yn.map(k=>e.jsxs("button",{onClick:()=>v(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:l.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:l.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[l.includes(k)?"☑ ":"☐ ",k]},k))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:m,onChange:k=>x(k.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:[h.map((k,E)=>e.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},E)),i==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:b})]}),j&&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:j})]})]}),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:N,disabled:l.length===0,className:"machine-btn",style:{background:l.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:l.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:l.length>0?"#a78bfa":void 0,opacity:l.length===0?.4:1},children:"🚀 Start Fix"})]}),i==="running"&&e.jsx("button",{onClick:y,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(i==="done"||i==="error")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{o("config"),p([]),u("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function zl({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:i}){var w;const o=s.filter(N=>N.category==="ide"),[c,d]=a.useState(((w=o[0])==null?void 0:w.type)||""),[l,f]=a.useState(""),[m,x]=a.useState(""),[h,p]=a.useState(!1),[j,u]=a.useState(""),[b,g]=a.useState(!1),v=N=>{const y=N.toLowerCase().replace(/[^a-z0-9-]/g,"");f(y),(!m||m===S(l))&&x(S(y))},S=N=>N.split("-").map(y=>y.charAt(0).toUpperCase()+y.slice(1)).join(" "),R=async()=>{if(!(!l||!m||!c)){p(!0),u("");try{const N=await r(t,"provider_clone",{type:l,name:m,category:"ide",location:"user",cloneFrom:c});N!=null&&N.success||N!=null&&N.created?(g(!0),i==null||i(l)):u((N==null?void 0:N.error)||"Failed to create provider")}catch(N){u((N==null?void 0:N.message)||"Connection failed")}p(!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:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),e.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:b?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),e.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[e.jsx("code",{className:"text-violet-400",children: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(N=>e.jsxs("button",{onClick:()=>d(N.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===N.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===N.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:N.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===N.type?"#a78bfa":"var(--text-secondary)"},children:N.displayName})]},N.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:N=>v(N.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",e.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",l||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:m,onChange:N=>x(N.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"})]}),j&&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:j})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:b?e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:R,disabled:!l||!m||h,className:"machine-btn",style:{background:l&&m?"rgba(34,197,94,0.12)":void 0,borderColor:l&&m?"rgba(34,197,94,0.3)":void 0,color:l&&m?"#86efac":void 0,opacity:!l||!m||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ul({machineId:t,providers:s,sendDaemonCommand:r}){const[n,i]=a.useState([]),[o,c]=a.useState(!1),[d,l]=a.useState(null),[f,m]=a.useState("all"),[x,h]=a.useState(null),[p,j]=a.useState(!1),u=a.useCallback(async()=>{var g;if(t){c(!0);try{const v=await r(t,"get_provider_settings",{}),S=(v==null?void 0:v.result)||v;if(v!=null&&v.success&&(S!=null&&S.settings)){const R=[];for(const[w,N]of Object.entries(S.settings)){const y=s.find(k=>k.type===w);R.push({type:w,displayName:(y==null?void 0:y.displayName)||w,icon:(y==null?void 0:y.icon)||"",category:(y==null?void 0:y.category)||"unknown",schema:N,values:((g=S.values)==null?void 0:g[w])||{}})}R.sort((w,N)=>w.category.localeCompare(N.category)||w.displayName.localeCompare(N.displayName)),i(R)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const b=async(g,v,S)=>{l(`${g}.${v}`),i(R=>R.map(w=>w.type===g?{...w,values:{...w.values,[v]:S}}:w));try{const R=await r(t,"set_provider_setting",{providerType:g,key:v,value:S});R!=null&&R.success||u()}catch{u()}l(null)};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(g=>e.jsx("button",{onClick:()=>m(g),className:`machine-btn text-[10px] px-2 py-0.5 ${f===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:()=>j(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),e.jsx("button",{onClick:u,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(g=>g.category===f).length>1&&(()=>{const g=n.filter(w=>w.category===f),v=new Map;for(const w of g)for(const N of w.schema){if(N.type!=="boolean")continue;const y=v.get(N.key),k=!!(w.values[N.key]??N.default);y?(y.onCount+=k?1:0,y.total+=1):v.set(N.key,{label:N.label||N.key,onCount:k?1:0,total:1})}const S=[...v.entries()].filter(([,w])=>w.total===g.length);if(S.length===0)return null;const R=async(w,N)=>{for(const y of g)await b(y.type,w,N)};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 ",f.toUpperCase()," providers (",g.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(([w,N])=>{const y=N.onCount===N.total,k=N.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:N.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",N.onCount,"/",N.total,")"]}),e.jsx("button",{onClick:()=>void R(w,!0),disabled:y,className:`machine-btn text-[9px] px-1.5 py-px ${y?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void R(w,!1),disabled:k,className:`machine-btn text-[9px] px-1.5 py-px ${k?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},w)})})]})})(),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=>f==="all"||g.category===f).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:()=>h(s.find(v=>v.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(v=>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:[v.label||v.key,d===`${g.type}.${v.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),v.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:v.description})]}),e.jsx("div",{className:"shrink-0",children:v.type==="boolean"?e.jsx("button",{onClick:()=>b(g.type,v.key,!(g.values[v.key]??v.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:g.values[v.key]??v.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[v.key]??v.default?21:3}})}):v.type==="number"?e.jsx("input",{type:"number",value:g.values[v.key]??v.default??0,min:v.min,max:v.max,onChange:S=>{const R=parseInt(S.target.value)||0;v.min!==void 0&&R<v.min||v.max!==void 0&&R>v.max||b(g.type,v.key,R)},className:"machine-input w-20 text-center text-[11px]"}):v.type==="select"&&v.options?e.jsx("select",{value:g.values[v.key]??v.default??"",onChange:S=>b(g.type,v.key,S.target.value),className:"machine-input text-[11px]",children:v.options.map(S=>e.jsx("option",{value:S,children:S},S))}):e.jsx("input",{type:"text",value:g.values[v.key]??v.default??"",onBlur:S=>b(g.type,v.key,S.target.value),className:"machine-input w-[120px] text-[11px]"})})]},v.key))})]},g.type))}),x&&e.jsx(Ol,{machineId:t,provider:x,sendDaemonCommand:r,onClose:()=>h(null)}),p&&e.jsx(zl,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>j(!1),onCreated:()=>{j(!1),u()}})]})}function Hl({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[i,o]=a.useState(0),[c,d]=a.useState(!0),[l,f]=a.useState("debug"),m=a.useRef(null),x=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const h=async()=>{try{const j=await s(t,"get_logs",{count:200,minLevel:l,since:i}),u=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(u==null?void 0:u.logs)&&u.logs.length>0){n(g=>[...g,...u.logs.map(S=>({timestamp:S.ts,level:S.level,message:`[${S.category}] ${S.message}`}))].slice(-300));const b=Math.max(...u.logs.map(g=>g.ts));o(b)}}catch{}};h();const p=setInterval(h,3e3);return()=>clearInterval(p)},[t,c,i,l,s]),a.useEffect(()=>{if(c&&r.length>0){const h=x.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:h}),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(h=>e.jsx("button",{onClick:()=>{f(h),n([]),o(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${l===h?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:h.toUpperCase()},h))]}),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((h,p)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:h.level==="error"?"#ef4444":h.level==="warn"?"var(--status-warning)":h.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(h.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:h.level==="error"?"#ef4444":h.level==="warn"?"var(--status-warning)":h.level==="debug"?"#475569":"#8b5cf6"},children:h.level==="error"?"ERR":h.level==="warn"?"WRN":h.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:h.message})]},p)),e.jsx("div",{ref:m})]})]})}function Fl({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 Vl({children:t}){return e.jsx("div",{className:"text-xs font-semibold text-text-muted mb-2 tracking-wide uppercase",children:t})}function Gl({machineEntry:t,providers:s,recentLaunches:r,onUpgradeDaemon:n,onOpenRecent:i}){const o=r.slice(0,4),c=d=>d==="ide"?"IDE":d==="cli"?"CLI":"ACP";return e.jsxs("div",{className:"flex flex-col gap-6 md:min-w-[280px] md:max-w-[340px] shrink-0 border-r border-[#ffffff0a] pr-4 md:pr-6 md:h-full overflow-y-auto",children:[o.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Vl,{children:"Recent Activity"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:o.map(d=>e.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-surface border border-[#ffffff08] hover:bg-[#ffffff0a] hover:border-[#ffffff10] transition-colors cursor-pointer group",onClick:()=>i(d),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:d.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[c(d.kind),d.subtitle?` · ${d.subtitle}`:""]})]},d.id))})]}),e.jsx("div",{className:"flex flex-col gap-2 mt-auto pt-4 border-t border-[#ffffff08]",children:t.versionMismatch&&e.jsx("button",{type:"button",className:"btn btn-sm w-full bg-accent-primary/20 text-accent-primary border-accent-primary/30 hover:bg-accent-primary/30",onClick:n,children:"Update Daemon"})})]})}function ql(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Yl={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 Qs({category:t,machine:s,machineId:r,providers:n,managedEntries:i,getIcon:o,actions:c,sendDaemonCommand:d,initialWorkspaceId:l,initialWorkspacePath:f}){const m=zt(),{handleLaunchIde:x,handleStopCli:h,handleRestartIde:p,handleStopIde:j,handleDetectIdes:u,launchingIde:b,launchingAgentType:g,addLog:v}=c,[S,R]=a.useState(null),w=a.useCallback(I=>{I&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(I)}`})},[m]),N=Yl[t],y=t==="ide",k=t==="acp",E=a.useMemo(()=>n.filter(I=>I.category===t),[t,n]),P=a.useMemo(()=>new Map(E.map(I=>[I.type,I.displayName||I.type])),[E]),[B,L]=a.useState(""),[A,W]=a.useState(""),[z,D]=a.useState(""),[U,T]=a.useState(f?"__custom__":l||s.defaultWorkspaceId||""),[M,_]=a.useState(f||""),[H,q]=a.useState([]),[ce,he]=a.useState(!1),[we,se]=a.useState(""),[Se,F]=a.useState([]),[oe,ee]=a.useState(!1),[xe,V]=a.useState(""),Y=a.useRef(null),[re,de]=a.useState(null),ae=a.useRef("__home__"),[Q,ue]=a.useState("__home__"),[C,ne]=a.useState(!1),te=H.filter(I=>!i.some(J=>J.type===I&&rt(J.status)!=="stopped")),$=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!U&&T(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){T("__custom__"),_(f);return}l&&(T(l),_(""))},[l,f]);const G=(()=>{if(U==="__custom__")return M.trim();if(!U)return"";const I=(s.workspaces||[]).find(J=>J.id===U);return(I==null?void 0:I.path)||""})(),Z=a.useCallback(I=>{const J=$.current[I];J&&(clearTimeout(J),delete $.current[I]),q(ie=>ie.includes(I)?ie.filter(X=>X!==I):ie)},[]),ge=a.useRef(new Set),ye=a.useCallback(async I=>{if(d){ee(!0),V("");try{const J=await Sr(d,r,I);se(J.path),_(J.path),F(J.directories)}catch(J){V(J instanceof Error?J.message:"Could not load folder")}finally{ee(!1)}}},[r,d]),Ee=a.useCallback(()=>{var J;if(!d)return;T("__custom__"),he(!0);const I=Ds(s.platform,[M.trim(),G,s.defaultWorkspacePath,(J=s.workspaces[0])==null?void 0:J.path]);ye(I)},[M,ye,s.defaultWorkspacePath,s.platform,s.workspaces,G,d]),$e=a.useCallback((I,J)=>{Y.current=J,ae.current=I.selectedWorkspaceKey||"__home__",ue(I.selectedWorkspaceKey||"__home__"),de(I)},[]),Re=a.useCallback(()=>{Y.current&&(ne(!0),Y.current().finally(()=>{Y.current=null,ne(!1),de(null)}))},[]),De=a.useCallback(I=>{if(!I)return;q(ie=>ie.includes(I)?ie:[...ie,I]);const J=$.current[I];J&&clearTimeout(J),$.current[I]=setTimeout(()=>{q(ie=>ie.includes(I)?ie.filter(X=>X!==I):ie),delete $.current[I]},2e4)},[]);a.useEffect(()=>{for(const J of i)rt(J.status)!=="stopped"&&(H.includes(J.type)&&!ge.current.has(J.type)&&(ge.current.add(J.type),v("info",`${P.get(J.type)||J.type} launched`,!0)),Z(J.type));const I=new Set(i.filter(J=>rt(J.status)!=="stopped").map(J=>J.type));ge.current.forEach(J=>{!H.includes(J)&&!I.has(J)&&ge.current.delete(J)})},[v,Z,i,H,P]),a.useEffect(()=>()=>{Object.values($.current).forEach(clearTimeout),$.current={}},[]);const[Ye,nt]=a.useState({}),[Qe,pe]=a.useState(null);a.useEffect(()=>{if(!y||!r||!d)return;(async()=>{try{const J=await d(r,"get_ide_extensions",{}),ie=(J==null?void 0:J.result)||J;ie!=null&&ie.success&&(ie!=null&&ie.ideExtensions)&&nt(ie.ideExtensions)}catch{}})()},[y,r,d]);const _e=I=>y?ze(I.type):t==="cli"?I.cliName:I.acpName,Ce=y?s.detectedIdes||[]:[],Ne=a.useCallback(async I=>{const J=(I==null?void 0:I.type)||B,ie=(I==null?void 0:I.workspacePath)??G;if(y){await x(J,ie?{workspace:ie}:void 0)&&De(J);return}const X=await c.runLaunchCliCore({cliType:J,dir:I!=null&&I.workspaceId?void 0:ie||void 0,workspaceId:(I==null?void 0:I.workspaceId)||void 0,useHome:(I==null?void 0:I.useHome)||!(I!=null&&I.workspaceId)&&!ie,argsStr:(I==null?void 0:I.argsStr)??(A||void 0),model:(I==null?void 0:I.model)??(k&&z||void 0)});(X.success||X.pending)&&(De(J),X.success&&X.sessionId&&w(X.sessionId))},[c,x,k,y,A,z,De,w,G,B]),O=()=>{const I=y?ze(B):P.get(B)||B,{options:J,selectedKey:ie}=Tt({machine:s,currentWorkspaceId:U&&U!=="__custom__"?U:null,currentWorkspacePath:G});$e({title:`Launch ${I}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:J,selectedWorkspaceKey:ie,details:[{label:"Mode",value:N.label},{label:"Provider",value:I},...!y&&A.trim()?[{label:"Arguments",value:A.trim()}]:[],...k&&z.trim()?[{label:"Model",value:z.trim()}]:[]]},async()=>{const X=J.find(Ie=>Ie.key===ae.current);X!=null&&X.workspaceId?(T(X.workspaceId),_("")):X!=null&&X.workspacePath?(T("__custom__"),_(X.workspacePath)):(T(""),_("")),await Ne({workspaceId:(X==null?void 0:X.workspaceId)??null,workspacePath:(X==null?void 0:X.workspacePath)??"",useHome:!(X!=null&&X.workspaceId)&&!(X!=null&&X.workspacePath)})})},K=I=>{y?j(I):h(I.type,I.workspace,I.id)},le=a.useCallback(async(I,J,ie=!1)=>{if(I.mode===J){ie&&I.sessionId&&w(I.sessionId);return}if(!d||!I.sessionId){ie&&I.sessionId&&w(I.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:I.sessionId,cliType:I.type,mode:J}),ie&&w(I.sessionId)}catch(X){console.error("Failed to switch CLI view mode:",X)}},[r,w,d]),me=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:U,onChange:I=>{const J=I.target.value;if(T(J),J==="__custom__"&&d){Ee();return}J!=="__custom__"&&_("")},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(I=>e.jsxs("option",{value:I.id,children:[I.id===s.defaultWorkspaceId?"⭐ ":"",Es(I.path,I.label)]},I.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…"})]})}),U==="__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:Ee,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:M,onChange:I=>_(I.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:U==="__custom__"?G?e.jsx("span",{className:"font-mono truncate block",title:G,children:G}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":G?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:U===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:G,children:G})]}):"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 ${N.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 ",N.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:y?Ce.length>0?Ce.map(I=>{const J=i.find(Me=>(Me.type||"").toLowerCase()===(I.type||"").toLowerCase()&&rt(Me.status)!=="stopped"),ie=I.running||!!J,X=!!J&&J.cdpConnected,Ie=H.includes(I.type||I.id||""),ve=B===(I.type||"");return e.jsxs("button",{onClick:()=>{if(X&&J){const Me=J.sessionId;Me?m(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}}):m("/dashboard",{state:{openRemoteForTabKey:J.id}});return}Ie||L(Me=>Me===(I.type||"")?"":I.type||"")},disabled:!!b||Ie,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":ve?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==I.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(I.type)}),ie&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${X?"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:I.name||ze(I.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${X?"text-green-400":Ie?"text-orange-400":ve?"text-accent-primary":"text-text-muted"}`,children:X?"Open Session":Ie?"Starting...":ve?"Configure":"Select"})]})]},I.type)}):e.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",e.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[e.jsx(wi,{size:14})," Scan System"]})]}):E.length>0?E.map(I=>{const J=B===I.type,ie=H.includes(I.type),Ie=!!i.find(ve=>ve.type===I.type&&rt(ve.status)!=="stopped");return e.jsxs("button",{onClick:()=>L(ve=>ve===I.type?"":I.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${J?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:I.icon}),Ie&&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:I.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ie?"text-orange-400":J?"text-accent-primary":"text-text-muted"}`,children:ie?"Starting...":J?"Configure":"Select"})]})]},I.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 ",t.toUpperCase()," providers available"]})}),B&&(y?Ce.find(I=>I.type===B):E.find(I=>I.type===B))&&e.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:y?ze(B):P.get(B)||B})]}),me,!y&&e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&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:z,onChange:I=>D(I.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:A,onChange:I=>W(I.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.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:O,disabled:!!g||!!b||H.includes(B),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===B||b===B?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",i.length+H.filter(I=>!i.some(J=>J.type===I&&rt(J.status)!=="stopped")).length,")"]}),i.length===0&&te.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 ",N.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[te.map(I=>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(I)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:y?ze(I):P.get(I)||I}),e.jsx("div",{className:"text-[11px] text-text-muted",children:g===I?"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:${I}`)),i.map(I=>{const J=y?I:null,ie=k?I:null,X=!y&&!k?I:null,Ie=rt(I.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(I.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[_e(I),(J==null?void 0:J.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",J.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:I.workspace||"—"}),(ie==null?void 0:ie.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",ie.currentModel]}),(ie==null?void 0:ie.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",ie.currentPlan]}),(X==null?void 0:X.mode)&&e.jsx("span",{className:X.mode==="chat"?"text-violet-400":"text-text-secondary",children:X.mode==="chat"?"Chat view":"Terminal view"})]}),X&&(X.runtimeKey||X.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[X.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 ",X.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 ve;(ve=navigator.clipboard)==null||ve.writeText(`adhdev attach ${X.runtimeKey}`),R(X.runtimeKey||null),window.setTimeout(()=>{R(Me=>Me===X.runtimeKey?null:Me)},1200)},children:S===X.runtimeKey?"Copied":"Copy"})]}),X.runtimeWriteOwner&&e.jsx("span",{style:{color:X.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:X.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:ql(X.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 ${Ie==="stopped"?"bg-red-500/[0.08] text-red-500":Ie==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ie}),y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const ve=I.sessionId;if(ve){m(`/dashboard?activeTab=${encodeURIComponent(ve)}`,{state:{openRemoteForTabKey:ve}});return}m("/dashboard",{state:{openRemoteForTabKey:I.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(st,{size:13})}),e.jsx("button",{onClick:()=>{const ve=I.workspace||"",{options:Me,selectedKey:Ge}=Tt({machine:s,currentWorkspacePath:ve});$e({title:`Restart ${ze(I.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Me,selectedWorkspaceKey:Ge,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ze(I.type)}]},async()=>{const Fe=Me.find(lt=>lt.key===ae.current),We=(Fe==null?void 0:Fe.workspacePath)??"";if(We&&We!==ve){await Ne({type:I.type,workspacePath:We});return}await p(I)})},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(mr,{size:14})})]}),k&&e.jsx("button",{onClick:()=>{const ve=I.sessionId;ve&&w(ve)},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:!I.sessionId,children:e.jsx(gt,{size:14})}),X&&Ie!=="stopped"&&e.jsxs(e.Fragment,{children:[X.mode&&e.jsx(yr,{mode:X.mode,onChange:ve=>void le(X,ve,!1),compact:!0}),e.jsx("button",{onClick:()=>{const ve=I.sessionId;ve&&w(ve)},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:!I.sessionId,children:X.mode==="chat"?e.jsx(gt,{size:14}):e.jsx(st,{size:13})})]}),Ie==="stopped"?e.jsx("button",{onClick:()=>{const ve=I.workspace||"",Me=y?ze(I.type):_e(I),{options:Ge,selectedKey:Fe}=Tt({machine:s,currentWorkspacePath:ve});$e({title:`Launch ${Me}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:Ge,selectedWorkspaceKey:Fe,details:[{label:"Mode",value:N.label},{label:"Provider",value:Me}]},async()=>{const We=Ge.find(lt=>lt.key===ae.current);await Ne({type:I.type,workspaceId:(We==null?void 0:We.workspaceId)??null,workspacePath:(We==null?void 0:We.workspacePath)??"",useHome:!(We!=null&&We.workspaceId)&&!(We!=null&&We.workspacePath),model:ie==null?void 0:ie.currentModel})})},disabled:H.includes(I.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:H.includes(I.type)?"⏳":e.jsx(hr,{size:14})}):e.jsx("button",{onClick:()=>K(I),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(At,{size:14})})]})]}),J&&J.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:J.aiAgents.map(ve=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${On(ve.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[ve.name," · ",rt(ve.status)]},ve.id))}),J&&(Ye[J.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:(Ye[J.type]||[]).map(ve=>e.jsxs("button",{disabled:Qe===`${J.type}.${ve.type}`,onClick:async()=>{const Me=`${J.type}.${ve.type}`;pe(Me);try{await d(r,"set_ide_extension",{ideType:J.type,extensionType:ve.type,enabled:!ve.enabled}),nt(Ge=>({...Ge,[J.type]:(Ge[J.type]||[]).map(Fe=>Fe.type===ve.type?{...Fe,enabled:!Fe.enabled}:Fe)}))}catch(Ge){console.error("Extension toggle failed:",Ge)}finally{pe(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 ${ve.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 ${ve.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),ve.name,e.jsx("span",{className:"text-[9px] font-normal",children:ve.enabled?"ON":"OFF"})]},ve.type))})]})]},I.id)})]}),ce&&d&&e.jsx(Bs,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:we,directories:Se,busy:oe,error:xe,confirmLabel:"Use this folder",onClose:()=>he(!1),onNavigate:I=>{ye(I)},onConfirm:I=>{_(I),T("__custom__"),he(!1)}}),re&&e.jsx(Cr,{title:re.title,description:re.description,details:re.details,workspaceOptions:re.workspaceOptions,selectedWorkspaceKey:Q,onWorkspaceChange:I=>{ae.current=I,ue(I)},confirmLabel:re.confirmLabel,busy:C,onConfirm:Re,onCancel:()=>{Y.current=null,de(null)}})]})}const vn=[{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 Xl({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:i,acpSessions:o,actions:c,getIcon:d,initialCategory:l="ide",initialWorkspaceId:f,initialWorkspacePath:m,sendDaemonCommand:x}){var u;const[h,p]=a.useState(l);a.useEffect(()=>{p(l)},[l]);const j=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:vn.map(b=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${h===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>p(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${h===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:j[b.id]})]},b.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=vn.find(b=>b.id===h))==null?void 0:u.helper})]}),h==="ide"&&e.jsx(Qs,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:m}),h==="cli"&&e.jsx(Qs,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:m}),h==="acp"&&e.jsx(Qs,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:m})]})}function Jl({onNicknameSynced:t}={}){var ee,xe,V,Y,re,de,ae,Q,ue;const{id:s}=ri(),r=zt(),n=dr(),{sendCommand:i}=jt(),o=gr(),c=o.ides||[],d=o.initialLoaded??!0,l=c.find(C=>C.id===s&&C.daemonMode),f=c.some(C=>C.type==="adhdev-daemon"),[m,x]=a.useState("workspace"),[h,p]=a.useState("ide"),j=a.useRef(null),[u,b]=a.useState(null),g=a.useRef("__home__"),[v,S]=a.useState("__home__"),[R,w]=a.useState(!1),N=a.useRef(null),y=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},k=Bl({machineId:s,registeredMachineId:(l==null?void 0:l.machineId)||null,sendDaemonCommand:i,onNicknameSynced:t,logsEndRef:N});a.useEffect(()=>vt.onToast(ne=>{o.setToasts($=>{if($.some(ge=>ge.message===ne.message&&ne.timestamp-ge.timestamp<3e3))return $;const Z={id:ne.id,message:ne.message,type:ne.type,timestamp:ne.timestamp,targetKey:ne.targetKey,actions:ne.actions};return[...$.slice(-4),Z]});const te=ne.duration||5e3;setTimeout(()=>o.setToasts($=>$.filter(G=>G.id!==ne.id)),te)}),[o]);const E=(l==null?void 0:l.availableProviders)||[],P={};for(const C of E)P[C.type]=C.icon;const B=C=>P[C]||"",L=l?{id:l.id,hostname:zn(l,{fallbackId:l.id}),platform:((ee=l.machine)==null?void 0:ee.platform)||"unknown",arch:((xe=l.machine)==null?void 0:xe.arch)||"",cpus:((V=l.machine)==null?void 0:V.cpus)||0,totalMem:((Y=l.machine)==null?void 0:Y.totalMem)||0,freeMem:((re=l.machine)==null?void 0:re.freeMem)||0,availableMem:(de=l.machine)==null?void 0:de.availableMem,loadavg:((ae=l.machine)==null?void 0:ae.loadavg)||[],uptime:((Q=l.machine)==null?void 0:Q.uptime)||0,release:((ue=l.machine)==null?void 0:ue.release)||"",cdpConnected:!!l.cdpConnected,machineNickname:l.machineNickname||null,p2p: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,A=c.filter(C=>C.daemonId===s&&!C.daemonMode).filter(C=>!Qt(C)&&!Bt(C)).map(C=>({id:C.id,sessionId:C.sessionId,type:C.type,version:C.version||"",instanceId:C.instanceId||"",status:C.status,workspace:C.workspace||null,terminals:C.terminals||0,aiAgents:no(C.aiAgents||C.agents||[]),activeChat:C.activeChat||null,chats:C.chats||[],childSessions:C.childSessions||[],cdpConnected:C.cdpConnected||!1,daemonId:s})),W=c.filter(C=>C.daemonId===s&&Qt(C)).map(C=>({id:C.id,sessionId:C.sessionId,type:C.type,cliName:C.cliName||C.type,status:C.status,workspace:C.workspace||"",activeChat:C.activeChat||null,providerSessionId:C.providerSessionId,mode:C.mode,daemonId:s})),z=c.filter(C=>C.daemonId===s&&Bt(C)).map(C=>({id:C.id,sessionId:C.sessionId,type:C.type,acpName:C.cliName||C.type,status:C.status,workspace:C.workspace||"",activeChat:C.activeChat||null,providerSessionId:C.providerSessionId,currentModel:C.currentModel,currentPlan:C.currentPlan,daemonId:s}));if(!L)return d?e.jsxs("div",{className:"p-10 text-center text-text-muted",children:[e.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),e.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),e.jsx("button",{onClick:y,className:"machine-btn-back",children:"← Back"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const D=ct(l,{fallbackId:L.id}),U="workspace",T=n.state,M=T==null?void 0:T.initialMachineTab,_=T==null?void 0:T.initialWorkspaceCategory,H=T==null?void 0:T.initialWorkspaceId,q=T==null?void 0:T.initialWorkspacePath,ce=M==="ides"||M==="clis"||M==="acps"?"workspace":M||U,he=M==="ides"?"ide":M==="clis"?"cli":M==="acps"?"acp":_,we=[...A.map(C=>{var ne,te,$,G,Z;return{id:`ide:${C.type}:${C.workspace||""}`,label:((ne=C.activeChat)==null?void 0:ne.title)||C.type,kind:"ide",providerType:C.type,subtitle:C.workspace||void 0,workspace:C.workspace||void 0,timestamp:((Z=(G=($=(te=C.activeChat)==null?void 0:te.messages)==null?void 0:$.at)==null?void 0:G.call($,-1))==null?void 0:Z.timestamp)||0}}),...W.map(C=>{var ne,te,$,G,Z;return{id:`cli:${C.type}:${C.workspace||""}`,label:((ne=C.activeChat)==null?void 0:ne.title)||C.cliName,kind:"cli",providerType:C.type,providerSessionId:C.providerSessionId,subtitle:C.workspace||void 0,workspace:C.workspace||void 0,timestamp:((Z=(G=($=(te=C.activeChat)==null?void 0:te.messages)==null?void 0:$.at)==null?void 0:G.call($,-1))==null?void 0:Z.timestamp)||0}}),...z.map(C=>{var ne,te,$,G,Z;return{id:`acp:${C.type}:${C.workspace||""}`,label:((ne=C.activeChat)==null?void 0:ne.title)||C.acpName,kind:"acp",providerType:C.type,providerSessionId:C.providerSessionId,subtitle:C.currentModel||C.workspace||void 0,workspace:C.workspace||void 0,currentModel:C.currentModel,timestamp:((Z=(G=($=(te=C.activeChat)==null?void 0:te.messages)==null?void 0:$.at)==null?void 0:G.call($,-1))==null?void 0:Z.timestamp)||0}})].sort((C,ne)=>ne.timestamp-C.timestamp).map(({timestamp:C,...ne})=>ne),se=(l.recentLaunches||[]).length>0?l.recentLaunches.map(C=>({id:C.id,label:C.title||C.providerName||C.providerType,kind:C.kind,providerType:C.providerType,providerSessionId:C.providerSessionId,subtitle:C.currentModel||C.workspace||void 0,workspace:C.workspace,currentModel:C.currentModel})):we,Se=a.useCallback(()=>{j.current&&(w(!0),j.current().finally(()=>{j.current=null,w(!1),b(null)}))},[]),F=a.useCallback(C=>{const{options:ne,selectedKey:te}=Tt({machine:L,currentWorkspacePath:C.workspace}),$=async()=>{p(C.kind),x("workspace")};j.current=async()=>{const G=ne.find(ye=>ye.key===g.current),Z=(G==null?void 0:G.workspacePath)??null,ge=(G==null?void 0:G.workspaceId)??null;if(C.kind==="ide"&&C.providerType){await k.handleLaunchIde(C.providerType,Z?{workspace:Z}:void 0);return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){await k.runLaunchCliCore({cliType:C.providerType,dir:ge?void 0:Z||"",workspaceId:ge||void 0,model:C.kind==="acp"?C.currentModel:void 0,resumeSessionId:C.providerSessionId});return}await $()},g.current=te,S(te),b({title:`Launch ${C.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ne,details:[{label:"Mode",value:C.kind.toUpperCase()},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]})},[k,L]);a.useEffect(()=>{x(ce)},[U,ce,L.id]),a.useEffect(()=>{he&&p(he)},[he,L.id]);const oe=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(st,{size:14})," Workspace"]}),count:A.length+W.length+z.length},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ps,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ki,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(vi,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[e.jsx("button",{onClick:y,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[k.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:k.nicknameInput,onChange:C=>k.setNicknameInput(C.target.value),onKeyDown:C=>{C.key==="Enter"&&k.handleSaveNickname(),C.key==="Escape"&&k.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),e.jsx("button",{onClick:k.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),e.jsx("button",{onClick:()=>k.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{k.setEditingNickname(!0),k.setNicknameInput(L.machineNickname||"")},title:"Click to set nickname",children:D}),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:[L.platform," · ",L.arch]}),e.jsxs("span",{children:[L.cpus," cores"]}),(l==null?void 0:l.version)&&e.jsxs("span",{children:["v",l.version]}),L.p2p.available&&e.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:oe.map(C=>e.jsxs("button",{onClick:()=>x(C.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${m===C.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[C.label,C.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${m===C.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:C.count})]},C.id))})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:e.jsx("div",{className:"max-w-7xl mx-auto h-full",children:e.jsxs("div",{className:"h-full",children:[m==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Gl,{machineEntry:l,providers:E,recentLaunches:se,onUpgradeDaemon:async()=>{try{await i(s,"daemon_upgrade",{})}catch{}},onOpenRecent:F}),e.jsx(Xl,{machine:L,machineId:s,providers:E,ideSessions:A,cliSessions:W,acpSessions:z,actions:k,getIcon:B,initialCategory:h,initialWorkspaceId:H,initialWorkspacePath:q,sendDaemonCommand:i})]}),m==="providers"&&e.jsx(Ul,{machineId:s,providers:E,sendDaemonCommand:i}),m==="overview"&&e.jsx(Kl,{machineId:s,machine:L,ideSessions:A,cliSessions:W,acpSessions:z,actions:k,sendDaemonCommand:i}),m==="logs"&&e.jsx(Hl,{machineId:s,sendDaemonCommand:i})]})})}),k.launchPick&&L&&e.jsx(Fl,{machine:L,launchPick:k.launchPick,actions:k}),u&&e.jsx(Cr,{title:u.title,description:u.description,details:u.details,workspaceOptions:u.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:C=>{g.current=C,S(C)},confirmLabel:u.confirmLabel,busy:R,onConfirm:Se,onCancel:()=>{j.current=null,b(null)}}),e.jsx(Gn,{toasts:o.toasts||[],onDismiss:C=>o.setToasts(ne=>ne.filter(te=>te.id!==C)),onClickToast:C=>{C.targetKey}}),e.jsx("style",{children:`
57
+ @keyframes toast-in {
58
+ from { opacity: 0; transform: translateX(40px); }
59
+ to { opacity: 1; transform: translateX(0); }
60
+ }
61
+ `})]})}function Zl(){const[t,s]=a.useState({ide:[],cli:[],ext:[],acp:[]}),[r,n]=a.useState(!0);a.useEffect(()=>{fetch("https://raw.githubusercontent.com/vilmire/adhdev-providers/main/registry.json").then(c=>c.json()).then(c=>{const d=[],l=[],f=[],m=[];Object.values(c.providers||{}).forEach(h=>{const p={name:h.name||"Unknown",status:h.status||"Stable",details:h.details||"Community Provider"};h.category==="ide"?d.push(p):h.category==="cli"?l.push(p):h.category==="extension"?f.push(p):h.category==="acp"&&m.push(p)});const x=(h,p)=>{const j={Stable:1,Beta:2,WIP:3},u=j[h.status]||99,b=j[p.status]||99;return u!==b?u-b:h.name.localeCompare(p.name)};s({ide:d.sort(x),cli:l.sort(x),ext:f.sort(x),acp:m.sort(x)})}).catch(c=>console.error("Failed to load capabilities:",c)).finally(()=>n(!1))},[]);const i=c=>c==="Stable"?e.jsxs("div",{className:"flex items-center gap-1.5 text-success",children:[e.jsx(Ln,{className:"w-4 h-4"})," ",e.jsx("span",{children:"Stable"})]}):c==="Beta"?e.jsxs("div",{className:"flex items-center gap-1.5 text-warning",children:[e.jsx(fr,{className:"w-4 h-4"})," ",e.jsx("span",{children:"Beta"})]}):e.jsxs("div",{className:"flex items-center gap-1.5 text-text-muted",children:[e.jsx(En,{className:"w-4 h-4"})," ",e.jsx("span",{children:c})]}),o=c=>e.jsx("div",{className:"bg-bg-card border border-border-subtle rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary border-b border-border-subtle text-xs uppercase text-text-muted font-medium tracking-wider",children:[e.jsx("th",{className:"py-3 px-4 w-1/3",children:"Target"}),e.jsx("th",{className:"py-3 px-4 w-1/4",children:"Status"}),e.jsx("th",{className:"py-3 px-4",children:"Details"})]})}),e.jsx("tbody",{className:"divide-y divide-border-subtle text-sm",children:c.map((d,l)=>e.jsxs("tr",{className:"hover:bg-bg-subtle/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4 font-medium text-text-main",children:d.name}),e.jsx("td",{className:"py-3 px-4",children:i(d.status)}),e.jsx("td",{className:"py-3 px-4 text-text-muted",children:d.details})]},l))})]})});return r?e.jsx(_s,{title:"Capabilities",subtitle:"Provider registry coverage for IDEs, CLI agents, extensions, and ACPs",icon:e.jsx(Is,{}),widthClassName:"max-w-5xl",children:e.jsx(wr,{icon:e.jsx("div",{className:"w-8 h-8 border-4 border-accent border-t-transparent rounded-full animate-spin mx-auto"}),title:"Loading provider registry",description:"Fetching the latest support matrix from the shared provider registry."})}):e.jsxs(_s,{title:"Capabilities",subtitle:"Provider registry coverage for IDEs, CLI agents, extensions, and ACPs",icon:e.jsx(Is,{}),widthClassName:"max-w-5xl",contentClassName:"animate-fade-in",children:[e.jsx(tt,{title:"Registry overview",description:"Support status is loaded from the shared provider registry used across OSS and cloud surfaces.",children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"IDEs"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.ide.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"CLI"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.cli.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"Extensions"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.ext.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-text-muted mb-1",children:"ACP"}),e.jsx("div",{className:"text-2xl font-semibold text-text-primary",children:t.acp.length})]})]})}),e.jsx(tt,{title:"IDE support",icon:e.jsx(st,{className:"w-4 h-4"}),description:"Desktop editors and IDE surfaces with registry-backed providers.",children:o(t.ide)}),e.jsx(tt,{title:"Standalone CLI agents",icon:e.jsx(xr,{className:"w-4 h-4"}),description:"CLI-first agents that can participate in the standalone dashboard.",children:o(t.cli)}),e.jsx(tt,{title:"AI extensions",icon:e.jsx(_t,{className:"w-4 h-4"}),description:"IDE extensions and companion integrations available in the registry.",children:o(t.ext)}),e.jsx(tt,{title:`ACP agents (${t.acp.length} loaded)`,icon:e.jsx(_t,{className:"w-4 h-4"}),description:"ACP-backed providers discovered through the same shared registry.",children:o(t.acp)})]})}class Ql{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(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 ht=new Ql;function ed(){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 wn=ed(),jn=3e3,td=3e4;let bt=null,sd=0;const Ms=new Map;let St=null,Yt=null;function kn(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function rd(t){return t==="connected"?"connected":t}async function Ns(t,s,r){const n=To(t,r||{}),i=bt;if(i&&i.readyState===WebSocket.OPEN){const o=`req_${++sd}_${Date.now()}`;return new Promise((c,d)=>{const l=setTimeout(()=>{Ms.delete(o),d(new Error(`WS command timeout: ${s}`))},3e4);Ms.set(o,{resolve:f=>{clearTimeout(l),c(f)},reject:f=>{clearTimeout(l),d(f)}}),i.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}class nd{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(bt==null?void 0:bt.readyState)===WebSocket.OPEN}get connectionState(){return(bt==null?void 0:bt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Ns(this.daemonId,s,r)}async sendInput(s,r){return Ns(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,St&&(clearInterval(St),St=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ns(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());ht.emitScreenshot(this.daemonId,i)}}catch{}};r(),St=setInterval(r,2e3)}stopScreenshots(s){St&&(clearInterval(St),St=null)}}let it=null;function ad(t){return(!it||it.daemonId!==t)&&(it=new nd(t)),it}function id({children:t}){const s=a.useRef(Dr()),r=Dr();s.current=r;const{setUserName:n}=Xt(),i=a.useRef(n);i.current=n;const[,o]=a.useState("disconnected"),c=a.useCallback((h,p)=>{o(h),Yt==null||Yt(h,p)},[]),d=a.useRef(null),l=a.useRef(),f=a.useRef(jn),m=a.useRef(!0),x=a.useRef(!1);return a.useEffect(()=>{m.current=!0,x.current=!1;function h(){var u,b;if(!m.current||((u=d.current)==null?void 0:u.readyState)===WebSocket.OPEN||((b=d.current)==null?void 0:b.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${wn}...`);let j;try{j=new WebSocket(wn)}catch(g){console.error("[Standalone WS] Failed to create WebSocket:",g),p();return}d.current=j,j.onopen=()=>{if(!m.current){j.close();return}c("connected"),f.current=jn,console.log("[Standalone WS] Connected")},bt=j,j.onmessage=g=>{var v;try{const S=JSON.parse(g.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const R=Ms.get(S.requestId);R&&(Ms.delete(S.requestId),S.type==="error"?R.reject(new Error(((v=S.data)==null?void 0:v.message)||"Command failed")):R.resolve(S.data));return}if(S.type==="session_output"){const R=S.sessionId||S.cliId||S.cliType;R&&ht.emitSessionOutput(R,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){ht.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated);return}if(S.type==="status"||S.type==="initial_state"){const R=S.data;if(!R)return;const{injectEntries:w,markLoaded:N}=s.current,y=R.id||"standalone",k=ad(y);ht.register(y,k),ht.setState(y,"connected"),c("connected",y),ht.emitStatus(y,R);const E=Co(R,{daemonId:y});kn("ws_status",{type:S.type,daemonId:y,sessions:(R.sessions||[]).map(P=>({id:P.id,parentId:P.parentId,providerType:P.providerType,kind:P.kind,transport:P.transport,unread:P.unread,inboxBucket:P.inboxBucket,lastSeenAt:P.lastSeenAt,lastUpdated:P.lastUpdated,title:P.title})),recentLaunches:(R.recentLaunches||[]).map(P=>({id:P.id,providerType:P.providerType,kind:P.kind,workspace:P.workspace,lastLaunchedAt:P.lastLaunchedAt}))}),kn("entries",{daemonId:y,entries:E.filter(P=>P.type!=="adhdev-daemon").map(P=>({id:P.id,type:P.type,unread:P.unread,inboxBucket:P.inboxBucket,lastSeenAt:P.lastSeenAt,lastUpdated:P.lastUpdated,sessionId:P.sessionId}))}),E.length>0&&w(E,{authoritativeDaemonIds:[y]}),N(),R.userName&&i.current&&i.current(R.userName)}}catch(S){console.error("[Standalone WS] Parse error:",S)}},j.onclose=()=>{m.current&&(it==null||it.stopScreenshots(),it&&ht.setState(it.daemonId,"disconnected"),c("disconnected"),d.current=null,p())},j.onerror=g=>{x.current||!m.current||console.warn("[Standalone WS] Error, will reconnect:",g)}}function p(){if(!m.current)return;clearTimeout(l.current);const j=f.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),l.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,td),h()},j)}return h(),()=>{m.current=!1,x.current=!0,clearTimeout(l.current),d.current&&(d.current.onerror=null,d.current.onclose=null,d.current.close(),d.current=null,bt=null),it&&(it.stopScreenshots(),ht.unregister(it.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function od({children:t}){const[s,r]=a.useState("disconnected"),[n,i]=a.useState(null);a.useEffect(()=>(Yt=(c,d)=>{r(c),d&&i(d)},()=>{Yt=null}),[]);const o=a.useMemo(()=>{const c=s==="connected",d=rd(s),l={};return n&&(l[n]=d),l.standalone=d,{wsStatus:s,isConnected:c,connectionStates:l}},[s,n]);return e.jsx(ui,{connectionOverrides:o,children:e.jsx(id,{children:t})})}const cd=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Mn,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Cs,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(Ps,{}),label:"Settings"}];function ld({children:t}){const s=zt(),r=dr(),[n,i]=a.useState(!1),[o,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=m=>{s(m),i(!1)},l=()=>{c(m=>{const x=!m;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${o?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${o?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>i(!0),children:[e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"})]}),n&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>i(!1),onKeyDown:m=>m.key==="Escape"&&i(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${o?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>i(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:cd.map(m=>e.jsxs("div",{className:f(m.path),id:`nav-${m.id}`,onClick:()=>d(m.path),title:o?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!o&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:o?"Docs":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(Is,{})}),!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(Pn,{})}),!o&&"About"]}),!o&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.20"]}),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 dd=[{icon:e.jsx(Cs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(gt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(Rn,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(st,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(_t,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Is,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ud=[{icon:e.jsx($n,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Mn,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(Ls,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(yi,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(bi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Ln,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],pd=[{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 md(){return e.jsxs(_s,{icon:e.jsx(Pn,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, supported 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.20"]}),children:[e.jsx(tt,{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(tt,{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:dd.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(tt,{title:"Compatible with",description:"Supported editors and agent surfaces exposed in the standalone dashboard.",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Xn.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Zn.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Jn.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(tt,{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:ud.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(tt,{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:pd.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(wr,{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(Mi,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function fd(){const{ides:t}=Xt(),s=t.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=jt(),{userName:i}=Xt(),[o,c]=a.useState(i||"");a.useEffect(()=>{i!==void 0&&c(i)},[i]);const d=x=>{const h=x.target.value.trim();s!=null&&s.id&&h!==i&&n(s.id,"set_user_name",{userName:h}).catch(console.error)},[l,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=x=>{f(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return e.jsxs(_s,{icon:e.jsx(Ps,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(Uo,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(tt,{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.20"]}),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(tt,{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(tt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Xo,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(tt,{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(ec,{})]}),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(mc,{})]}),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(xc,{})]})]})}),e.jsx(tt,{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(Yo,{}),e.jsx(wt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ai,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:l,onChange:m})]})}),e.jsx(tt,{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(gi,{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()}})]})})})]})}qo();uc();oc();const xd=_n({baseUrl:""});function Nn(){const{ides:t,initialLoaded:s}=Xt();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(er,{to:`/machines/${r.id}`,replace:!0}):e.jsx(er,{to:"/dashboard",replace:!0})}function hd(){return e.jsx(ni,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(fi,{client:xd,children:e.jsx(od,{children:e.jsx(hi,{value:{sendCommand:Ns,sendData:()=>!1},children:e.jsx(ld,{children:e.jsxs(ai,{children:[e.jsx(yt,{path:"/dashboard",element:e.jsx(Dl,{})}),e.jsx(yt,{path:"/machine",element:e.jsx(Nn,{})}),e.jsx(yt,{path:"/machines/:id",element:e.jsx(Jl,{})}),e.jsx(yt,{path:"/machines",element:e.jsx(Nn,{})}),e.jsx(yt,{path:"/capabilities",element:e.jsx(Zl,{})}),e.jsx(yt,{path:"/about",element:e.jsx(md,{})}),e.jsx(yt,{path:"/settings",element:e.jsx(fd,{})}),e.jsx(yt,{path:"*",element:e.jsx(er,{to:"/dashboard",replace:!0})})]})})})})})})}xo({connectionManager:ht});ii(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(hd,{})}));