@adhdev/daemon-standalone 0.7.46 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,68 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-PD6SznsC.js","assets/vendor-CPghmr9Y.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var Hr=Object.defineProperty;var Vr=(t,s,n)=>s in t?Hr(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var Ie=(t,s,n)=>Vr(t,typeof s!="symbol"?s+"":s,n);import{r as a,j as e,M as gn,a as yn,b as qr,c as Yr,u as dt,t as Gr,d as Xr,e as Jr,R as vn,D as Zr,f as Qr,g as ea,h as js,i as ta,k as sa,B as na,l as ra,m as Xe,N as ps,n as aa}from"./vendor-CPghmr9Y.js";import{_ as ia}from"./terminal-PD6SznsC.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"]'))r(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"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(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 r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();const jn=a.createContext({ides:[],updateIdeChats:()=>{},screenshotMap:{},setScreenshotMap:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),wn=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ks(t){var n,r;let s=0;return"activeChat"in t&&(s+=4),(n=t.childSessions)!=null&&n.length&&(s+=2),t.workspace&&(s+=1),t.machine&&(s+=1),(r=t.agents)!=null&&r.length&&(s+=1),s}function as(t,s,n){if(n.type!=="adhdev-daemon")return n;const r={...n},i=s.version??n.version??t.version,o=s.serverVersion??t.serverVersion??n.serverVersion,c=s.versionMismatch===!0||t.versionMismatch===!0;return i&&(r.version=i),o&&(r.serverVersion=o),i&&o&&i===o?(delete r.versionMismatch,delete r.serverVersion,r):((s.versionMismatch===!0||c&&i&&o&&i!==o)&&(r.versionMismatch=!0),r)}function oa(t,s,n){var l,p,u,x,m,h,g;const r=Date.now(),i=new Set((n==null?void 0:n.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(b=>({...b,_lastUpdate:r}));const o=new Map;for(const b of s)o.set(b.id,b);for(const b of t){const w=o.get(b.id);if(!w){o.set(b.id,{...b,_lastUpdate:r});continue}const f=Ks(b),y=Ks(w);if(f>y){const k=(l=b.chats)!=null&&l.length?b.chats:w.chats,j=as(w,b,{...w,...b,chats:k,_lastUpdate:r});o.set(b.id,j)}else if(f<y){const k={};if(b.status&&b.status!==w.status&&(k.status=b.status),b.cdpConnected!==void 0&&(k.cdpConnected=b.cdpConnected),(p=b.chats)!=null&&p.length&&!((u=w.chats)!=null&&u.length)&&(k.chats=b.chats),b.machineNickname!==void 0&&b.machineNickname!==w.machineNickname&&(k.machineNickname=b.machineNickname),b.version!==void 0&&(k.version=b.version),b.serverVersion!==void 0&&(k.serverVersion=b.serverVersion),b.versionMismatch===!0&&(k.versionMismatch=!0),Object.keys(k).length>0){const j=as(w,b,{...w,...k,_lastUpdate:w._lastUpdate});o.set(b.id,j)}}else{const k=b.timestamp||r,j=w._lastUpdate||w.timestamp||0;if(k>=j){const v=(x=b.chats)!=null&&x.length?b.chats:w.chats,T=as(w,b,{...w,...b,chats:v,_lastUpdate:r});o.set(b.id,T)}else(m=b.chats)!=null&&m.length&&!((h=w.chats)!=null&&h.length)&&o.set(b.id,{...w,chats:b.chats})}}const c=new Set(t.map(b=>b.id)),d=new Set;for(const b of t){const w=b.daemonId||((g=b.id)==null?void 0:g.split(":")[0]);w&&d.add(w)}for(const[b,w]of o){const f=w.daemonId||b.split(":")[0];if(!d.has(f))continue;if(i.has(f)&&!c.has(b)){o.delete(b);continue}const y=r-(w._lastUpdate||w.timestamp||0);(w.transport==="pty"&&!c.has(b)&&y>1e4||w.transport==="acp"&&!c.has(b)&&y>1e4||w.transport==="cdp-page"&&!c.has(b)&&y>3e4)&&o.delete(b)}for(const[b,w]of o)r-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&o.delete(b);return Array.from(o.values())}function ca(t,s){if(t.length!==s.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==s[n])return!1;return!0}function la({children:t,connectionOverrides:s}){const[n,r]=a.useState([]),[i,o]=a.useState({}),[c,d]=a.useState(!1),[l,p]=a.useState([]),[u,x]=a.useState(void 0),m=a.useRef(n);a.useEffect(()=>{m.current=n},[n]);const h=a.useCallback((k,j)=>{r(v=>{let T=!1;const S=v.map(C=>C.id!==k||C.chats===j?C:(T=!0,{...C,chats:j}));return T?S:v})},[]),g=a.useCallback((k,j)=>{r(v=>{const T=v.length===0?k:oa(k,v,j);return ca(v,T)?v:T})},[]),b=a.useCallback(()=>d(!0),[]),w=a.useMemo(()=>({injectEntries:g,markLoaded:b,getIdes:()=>m.current}),[g,b]),f=s,y=a.useMemo(()=>({ides:n,updateIdeChats:h,screenshotMap:i,setScreenshotMap:o,initialLoaded:c,toasts:l,setToasts:p,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,userName:u,setUserName:x}),[n,h,i,c,l,f==null?void 0:f.wsStatus,f==null?void 0:f.isConnected,f==null?void 0:f.connectionStates,f==null?void 0:f.connectionTransports,f==null?void 0:f.showReconnected,f==null?void 0:f.retryConnection,f==null?void 0:f.isP2PActive,f==null?void 0:f.p2pStates,f==null?void 0:f.userRole,u]);return e.jsx(wn.Provider,{value:w,children:e.jsx(jn.Provider,{value:y,children:t})})}function jt(){return a.useContext(jn)}function Ws(){return a.useContext(wn)}function kn(t){const{baseUrl:s,getToken:n,onUnauthorized:r}=t;function i(d){return d.startsWith("http")?d:`${s}${d.startsWith("/")?"":"/"}${d}`}function o(d){const l=n==null?void 0:n(),p=i(d),u=d.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return l&&u.searchParams.set("token",l),!d.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(d,l={}){const p={"Content-Type":"application/json",...l.headers||{}},u=n==null?void 0:n();u&&(p.Authorization=`Bearer ${u}`);const x=i(d),m=await fetch(x,{...l,headers:p});if(m.status===401)throw r==null||r(),new Error("Unauthorized");if(!m.ok){const h=await m.json().catch(()=>({error:m.statusText}));throw new Error(h.error||`API Error: ${m.status}`)}return m.json()}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,l,p={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:l,payload:p})}),execTerminal:(d,l,p)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:l,name:p})}),sendAgentMessage:(d,l,p)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:l,message:p})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,l,p)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:l,action:p?"approve":"reject"})}),getMuxState:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/state`),getMuxSocketInfo:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/socket-info`),controlMux:(d,l,p={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:l,payload:p})}),getMuxEventsUrl:d=>o(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>o(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const da=kn({baseUrl:"http://localhost:3847"}),ua=a.createContext(da);function ha({client:t,children:s}){return e.jsx(ua.Provider,{value:t,children:s})}const ma={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Nn=a.createContext(ma);function pa({value:t,children:s}){return e.jsx(Nn.Provider,{value:t,children:s})}function Qe(){return a.useContext(Nn)}const xe={size:18};function Sn({size:t=xe.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 Cn({size:t=xe.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 ws({size:t=xe.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 xa({size:t=xe.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 fa({size:t=xe.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 ba({size:t=xe.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 Wt({size:t=xe.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 ga({size:t=xe.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 Gt({size:t=xe.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 In({size:t=xe.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 Mn({size:t=xe.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 rt({size:t=xe.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 Be({size:t=xe.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 ks({size:t=xe.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 ya({size:t=xe.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 xs({size:t=xe.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 Ns({size:t=xe.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 Ss({size:t=xe.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 ct({size:t=xe.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 Tn({size:t=xe.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 va({size:t=xe.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 An({size:t=xe.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 ja({size:t=xe.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 Cs({size:t=xe.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 wa({size:t=xe.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 Rn({size:t=xe.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 Ln({size:t=xe.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 ka({size:t=xe.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 Na({size:t=xe.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 Sa({size:t=xe.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 Xt({size:t=xe.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 Ca({size:t=xe.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 Ia({size:t=xe.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 Ma({size:t=xe.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 Ta({size:t=xe.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 Aa(t){const n=t.split(`
3
- `).map(d=>{if(!d.includes("\r"))return d;const l=d.split("\r").map(x=>x.trim()).filter(Boolean);if(l.length===0)return"";const p=l.filter(x=>x.startsWith("⏺"));if(p.length>0)return p[p.length-1];const u=l.filter(x=>!(/^[❯›>]\s*$/.test(x)||/^[^a-zA-Z0-9\s]\s*\S+[…\.]{1,3}\s*$/.test(x)&&x.length<40||/^[╭╰│├╮╯─═]+$/.test(x)));return u.length>0?u[u.length-1]:l[l.length-1]}).join(`
4
- `).split(`
5
- `),r={},i=[];let o=!1;for(const d of n){const l=d.trim();if(l===""){o=!1,i.push("");continue}if(/^❯\s*$/.test(l)||/^>\s*$/.test(l)||/^[✡-✩✪-✿⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏◆◇◐◑◒◓]\s*\S+[…\.]{1,3}\s*$/.test(l)||/^◐\s/.test(l)||/\/effort/.test(l)||/^⎿\s+(Tip|Note|Hint):/.test(l)||/^\?\s*(for\s*shortcuts|shortcuts)/.test(l)||/esc\s+to\s+interrupt|shift\+tab\s+to\s+cycle|accept\s+edits\s+on/i.test(l)||/Brewing[…\.]{0,3}\s*\d*$/i.test(l)||/^[✢✳✶✻⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏◆◇✦\s]+$/.test(l)||/^Auto-updating/i.test(l))continue;if(/^[⏺●·⏵]/.test(d)){const u=d.match(/^[⏺●·]\s*([A-Za-z][A-Za-z0-9_]*)\s*[\(\[]/);if(u)r[u[1]]=(r[u[1]]||0)+1;else{const x=d.replace(/^[⏺●·⏵]\s*/,"").trim().slice(0,40);x&&(r[x]=(r[x]||0)+1)}o=!0;continue}if(/^[\s]*[╭╰│├╮╯]/.test(d)||/^[╭╰│├╮╯─]+/.test(l)||/^\s+[⊙✓✗○◎▸►✦]/.test(d)||o&&/^\s{2,}/.test(d))continue;o=!1;const p=d.replace(/^❯\s+/,"");i.push(p)}const c=i.join(`
6
- `).replace(/\n{3,}/g,`
7
-
8
- `).trim();return{toolCounts:r,textContent:c,hasTools:Object.keys(r).length>0}}function fs(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Ra(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ot(t,s){const n=t,r=typeof n.content=="string"?n.content:Array.isArray(n.content)?n.content.map(o=>(o==null?void 0:o.text)||"").join(`
9
- `):String(n.content||"");return[n.id?`id:${n.id}`:"",n._localId?`local:${n._localId}`:"",n._turnKey?`turn:${n._turnKey}`:"",typeof n.index=="number"?`msgIndex:${n.index}`:"",n.timestamp?`ts:${n.timestamp}`:"",n.role?`role:${n.role}`:"",r?`content:${r.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const Os=700,La=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(gn,{remarkPlugins:[yn],children:s.text}),e.jsx("span",{className:"action-time",children:fs(s.timestamp)})]})},(t,s)=>t.log===s.log),Da=a.memo(function({message:s,receivedAt:n,agentName:r,userName:i,isCliMode:o,isExpanded:c,isTextExpanded:d,onToggleExpanded:l,onToggleTextExpanded:p}){var j;const u=(s.role||"").toLowerCase(),x=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),h=typeof s.content=="string"?s.content:(s.content||[]).map(v=>v.text||"").join(`
10
- `);if(m==="thought"){const v=((j=s.meta)==null?void 0:j.label)||"Thought";return e.jsxs("div",{className:"self-start chat-msg-thought",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx(Na,{size:13}),e.jsx("span",{children:v})]}),e.jsx("div",{className:"chat-msg-body",children:h})]})}if(m==="tool")return e.jsxs("div",{className:"self-start chat-msg-tool",children:[e.jsx("span",{className:"tool-icon",children:"⏺"}),e.jsx("span",{className:"tool-text",children:h.split(`
11
- `)[0].slice(0,80)})]});if(m==="terminal"){const v=s.meta||{},T=v.isRunning?"⏳":"✅",S=v.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:T}),e.jsx("span",{children:S})]}),e.jsx("pre",{className:"chat-msg-body",children:h})]})}if(m==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:h.slice(0,100)});const g=!x&&o?Aa(h):null,b=g?g.textContent:h,w=g?Object.entries(g.toolCounts):[],f=o&&!x&&!c&&b.length>Os,y=c?h:f&&!d?b.slice(0,Os):b,k=Ra(y);return e.jsxs("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${x?"self-end":"self-start"}`,children:[w.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 items-center mb-0.5",children:[w.map(([v,T])=>e.jsxs("span",{className:"chat-tool-badge",children:["⏺ ",v,T>1?` ×${T}`:""]},v)),(g==null?void 0:g.hasTools)&&e.jsx("button",{onClick:l,className:"text-[10px] text-text-muted px-1 py-px opacity-50",children:c?"Collapse":"Original"}),!b&&n!=null&&e.jsx("span",{className:"text-[10px] opacity-35 ml-0.5",children:fs(n)})]}),(b||x)&&e.jsxs("div",{className:`chat-bubble ${x?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${b?"mb-1.5":"mb-0"}`,children:[e.jsx("span",{className:"chat-sender",children:x?i||"You":r}),n!=null&&e.jsx("span",{className:"chat-time",children:fs(n)})]}),b&&e.jsx("div",{className:"chat-markdown",children:k?e.jsx(gn,{remarkPlugins:[yn,qr,Yr],children:y}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),f&&e.jsx("button",{onClick:p,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:d?"Collapse ↑":`Show more (${Math.round(b.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),_a=a.forwardRef(function({messages:s,actionLogs:n,agentName:r="Agent",userName:i,isCliMode:o=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:l={},emptyState:p,onLoadMore:u,isLoadingMore:x,hasMoreHistory:m,hiddenLiveCount:h=0,loadError:g},b){var F;const w=a.useRef(null),f=a.useRef(null),y=a.useRef(null),k=a.useRef(0),j=a.useRef(""),v=a.useRef(!1),T=a.useRef(null),S=a.useRef(!1),C=a.useRef(null),_=a.useRef(!1),[B,H]=a.useState(new Set),[E,N]=a.useState(new Set),A=a.useRef(!1),P=()=>{const K=w.current;return K?K.scrollHeight-K.scrollTop-K.clientHeight<200:!0},I=a.useCallback((K="auto")=>{const M=w.current;M&&M.scrollTo({top:M.scrollHeight,behavior:K})},[]),q=a.useCallback(()=>{var Q;const K=w.current,M=(Q=window.getSelection)==null?void 0:Q.call(window);if(!K||!M||M.rangeCount===0||M.isCollapsed){_.current=!1;return}const Y=M.anchorNode,X=M.focusNode;_.current=!!(Y&&X&&K.contains(Y)&&K.contains(X))},[]),L=a.useCallback((K="auto")=>{T.current!=null&&cancelAnimationFrame(T.current),T.current=requestAnimationFrame(()=>{T.current=null,I(K)})},[I]),$=s.length>0?`${s.length}:${(((F=s[s.length-1])==null?void 0:F.content)||"").length}`:"0:0";a.useEffect(()=>{const K=!v.current,M=j.current!==d;if(j.current=d,K||M){v.current=!0,A.current=!1,S.current=!0,_.current||L("auto"),k.current=s.length;return}s.length>k.current?!A.current&&!_.current&&L("auto"):P()&&!A.current&&!_.current&&L("auto"),k.current=s.length},[$,d,c,s.length,L]),a.useEffect(()=>()=>{T.current!=null&&cancelAnimationFrame(T.current),C.current!=null&&window.clearTimeout(C.current)},[]),a.useEffect(()=>{const K=f.current;if(!K)return;const M=()=>{C.current!=null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{S.current=!1,C.current=null},180)},Y=new ResizeObserver(()=>{S.current&&(_.current||(L("auto"),M()))});return Y.observe(K),()=>{Y.disconnect(),C.current!=null&&(window.clearTimeout(C.current),C.current=null)}},[L,d]),a.useImperativeHandle(b,()=>({scrollToBottom:(K="smooth")=>{I(K)}}),[I]),a.useEffect(()=>{const K=w.current;if(!K)return;let M;const Y=()=>{clearTimeout(M),M=setTimeout(()=>{A.current=!P()},50)};return K.addEventListener("scroll",Y,{passive:!0}),()=>{K.removeEventListener("scroll",Y),clearTimeout(M)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",q),()=>document.removeEventListener("selectionchange",q)),[q]);const D=a.useRef(0),V=a.useRef(!1);a.useEffect(()=>{const K=w.current;if(!K||!V.current||D.current===0)return;const M=K.scrollHeight-D.current;M>0&&(K.scrollTop=M),D.current=0,V.current=!1},[s.length]);const ae=()=>{const K=w.current;K&&(D.current=K.scrollHeight),V.current=!0,u==null||u()},G=a.useMemo(()=>{const K=s.map((Q,J)=>({type:"message",data:Q,index:J,ts:Q.receivedAt||l[ot(Q,J)]||0}));if(!n||n.length===0)return K;const M=[...n].sort((Q,J)=>Q.timestamp-J.timestamp).map((Q,J)=>({type:"action",data:Q,index:J,ts:Q.timestamp})),Y=[];let X=0;for(const Q of K){for(;X<M.length&&Q.ts>0&&M[X].ts<Q.ts;)Y.push(M[X++]);Y.push(Q)}for(;X<M.length;)Y.push(M[X++]);return Y},[s,n,l]),W=h>0||!!m,ee=h>0?`↑ Show ${Math.min(h,80)} earlier messages${h>80?` (${h} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return e.jsx("div",{ref:w,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:f,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..."}),W&&!x&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:ae,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&h===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:ee})}),G.length===0&&!W&&(p||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),G.map(K=>{if(K.type==="action"){const he=K.data;return e.jsx(La,{log:he},`action-${K.index}`)}const M=K.data,Y=K.index,X=ot(M,Y),Q=M.receivedAt||l[X],J=`${d}-${X}`,oe=B.has(J),me=E.has(J);return e.jsx(Da,{message:M,receivedAt:Q,agentName:r,userName:i,isCliMode:o,isExpanded:oe,isTextExpanded:me,onToggleExpanded:()=>H(he=>{const pe=new Set(he);return oe?pe.delete(J):pe.add(J),pe}),onToggleTextExpanded:()=>N(he=>{const pe=new Set(he);return me?pe.delete(J):pe.add(J),pe})},`msg-${X}`)}),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:y})]})})}),Ea=a.memo(_a,(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);let Us=!1;const Dn=a.forwardRef(({onInput:t,onResize:s,fontSize:n=13,readOnly:r=!1},i)=>{const o=a.useRef(null),[c,d]=a.useState(null),l=a.useRef([]),p=a.useRef(!1),u=a.useRef(!1),x=a.useRef(!1),m=()=>{const h=o.current;if(h){p.current&&(h.clear(),p.current=!1);for(const g of l.current)h.write(g);l.current=[],u.current&&(h.fit(),u.current=!1),x.current&&(h.bumpResize(),x.current=!1)}};return a.useImperativeHandle(i,()=>({write:h=>{o.current?o.current.write(h):l.current.push(h)},clear:()=>{o.current?o.current.clear():(l.current=[],p.current=!0)},reset:()=>{o.current&&"reset"in o.current&&typeof o.current.reset=="function"?o.current.reset():(l.current=[],p.current=!0)},resize:(h,g)=>{o.current&&"resize"in o.current&&typeof o.current.resize=="function"&&o.current.resize(h,g)},fit:()=>{o.current?o.current.fit():u.current=!0},bumpResize:()=>{o.current?o.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const h=requestAnimationFrame(()=>{m()});return()=>cancelAnimationFrame(h)},[c]),a.useEffect(()=>{let h=!1;return ia(()=>import("./terminal-PD6SznsC.js").then(g=>g.i),__vite__mapDeps([0,1,2])).then(g=>{Us||(Us=!0,console.info("[CliTerminal] renderer module loaded: ghostty-web")),h||d(()=>g.GhosttyTerminalView)}).catch(g=>{console.error("[CliTerminal] failed to load terminal renderer",g)}),()=>{h=!0}},[]),c?e.jsx(c,{ref:o,onInput:t,onResize:s,fontSize:n,readOnly:r,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 Mt({label:t,value:s,sub:n,icon:r}){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:r}),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}),n&&e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function zs({value:t,max:s,label:n,color:r="#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)":r;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:n}),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:n}),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 Pa({cursorPos:t,viewportRef:s,imgRef:n}){var y;if(!t||!n.current)return null;const r=n.current,i=r.getBoundingClientRect(),o=(y=s.current)==null?void 0:y.getBoundingClientRect();if(!o)return null;const c=r.naturalWidth||i.width,d=r.naturalHeight||i.height,l=c/d,p=i.width/i.height;let u,x,m,h;l>p?(u=i.width,x=i.width/l,m=0,h=(i.height-x)/2):(x=i.height,u=i.height*l,m=(i.width-u)/2,h=0);const g=i.left-o.left+m+u*t.nx,b=i.top-o.top+h+x*t.ny,w=Math.max(8,Math.min(o.width-8,g)),f=Math.max(8,Math.min(o.height-8,b));return e.jsxs("div",{style:{position:"absolute",left:w-8,top:f-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 $a({inputMode:t,onToggleInputMode:s,isImeOpen:n,setIsImeOpen:r,isMenuOpen:i,setIsMenuOpen:o,imeText:c,setImeText:d,handleImeSubmit:l,isConnActive:p,zoom:u,isMobile:x,mobileFillZoom:m,onZoomOut:h,onZoomReset:g,onZoomIn:b,transportType:w,screenshotUsage:f,lastActionStatus:y}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:k=>k.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[e.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${t==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[e.jsx("span",{className:"text-sm",children:t==="mouse"?"🖱️":"👆"}),e.jsx("span",{className:`text-[10px] font-bold ${t==="mouse"?"text-blue-400":"text-slate-400"}`,children:t==="mouse"?"Mouse":"Touch"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{onClick:()=>{r(k=>!k),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"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:"⌨️"})}),n&&e.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:e.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:k=>k.stopPropagation(),onChange:k=>d(k.target.value),onKeyDown:k=>{l(k)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),e.jsx("div",{className:"relative",children:e.jsx("div",{onClick:()=>{o(k=>!k),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${i?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:e.jsx("span",{className:"text-sm",children:"⚙️"})})}),e.jsx("div",{className:"w-px h-[18px] bg-white/10"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[e.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),e.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),u>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),w==="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"}),w==="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"}),f&&f.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:f.budgetExhausted?"#ef4444":"#c4b5fd",background:f.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:f.budgetExhausted?"TURN blocked":`TURN ${f.dailyUsedMinutes}/${f.dailyBudgetMinutes}m`}),y&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),i&&e.jsxs("div",{onTouchStart:k=>k.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(x?m:1)+.01?x?"FILL":"FIT":`${Math.round(u*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:k=>{k.stopPropagation(),h()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),e.jsx("button",{onClick:k=>{k.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:x?"FILL":"FIT"}),e.jsx("button",{onClick:k=>{k.stopPropagation(),b()},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 Ba({waitingLabel:t,waitingHint:s,transportType:n}){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}),n==="relay"&&e.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Ka(){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 Fs(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 Nt(t,s){const n=a.useRef(null),r=a.useRef(0);a.useEffect(()=>{if(!Ka())return;r.current+=1;const i=n.current;if(!i){console.debug(`[render-trace] ${t}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,d])=>[c,Fs(d)]))}),n.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}#${r.current}`,{changed:o,snapshot:Object.fromEntries(o.map(c=>[c,Fs(s[c])]))}),n.current=s})}function Wa({containerRef:t,viewportRef:s,imgRef:n,inputMode:r,setInputMode:i,minZoom:o,zoomRef:c,panXRef:d,panYRef:l,setPanX:p,setPanY:u,setZoom:x,lastWheelTimeRef:m,onAction:h,setLastActionStatus:g,spawnRippleFromNormalized:b,clampPan:w,isMobile:f,mobileFillZoom:y}){const[k,j]=a.useState(null),v=a.useRef(null),T=a.useRef(null),S=a.useRef(null),C=a.useRef(!1),_=a.useRef(null),B=a.useRef(0),H=a.useRef(null),E=a.useRef(1),N=a.useRef({x:0,y:0}),A=a.useRef(!1),P=a.useRef(r),I=a.useRef(h),q=()=>{if(v.current)return;const D={nx:.5,ny:.5};v.current=D,j(D)};return a.useEffect(()=>{P.current=r,r==="mouse"&&q()},[r]),a.useEffect(()=>{I.current=h},[h]),a.useEffect(()=>{const D=t.current;if(!D)return;const V=K=>{if(!n.current)return null;const M=n.current.getBoundingClientRect();return!M.width||!M.height?null:{nx:Math.max(0,Math.min(1,(K.clientX-M.left)/M.width)),ny:Math.max(0,Math.min(1,(K.clientY-M.top)/M.height))}},ae=(K,M)=>{if(!n.current)return{dnx:0,dny:0};const Y=n.current,X=Y.getBoundingClientRect(),Q=Y.naturalWidth||X.width,J=Y.naturalHeight||X.height,oe=Q/J,me=X.width/X.height;let he,pe;return oe>me?(he=X.width,pe=X.width/oe):(pe=X.height,he=X.height*oe),{dnx:K/he,dny:M/pe}},G=(K,M,Y)=>{if(Y<=1.05)return;const X=-(K-.5)*100,Q=-(M-.5)*100,J=w(X,Q,Y);(Math.abs(J.x-d.current)>.1||Math.abs(J.y-l.current)>.1)&&(p(J.x),u(J.y),d.current=J.x,l.current=J.y)},W=K=>{const M=s.current;if(M&&K.target instanceof Node&&M.contains(K.target))K.preventDefault();else return;if(K.touches.length===1){const Y=K.touches[0];T.current={x:Y.clientX,y:Y.clientY,time:Date.now()},S.current={x:Y.clientX,y:Y.clientY},A.current||(C.current=!1),_.current=setTimeout(()=>{if(!C.current&&!A.current)if(C.current=!0,P.current==="mouse"){const X=v.current||{nx:.5,ny:.5};g("Right Click"),b(X.nx,X.ny,"right"),I.current("input_click",{...X,button:"right"}).catch(()=>{})}else{const X=V(Y);X&&(g("Right Click"),b(X.nx,X.ny,"right"),I.current("input_click",{...X,button:"right"}).catch(()=>{}))}},500);return}if(K.touches.length===2){_.current&&clearTimeout(_.current),C.current=!0,A.current=!0;const Y=K.touches[1].clientX-K.touches[0].clientX,X=K.touches[1].clientY-K.touches[0].clientY;H.current=Math.sqrt(Y*Y+X*X),E.current=c.current,N.current={x:(K.touches[0].clientX+K.touches[1].clientX)/2,y:(K.touches[0].clientY+K.touches[1].clientY)/2}}},ee=K=>{const M=s.current;if(M&&K.target instanceof Node&&M.contains(K.target)&&K.preventDefault(),K.touches.length===1&&S.current){const Y=K.touches[0],X=Y.clientX-S.current.x,Q=Y.clientY-S.current.y;if(!C.current&&T.current){const J=Y.clientX-T.current.x,oe=Y.clientY-T.current.y;Math.sqrt(J*J+oe*oe)>8&&(C.current=!0,_.current&&clearTimeout(_.current))}if(C.current)if(P.current==="mouse"){const J=ae(X,Q),oe=v.current||{nx:.5,ny:.5},me=Math.max(0,Math.min(1,oe.nx+J.dnx)),he=Math.max(0,Math.min(1,oe.ny+J.dny));v.current={nx:me,ny:he},j({nx:me,ny:he}),g(`Cursor: ${Math.round(me*100)}%, ${Math.round(he*100)}%`),G(me,he,c.current);const pe=Date.now();pe-m.current>=30&&(m.current=pe,I.current("input_mouseMoved",{nx:me,ny:he}).catch(()=>{}))}else if(c.current>1){const J=s.current;if(J){const oe=J.clientWidth,me=J.clientHeight,he=d.current+X/oe*100,pe=l.current+Q/me*100,Z=w(he,pe,c.current);p(Z.x),u(Z.y),d.current=Z.x,l.current=Z.y}}else{const J=V(Y);if(J){const oe=Date.now();oe-m.current>=40&&(m.current=oe,g("Scroll"),I.current("input_wheel",{nx:J.nx,ny:J.ny,deltaX:Math.round(-X*2.5),deltaY:Math.round(-Q*2.5)}).catch(()=>{}))}}S.current={x:Y.clientX,y:Y.clientY};return}if(K.touches.length===2&&H.current!==null){const Y=K.touches[1].clientX-K.touches[0].clientX,X=K.touches[1].clientY-K.touches[0].clientY,J=Math.sqrt(Y*Y+X*X)/H.current,oe=(K.touches[0].clientX+K.touches[1].clientX)/2,me=(K.touches[0].clientY+K.touches[1].clientY)/2,he=oe-N.current.x,pe=me-N.current.y,Z=Math.abs(J-1)>.03;if(P.current==="mouse"){if(Z){const R=Math.max(o,Math.min(5,E.current*J));x(R),c.current=R}else if(Math.abs(he)>2||Math.abs(pe)>2){const R=v.current||{nx:.5,ny:.5},O=Date.now();O-m.current>=30&&(m.current=O,g("Scroll"),I.current("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(-he*3),deltaY:Math.round(-pe*3)}).catch(()=>{}))}}else{const R=Math.max(o,Math.min(5,E.current*J));x(R),c.current=R;const O=s.current;if(O&&R>1){const te=O.clientWidth,ne=O.clientHeight,de=d.current+he/te*100,re=l.current+pe/ne*100,we=w(de,re,R);p(we.x),u(we.y),d.current=we.x,l.current=we.y}}N.current={x:oe,y:me}}},F=K=>{var M;if(_.current&&clearTimeout(_.current),H.current=null,K.touches.length===1&&A.current){const Y=K.touches[0];T.current={x:Y.clientX,y:Y.clientY,time:Date.now()},S.current={x:Y.clientX,y:Y.clientY},C.current=!0;return}if(K.touches.length===0){if(A.current){A.current=!1,C.current=!1;return}if(K.changedTouches.length===1&&!C.current){const Y=K.changedTouches[0],X=Date.now(),Q=X-(((M=T.current)==null?void 0:M.time)||0);if(Q<60||Q>400){C.current=!1;return}if(T.current){const J=Y.clientX-T.current.x,oe=Y.clientY-T.current.y;if(Math.sqrt(J*J+oe*oe)>12){C.current=!1;return}}if(P.current==="mouse"){const J=v.current||V(Y);J&&(g(`Click: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),b(J.nx,J.ny,"left"),I.current("input_click",{...J}).catch(()=>{}))}else{const J=V(Y);if(!J)return;X-B.current<300?(g("Double tap"),b(J.nx,J.ny,"double"),I.current("input_click",{...J,clickCount:2}).catch(()=>{}),B.current=0):(g(`Tap: ${Math.round(J.nx*100)}%, ${Math.round(J.ny*100)}%`),b(J.nx,J.ny,"left"),I.current("input_click",{...J}).catch(()=>{}),B.current=X)}}C.current=!1}};return D.addEventListener("touchstart",W,{passive:!1}),D.addEventListener("touchmove",ee,{passive:!1}),D.addEventListener("touchend",F,{passive:!1}),()=>{D.removeEventListener("touchstart",W),D.removeEventListener("touchmove",ee),D.removeEventListener("touchend",F),_.current&&clearTimeout(_.current)}},[t,s,n,o,c,d,l,p,u,x,m,g,b,w]),{cursorPos:k,cursorPosRef:v,handleToggleInputMode:()=>{i(D=>{const V=D==="touch"?"mouse":"touch";return V==="mouse"&&q(),V})},handleZoomReset:()=>{const D=f?y:1;x(D),c.current=D,p(0),u(0),d.current=0,l.current=0}}}function _n({onAction:t,addLog:s,connState:n,connScreenshot:r,screenshotUsage:i,transportType:o}){const c=a.useRef(null),d=a.useRef(null),l=a.useRef(null),[p,u]=a.useState(null),[x,m]=a.useState(""),[,h]=a.useState(!1),[g,b]=a.useState([]),w=a.useRef(0),[f,y]=a.useState(!1),[k,j]=a.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[T,S]=a.useState(v?"mouse":"touch"),[C,_]=a.useState(1),B=a.useRef(!1),[H,E]=a.useState(1),[N,A]=a.useState(0),[P,I]=a.useState(0);Nt("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:T,zoom:H,panX:N,panY:P,isMenuOpen:f,isImeOpen:k});const q=a.useRef(0),L=a.useRef(H),$=a.useRef(N),D=a.useRef(P);a.useEffect(()=>{L.current=H},[H]),a.useEffect(()=>{$.current=N},[N]),a.useEffect(()=>{D.current=P},[P]),a.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const V=n==="connected",ae=r,G=V?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",W=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!v||B.current||!ae)return;const Z=l.current,R=d.current;if(!Z||!R)return;const O=()=>{const te=R.clientWidth,ne=R.clientHeight,de=Z.naturalWidth,re=Z.naturalHeight;if(!de||!re||!te||!ne)return;const we=Math.min(te/de,ne/re),Me=Math.max(te/de,ne/re)/we;Me>1.01&&(_(Me),E(Me),L.current=Me),B.current=!0};Z.complete&&Z.naturalWidth?O():Z.addEventListener("load",O,{once:!0})},[ae,v]);const ee=.5;a.useEffect(()=>{H<=ee&&(A(0),I(0))},[H,ee]);const F=(Z,R,O)=>{if(O<=ee)return{x:0,y:0};const te=(O-1)/(2*O)*100,ne=(O-1)/(2*O)*100;return{x:Math.max(-te,Math.min(te,Z)),y:Math.max(-ne,Math.min(ne,R))}},K=(Z,R)=>{if(!l.current)return null;const O=l.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(Z-O.left)/O.width)),ny:Math.max(0,Math.min(1,(R-O.top)/O.height))}},M=(Z,R,O)=>{const te=d.current;if(!te)return;const ne=te.getBoundingClientRect(),de=++w.current;b(re=>[...re,{id:de,x:Z-ne.left,y:R-ne.top,type:O}]),setTimeout(()=>b(re=>re.filter(we=>we.id!==de)),600)},Y=(Z,R,O)=>{const te=l.current,ne=d.current;if(!te||!ne)return;const de=te.getBoundingClientRect(),re=ne.getBoundingClientRect(),we=te.naturalWidth||de.width,Ke=te.naturalHeight||de.height,Me=we/Ke,De=de.width/de.height;let Le,Ye,Oe,ze;Me>De?(Le=de.width,Ye=de.width/Me,Oe=0,ze=(de.height-Ye)/2):(Ye=de.height,Le=de.height*Me,Oe=(de.width-Le)/2,ze=0);const U=de.left-re.left+Oe+Le*Z,z=de.top-re.top+ze+Ye*R,se=++w.current;b(ie=>[...ie,{id:se,x:U,y:z,type:O}]),setTimeout(()=>b(ie=>ie.filter(fe=>fe.id!==se)),600)},X=async Z=>{var O;const R=K(Z.clientX,Z.clientY);if(R){u(`Click: ${Math.round(R.nx*100)}%, ${Math.round(R.ny*100)}%`),M(Z.clientX,Z.clientY,"left"),(O=c.current)==null||O.focus();try{const te=await t("input_click",{nx:R.nx,ny:R.ny});te!=null&&te.success||s(`❌ Click failed: ${te==null?void 0:te.error}`)}catch(te){s(`❌ Click error: ${te.message||te}`)}}},Q=async(Z,R,O,te=0)=>{try{await t("input_key",{type:O?"char":"keyDown",key:Z,code:R,text:O?Z:void 0,unmodifiedText:O?Z:void 0,modifiers:te})}catch(ne){s(`❌ Key error: ${ne.message||ne}`)}},J=async Z=>{if(Z.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Z.key)&&Z.preventDefault();let O=0;Z.altKey&&(O|=1),Z.ctrlKey&&(O|=2),Z.metaKey&&(O|=4),Z.shiftKey&&(O|=8),u(`Key: ${Z.key}`),await Q(Z.key,Z.code,Z.key.length===1,O)},oe=async Z=>{if(Z.key==="Enter"){if(Z.nativeEvent.isComposing)return;if(x){const R=x;m(""),u(`IME Sent: ${R}`);try{const O=await t("input_type",{text:R});O!=null&&O.success||s(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){s(`❌ IME error: ${O.message}`)}}else u("Key: Enter"),await Q("Enter","Enter",!1)}};a.useEffect(()=>{const Z=c.current;if(!Z)return;const R=O=>{var te;if((te=l.current)!=null&&te.contains(O.target)){O.preventDefault();const ne=Date.now();if(ne-q.current<40)return;q.current=ne;const de=K(O.clientX,O.clientY);if(!de)return;u(`Scroll: ${Math.round(O.deltaY)}`),t("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return Z.addEventListener("wheel",R,{passive:!1}),()=>Z.removeEventListener("wheel",R)},[t]);const{cursorPos:me,handleToggleInputMode:he,handleZoomReset:pe}=Wa({containerRef:c,viewportRef:d,imgRef:l,inputMode:T,setInputMode:S,minZoom:ee,zoomRef:L,panXRef:$,panYRef:D,setPanX:A,setPanY:I,setZoom:E,lastWheelTimeRef:q,onAction:t,setLastActionStatus:u,spawnRippleFromNormalized:Y,clampPan:F,isMobile:v,mobileFillZoom:C});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:J,onContextMenu:Z=>Z.preventDefault(),onFocus:()=>h(!0),onBlur:()=>h(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[ae?e.jsx("img",{ref:l,src:ae,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${H}) translate(${N}%, ${P}%)`,transformOrigin:"center center",cursor:T==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:X,onContextMenu:Z=>Z.preventDefault(),onDragStart:Z=>Z.preventDefault()}):e.jsx(Ba,{waitingLabel:G,waitingHint:W,transportType:o}),T==="mouse"&&ae&&e.jsx(Pa,{cursorPos:me,viewportRef:d,imgRef:l}),g.map(Z=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Z.type];return e.jsxs("div",{style:{position:"absolute",left:Z.x,top:Z.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 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(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Z.id)})]}),e.jsx($a,{inputMode:T,onToggleInputMode:he,isImeOpen:k,setIsImeOpen:j,isMenuOpen:f,setIsMenuOpen:y,imeText:x,setImeText:m,handleImeSubmit:oe,isConnActive:V,zoom:H,isMobile:v,mobileFillZoom:C,onZoomOut:()=>E(Z=>Math.max(.5,Z-.25)),onZoomReset:pe,onZoomIn:()=>E(Z=>Math.min(5,Z+.25)),transportType:o,screenshotUsage:i,lastActionStatus:p}),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 Oa({screenshotUrl:t,mode:s="preview",zoom:n=100,interactive:r=!1,connectionState:i,onDismiss:o,onClickAt:c,onKeyDown:d,badge:l,emptyMessage:p,aspectRatio:u,className:x,style:m}){const h=a.useRef(null),g=a.useCallback(b=>{if(!r||!c||!h.current)return;const w=h.current,f=w.getBoundingClientRect(),y=(b.clientX-f.left)/f.width*w.naturalWidth,k=(b.clientY-f.top)/f.height*w.naturalHeight;c(y,k,w.naturalWidth,w.naturalHeight)},[r,c]);return s==="preview"?t?e.jsxs("div",{className:`relative rounded-xl overflow-hidden border border-border-subtle bg-bg-secondary ${x||""}`,style:{aspectRatio:u||"16/9",...m},children:[e.jsx("img",{ref:h,src:t,alt:"IDE Screenshot",className:"w-full h-full object-cover"}),o&&e.jsx("button",{onClick:o,className:"absolute top-2.5 right-2.5 bg-black/50 border-none text-white w-5 h-5 rounded-full text-[10px] z-10 cursor-pointer flex items-center justify-center",children:"✕"})]}):null:t?e.jsxs("div",{className:`${r?"screenshot-interactive":""} ${x||""} relative h-full flex items-center justify-center overflow-auto`,tabIndex:r?0:void 0,onKeyDown:r?d:void 0,style:m,children:[e.jsx("img",{ref:h,src:t,alt:"IDE Screenshot",onClick:r?g:void 0,className:"max-w-full max-h-full object-contain",style:{...r?{cursor:"crosshair"}:{},...n!==100?{transform:`scale(${n/100})`,transformOrigin:"center center"}:{}}}),l&&e.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/70 text-white px-3.5 py-1.5 rounded-[20px] text-xs font-semibold backdrop-blur-sm",children:l})]}):e.jsxs("div",{className:`flex items-center justify-center flex-col gap-2 h-full text-text-muted ${x||""}`,style:m,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.22)] mb-1",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("p",{className:"text-base",children:p||"Waiting for screenshot stream..."}),i&&e.jsxs("p",{className:"text-[13px] mt-2 opacity-50",children:["P2P: ",i]}),e.jsx("style",{children:`
35
- @keyframes remote-float {
36
- 0% { transform: translateY(0px); }
37
- 50% { transform: translateY(-7px); }
38
- 100% { transform: translateY(0px); }
39
- }
40
- `})]})}function En({activeConv:t,onModalButton:s}){const[n,r]=a.useState(null);if(a.useEffect(()=>{r(null)},[t.modalMessage,t.status]),t.status!=="waiting_approval"||!t.modalButtons)return null;const i=c=>{n||(r(c),s(c))},o=c=>c.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(Ss,{size:14})," ",n?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((c,d)=>{const l=o(c).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(l),u=/^(reject|deny|delete|remove|abort)/.test(l),x=n===c,m=n!==null;return e.jsx("button",{onClick:()=>i(c),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"bg-white font-extrabold":u?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${m&&!x?"opacity-40":"opacity-100"} ${m?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)"}:void 0,children:x?"⏳ ...":o(c)},d)})})]})]})}const Hs=new Map,Ua={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",antigravity:"#f97316",windsurf:"#34d399"};function za({ideId:t,sessionId:s,ideType:n,providerType:r,displayLabel:i,controls:o,controlValues:c,serverModel:d,serverMode:l}){const{sendCommand:p}=Qe(),u=`${t}:${s||r}`,x=Ua[r]||"#94a3b8",[m,h]=a.useState({}),g=a.useRef(0),b={...d?{model:d}:{},...l?{mode:l}:{},...c||{},...Date.now()<g.current?m:{}};a.useEffect(()=>{c&&Date.now()>g.current&&h({})},[c]);const[w,f]=a.useState(Hs.get(u)||{}),[y,k]=a.useState(null),[j,v]=a.useState(null),T=a.useCallback(async(N,A={})=>{const P={...A,...s&&{targetSessionId:s}};return await p(t,N,P)},[t,s,p]);if(!o||o.length===0)return null;const S=o.filter(N=>N.placement==="bar").sort((N,A)=>(N.order??50)-(A.order??50));if(S.length===0)return null;const C=async N=>{var P,I,q;if(y===N.id){k(null);return}if((((P=N.options)==null?void 0:P.map(L=>L.value))||w[N.id]||[]).length>0){k(N.id);return}if(N.dynamic&&N.listScript){v(N.id);try{const L=await T(N.listScript==="listModels"?"list_extension_models":N.listScript==="listModes"?"list_extension_modes":N.listScript,{agentType:r,ideType:n}),D=((L==null?void 0:L.models)||(L==null?void 0:L.modes)||((I=L==null?void 0:L.result)==null?void 0:I.models)||((q=L==null?void 0:L.result)==null?void 0:q.modes)||(L==null?void 0:L.options)||[]).map(V=>typeof V=="string"?V:(V==null?void 0:V.name)||(V==null?void 0:V.id)||(V==null?void 0:V.value)||String(V));f(V=>{const ae={...V,[N.id]:D};return Hs.set(u,ae),ae}),k(N.id)}catch{}finally{v(null)}}},_=async(N,A)=>{k(null),h(P=>({...P,[N.id]:A})),g.current=Date.now()+5e3;try{if(!N.setScript)return;const P=is(N.setScript,r);await T(P,{agentType:r,ideType:n,model:N.id==="model"?A:void 0,mode:N.id==="mode"?A:void 0,value:A})}catch{}},B=async N=>{var $;const A=(($=N.options)==null?void 0:$.map(D=>D.value))||w[N.id]||[];if(A.length===0)return;const P=String(b[N.id]||""),q=(A.indexOf(P)+1)%A.length,L=A[q];if(typeof L=="string"){h(D=>({...D,[N.id]:L})),g.current=Date.now()+5e3;try{if(!N.setScript)return;const D=is(N.setScript,r);await T(D,{agentType:r,ideType:n,value:L})}catch{}}},H=async N=>{const P=!b[N.id];h(I=>({...I,[N.id]:P})),g.current=Date.now()+5e3;try{if(!N.setScript)return;const I=is(N.setScript,r);await T(I,{agentType:r,ideType:n,value:P})}catch{}},E=async N=>{if(N.invokeScript)try{await T("invoke_extension_script",{agentType:r,ideType:n,scriptName:N.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-[var(--surface-primary)]",children:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:x},children:i}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),S.map(N=>{var L;const A=String(b[N.id]||""),P=y===N.id,I=j===N.id,q=((L=N.options)==null?void 0:L.map($=>$.value))||w[N.id]||[];switch(N.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:P?`${x}55`:"transparent",border:"1px solid",color:A?"var(--text-primary)":"var(--text-muted)"},onClick:()=>C(N),children:[N.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:N.icon}),I?"...":A||N.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),P&&q.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>k(null)}),e.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:N.label.toUpperCase()}),q.map($=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:$===A?`${x}18`:"transparent",color:$===A?x:"var(--text-secondary)",fontWeight:$===A?600:400,borderLeft:$===A?`2px solid ${x}`:"2px solid transparent"},onMouseEnter:D=>{D.currentTarget.style.background=`${x}12`},onMouseLeave:D=>{D.currentTarget.style.background=$===A?`${x}18`:"transparent"},onClick:()=>_(N,$),children:$},$))]})]})]},N.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:A?"var(--text-primary)":"var(--text-muted)"},onClick:()=>B(N),title:`Click to cycle: ${q.join(" → ")}`,children:[N.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:N.icon}),A||N.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},N.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:A?`${x}44`:"transparent",background:A?`${x}14`:"var(--surface-tertiary)",color:A?x:"var(--text-muted)"},onClick:()=>H(N),children:[N.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:N.icon}),N.label]},N.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:()=>E(N),children:[N.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:N.icon}),N.label]},N.id);default:return null}})]})}function is(t,s){return{setModel:"set_extension_model",setMode:"set_extension_mode",setThinkingLevel:"set_thought_level"}[t]||t}const Fa=a.memo(function({contextKey:s,panelLabel:n,isSending:r,onSend:i}){const o=a.useRef(null),[c,d]=a.useState("");a.useEffect(()=>{d("")},[s]);const l=()=>{const p=c.trim();!p||r||(d(""),i(p))};return e.jsx("div",{className:"dashboard-input-area px-3 py-2.5 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:o,type:"text",placeholder:`Send message to ${n}...`,value:c,onChange:p=>d(p.target.value),onPaste:p=>{const u=p.clipboardData.getData("text");u&&d(x=>x+u),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),l()}},onBlur:p=>{if(window.innerWidth<768){const u=p.relatedTarget;if((u==null?void 0:u.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:l,disabled:!c.trim()||r,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${c.trim()&&!r?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:c.trim()&&!r?{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:c.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var Ha=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Va(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function _e(t,s){if(Va(s==null?void 0:s.activeModal))return"waiting_approval";const n=String(t||"idle").trim().toLowerCase();return n==="waiting_approval"?"waiting_approval":Ha.has(n)?"generating":n==="error"?"error":n==="stopped"?"stopped":n==="starting"?"starting":n==="panel_hidden"?"panel_hidden":n==="not_monitored"?"not_monitored":n==="disconnected"?"disconnected":"idle"}function Pn(t){return _e(t)==="generating"}function Ne(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function qa(t){if(t<60)return`${Math.round(t)}s`;const s=Math.floor(t/60);if(s<60)return`${s}m`;const n=Math.floor(s/60),r=s%60;if(n<24)return r>0?`${n}h ${r}m`:`${n}h`;const i=Math.floor(n/24),o=n%24;return`${i}d ${o}h`}function Vs(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function $n(t,s){const n=typeof s=="string"?s.trim():"";if(n)return n;const r=typeof t=="string"?t.trim():"";if(!r)return"";const i=r.replace(/[\\/]+$/,""),o=i.split(/[\\/]/).filter(Boolean);return o[o.length-1]||i}function Ya(t){if(t.length>16&&/^[a-f0-9]+$/i.test(t))return`Machine-${t.substring(0,8)}`;if(t.includes("_")){const s=t.split("_"),n=s[s.length-1];return n.length>12?`Machine-${n.substring(0,8)}`:n}return t}function Ga(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Xa(t){return Ya(t.trim().replace(/\.local$/i,""))}function Ja(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function Bn(t,s={}){var i,o;const n=[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&&!Ga(c));if(n&&n!=="Unknown")return Xa(n);const r=s.fallbackId||t.id;return r?`Machine-${r.substring(0,8)}`:s.fallbackLabel||"Machine"}function qe(t,s={}){return Ja(t)||Bn(t,s)}function Ot(t){return t.transport==="pty"}function xt(t){return t.transport==="acp"}function qs(t,s){return Ne(t)}function Za(t,s,n){const r=(t||"").trim().toLowerCase();if(!r)return!0;const i=(s||"").trim().toLowerCase(),o=(n||"").trim().toLowerCase(),c=Ne(n||"").trim().toLowerCase();return r===i||r===o||r===c}function Qa(t){return _e(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function ei(t){if(!Array.isArray(t)||t.length<=1)return t;const s=new Map,n=["generating","waiting_approval","connected","idle","panel_hidden"];for(const r of t){const i=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),o=s.get(i),c=_e(r.status);if(!o){s.set(i,{...r,status:c});continue}const d=n.indexOf(o.status||"idle"),l=n.indexOf(c||"idle");l>=0&&(d<0||l<d)&&s.set(i,{...r,status:c})}return Array.from(s.values())}function os(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 ti(t){var n,r;const s=(r=(n=t==null?void 0:t.messages)==null?void 0:n.at)==null?void 0:r.call(n,-1);return s&&(os(s.timestamp)||os(s.receivedAt)||os(s.createdAt))||0}function si(t){return(t.recentLaunches||[]).reduce((n,r)=>Math.max(n,r.lastLaunchedAt||0),0)}function Ut(t){return Math.max(si(t),ti(t.activeChat))}function ni(t,s,n,r,i,o){const c=s-t;if(c!==0)return c;const d=n.localeCompare(r);return d!==0?d:i.localeCompare(o)}function ri(t,s){return ni(Ut(t),Ut(s),qe(t,{fallbackId:t.id}),qe(s,{fallbackId:s.id}),t.id,s.id)}function Kn({conversation:t,className:s="",onOpenNativeConversation:n,onOpenMachine:r}){var x;const i=dt(),o=t.daemonId||((x=t.ideId)==null?void 0:x.split(":")[0])||t.ideId,c=t.transport==="cdp-page"||t.transport==="cdp-webview",d=t.streamSource==="agent-stream"&&!!t.agentName,l=(()=>{var m,h;if(t.streamSource==="agent-stream"){const g=(h=(m=t.displaySecondary)==null?void 0:m.split("·")[0])==null?void 0:h.trim();if(g)return g}return Ne(t.ideType||"")})(),p=a.useCallback(()=>{if(r){r();return}o&&i("/dashboard",{state:{openMachineId:o}})},[o,i,r]),u=a.useCallback(()=>{if(n){n();return}const m=t.streamSource==="agent-stream"?t.nativeSessionId:t.sessionId;m&&i(`/dashboard?activeTab=${encodeURIComponent(m)}`)},[t.nativeSessionId,t.sessionId,t.streamSource,i,n]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[c&&e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:u,title:l,children:[e.jsx(Be,{size:12}),e.jsx("span",{children:l})]}),d&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:t.agentName,children:[e.jsx(ct,{size:12}),e.jsx("span",{children:t.agentName})]}),t.machineName&&e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:t.machineName,children:[e.jsx(ws,{size:12}),e.jsx("span",{children:t.machineName})]})]})}const Se=t=>t.transport==="pty",lt=(t,s)=>Se(t)?s||t.mode||"terminal":"chat",Wn=(t,s)=>Se(t)&&lt(t,s)==="terminal",ye=t=>t.transport==="acp";function Ys(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(`
41
- `).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 Gs(t){const s=[];for(const n of t){const r=Ys(n==null?void 0:n.content),i=n==null?void 0:n.role,o=!!(n!=null&&n._localId),c=s.findIndex(d=>(d==null?void 0:d.role)===i&&Ys(d==null?void 0:d.content)===r&&!!(d!=null&&d._localId)!==o);if(c>=0){if(o)continue;s.splice(c,1,n);continue}s.push(n)}return s}const ai=60,ii=60;function wt({activeConv:t,ideEntry:s,handleSendChat:n,isSendingChat:r=!1,handleFocusAgent:i,isFocusingAgent:o,actionLogs:c,userName:d,showMetaChips:l=!1}){const p=a.useRef(new Map),{sendCommand:u}=Qe();Nt("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:r});const x=a.useRef(new Map),m=a.useCallback(N=>(x.current.has(N)||x.current.set(N,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:ai}),x.current.get(N)),[]),h=a.useCallback((N,A)=>{const P=m(N);x.current.set(N,{...P,...A}),g(I=>I+1)},[m]),[,g]=a.useState(0),b=t.tabKey,w=m(b),f=w.messages,y=w.hasMore,k=w.error,j=Math.max(0,t.messages.length-w.visibleLiveCount),[v,T]=a.useState(!1),S=a.useCallback(async()=>{var P,I;if(v)return;const N=t.tabKey,A=m(N);if(t.messages.length>A.visibleLiveCount){h(N,{visibleLiveCount:Math.min(t.messages.length,A.visibleLiveCount+ii),error:null});return}T(!0),h(N,{error:null});try{const q=(s==null?void 0:s.daemonId)||((P=t.ideId)==null?void 0:P.split(":")[0])||"";if(!q){h(N,{hasMore:!1});return}const L=t.ideType||t.agentType||"",$=await u(q,"chat_history",{agentType:L,offset:A.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),D=($==null?void 0:$.result)??$;if(((I=D.messages)==null?void 0:I.length)>0){const V=m(N);h(N,{messages:[...D.messages,...V.messages],offset:V.offset+D.messages.length,hasMore:!!D.hasMore})}else h(N,{hasMore:!!D.hasMore})}catch(q){const L=(q==null?void 0:q.message)||"";L.includes("P2P not available")||L.includes("channel not open")||L.includes("P2P not connected")||L.includes("timeout")?h(N,{error:"Connection not ready — tap to retry"}):h(N,{hasMore:!1,error:"Failed to load history"})}finally{T(!1)}},[v,s,t,u,m,h]),{allMessages:C,receivedAtMap:_}=a.useMemo(()=>{const N=j>0?t.messages.slice(-w.visibleLiveCount):t.messages;if(f.length===0){const L=Gs(N),$={};return L.forEach((D,V)=>{const ae=`${t.tabKey}:${ot(D,V)}`;let G=D.receivedAt||p.current.get(ae)||0;G||(G=Date.now(),p.current.set(ae,G)),$[ot(D,V)]=G}),{allMessages:L,receivedAtMap:$}}const A=new Set(N.map(L=>`${L.role}:${(L.content||"").slice(0,100)}`)),P=f.filter(L=>!A.has(`${L.role}:${(L.content||"").slice(0,100)}`)),I=Gs([...P,...N]),q={};return I.forEach((L,$)=>{const D=`${t.tabKey}:${ot(L,$)}`;let V=L.receivedAt||p.current.get(D)||0;V||(V=Date.now(),p.current.set(D,V)),q[ot(L,$)]=V}),{allMessages:I,receivedAtMap:q}},[t.messages,t.tabKey,j,f,w.visibleLiveCount]),B=a.useMemo(()=>c.filter(N=>N.ideId===t.tabKey).sort((N,A)=>N.timestamp-A.timestamp),[c,t.tabKey]),H=t.displayPrimary||t.agentName||"Agent",E=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(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(ct,{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(xs,{size:14})," Open ",H," 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(Tn,{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(xs,{size:14})," Open ",H," 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"&&!v)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,v,H]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[l&&e.jsx(Kn,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(Ea,{messages:C,actionLogs:B,agentName:t.agentName||t.displayPrimary||"Agent",userName:d,isCliMode:Se(t)||ye(t),isWorking:t.status==="generating",contextKey:t.tabKey,receivedAtMap:_,onLoadMore:S,isLoadingMore:v,hasMoreHistory:y,hiddenLiveCount:j,loadError:k??void 0,emptyState:E}),!Wn(t)&&(()=>{const N=t.streamSource!=="agent-stream",A=N?t.ideType:t.agentType,P=N?s!=null&&s.type?Ne(s.type):Ne(t.ideType||""):t.agentName||Ne(t.agentType||""),I=!N&&(s!=null&&s.childSessions)&&s.childSessions.find($=>$.id===t.sessionId||$.providerType===t.agentType)||s,q=I==null?void 0:I.providerControls,L=I==null?void 0:I.controlValues;return e.jsx(za,{ideId:t.ideId,sessionId:t.sessionId,ideType:t.ideType,providerType:A,displayLabel:P,controls:q,controlValues:L,serverModel:(I==null?void 0:I.currentModel)||void 0,serverMode:(I==null?void 0:I.currentPlan)||void 0,acpConfigOptions:ye(t)?I==null?void 0:I.acpConfigOptions:void 0,acpModes:ye(t)?I==null?void 0:I.acpModes:void 0})})(),e.jsx(Fa,{contextKey:t.tabKey,panelLabel:H,isSending:r,onSend:n})]})}let On=jt;function Is(){return On()}class oi{constructor(){Ie(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,n){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(n),()=>{var r;(r=this.listeners.get(s))==null||r.delete(n)}}emit(s,...n){var r;(r=this.listeners.get(s))==null||r.forEach(i=>i(...n))}}let Un=new oi;class ci{sendPtyInput(s,n,r){return!1}sendPtyResize(s,n,r,i){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,n){return!1}get(s){}onScreenshot(s,n){return()=>{}}onRuntimeEvent(s,n){return()=>{}}requestRuntimeSnapshot(s,n){return Promise.resolve()}}let je=new ci;function li(t){t.dashboardWS&&(Un=t.dashboardWS),t.connectionManager&&(je=t.connectionManager),t.useDaemonsHook&&(On=t.useDaemonsHook)}function zn({activeConv:t,clearToken:s=0,terminalRef:n,handleSendChat:r,isSendingChat:i=!1,isVisible:o=!0}){var H;const c=a.useRef(null),{sendCommand:d,sendData:l}=Qe(),[p,u]=a.useState(""),[x,m]=a.useState(!1),h=a.useRef(0),g=a.useRef(!1),b=a.useRef(""),w=a.useRef(null),f=a.useRef(!1),y=a.useRef(null),k=t.tabKey,j=t.sessionId||"",v=t.daemonId||((H=t.ideId)==null?void 0:H.split(":")[0])||t.ideId||"",T=()=>{var E,N;h.current=0,g.current=!1,b.current="",w.current=null,f.current=!1,y.current!==null&&(cancelAnimationFrame(y.current),y.current=null),m(!1),(N=(E=n.current)==null?void 0:E.reset)==null||N.call(E)},S=()=>{var E,N;h.current=0,g.current=!1,b.current="",w.current=null,f.current=!1,y.current!==null&&(cancelAnimationFrame(y.current),y.current=null),m(!0),(N=(E=n.current)==null?void 0:E.reset)==null||N.call(E)},C=()=>{var N;if(y.current=null,!o)return;const E=b.current;E&&(b.current="",(N=n.current)==null||N.write(E))},_=E=>{E&&(b.current+=E,o&&y.current===null&&(y.current=requestAnimationFrame(C)))},B=(E,N=0,A,P)=>{var I,q,L,$,D;N>0&&h.current>=N||N===0&&g.current||(h.current=N,m(!0),typeof A=="number"&&typeof P=="number"&&A>0&&P>0&&((q=(I=n.current)==null?void 0:I.resize)==null||q.call(I,A,P)),($=(L=n.current)==null?void 0:L.reset)==null||$.call(L),E&&((D=n.current)==null||D.write(E)))};return a.useEffect(()=>{T()},[j]),a.useEffect(()=>{var N;if(!j)return;const E=((N=je.onRuntimeEvent)==null?void 0:N.call(je,j,A=>{if(!(!A||A.sessionId!==j)){if(A.type==="runtime_snapshot"){if(!o){w.current={text:A.text||"",seq:A.seq||0,cols:A.cols,rows:A.rows};return}B(A.text||"",A.seq||0,A.cols,A.rows);return}if(A.type==="session_output"){g.current=!0,typeof A.seq=="number"&&(h.current=Math.max(h.current,A.seq)),x||m(!0),typeof A.data=="string"&&_(A.data);return}if(A.type==="session_cleared"){if(!o){f.current=!0,b.current="",w.current=null;return}S()}}}))||(()=>{});return()=>{E()}},[v,j,n,o,x]),a.useEffect(()=>{var N,A,P;if(!j)return;v&&((N=je.getState)==null?void 0:N.call(je,v))==="connected"&&(m(!0),(A=je.requestRuntimeSnapshot)==null||A.call(je,v,j).catch(()=>{}));const E=(P=je.onStateChange)==null?void 0:P.call(je,(I,q)=>{var L;I!==v||q!=="connected"||(m(!0),(L=je.requestRuntimeSnapshot)==null||L.call(je,v,j).catch(()=>{}))});return()=>{E==null||E()}},[v,j,n]),a.useEffect(()=>{s&&T()},[s,k,n]),a.useEffect(()=>{u("")},[t.tabKey]),a.useEffect(()=>{var N;if(!o){(N=c.current)==null||N.blur();return}f.current&&(f.current=!1,S());const E=w.current;E&&(w.current=null,B(E.text,E.seq,E.cols,E.rows)),b.current&&y.current===null&&(y.current=requestAnimationFrame(C))},[o]),a.useEffect(()=>()=>{y.current!==null&&(cancelAnimationFrame(y.current),y.current=null)},[]),a.useEffect(()=>{const E=N=>{var P;const A=N.detail;A!=null&&A.sessionId&&A.sessionId!==j||x&&((P=n.current)==null||P.fit())};return window.addEventListener("adhdev:fit-cli-terminal",E),()=>{window.removeEventListener("adhdev:fit-cli-terminal",E)}},[x,j,n]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117]",children:[e.jsx(Dn,{ref:n,readOnly:!x||!o,onInput:E=>{x&&(l!=null&&l(v,{type:"pty_input",targetSessionId:j,data:E})||d(v,"pty_input",{targetSessionId:j,data:E}).catch(console.error))},onResize:(E,N)=>{x&&(l!=null&&l(v,{type:"pty_resize",targetSessionId:j,cols:E,rows:N})||d(v,"pty_resize",{targetSessionId:j,cols:E,rows:N,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:p,disabled:!x||!o||i,onChange:E=>u(E.target.value),onPaste:E=>{const N=E.clipboardData.getData("text");N&&u(A=>A+N),E.preventDefault()},onKeyDown:E=>{if(E.key!=="Enter")return;if(E.nativeEvent.isComposing){E.preventDefault();return}E.preventDefault();const N=p.trim();!x||!N||i||(u(""),r(N))},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 E=p.trim();!x||!E||i||(u(""),r(E))},disabled:!x||!o||!p.trim()||i,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!i?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.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:p.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function di({wsStatus:t,showReconnected:s,loginUrl:n}){const r=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:[r&&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"&&(n?e.jsxs(e.Fragment,{children:["Session expired."," ",e.jsx("a",{href:n,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 ui({terminalBackend:t,isStandalone:s=!1}){return!s||!t||t.backend!=="xterm"?null:e.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",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.jsx("span",{children:"Terminal 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."})]})}function hi(t,s={}){if(!t)return"";const{suffix:n="",nowLabel:r="now",nowThreshold:i=60}=s,o=Date.now()-t,c=Math.floor(o/1e3);if(c<i)return r;const d=Math.floor(c/60);if(d<60)return`${d}m${n}`;const l=Math.floor(d/60);if(l<24)return`${l}h${n}`;const p=Math.floor(l/24);return p<7?`${p}d${n}`:new Date(t).toLocaleDateString()}const pt=t=>hi(t);function mi(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function St(t){const s=new Map,n=(r,i)=>{r&&s.set(r,{sessionId:r,...mi(i)})};for(const r of t)if(!r.daemonMode){n(r.sessionId,r);for(const i of r.childSessions||[])n(i.id,i)}return s}function kt(t,s){if(t.sessionId){const n=s.get(t.sessionId);if(n)return n}return{sessionId:t.sessionId||t.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function zt(t,s,n){const r=kt(t,s),i=r.inboxBucket==="needs_attention",o=r.inboxBucket==="working",c=r.inboxBucket==="task_complete"&&r.unread&&!(n!=null&&n.hideOpenTaskCompleteUnread&&(n!=null&&n.isOpenConversation));return{unread:c,requiresAction:i,isWorking:o,inboxBucket:i?"needs_attention":o?"working":c?"task_complete":"idle"}}function Fn(t,s,n){return zt(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:n==null?void 0:n.isOpenConversation}).unread}function pi(t,s,n){return kt(t,n||new Map).surfaceHidden}function Ms({mode:t,onChange:s,compact:n=!1}){const r=n?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(Cs,{size:r}):e.jsx(rt,{size:r})})}function xi({activeConv:t,agentCount:s,wsStatus:n,isConnected:r,conversations:i,onOpenHistory:o,onOpenRemote:c,onStopCli:d,activeCliViewMode:l,onSetCliViewMode:p,onOpenConversation:u,onHideConversation:x,hiddenConversations:m=[],onShowConversation:h,onShowAllHidden:g}){const b=Is(),w=b.p2pStates||{},f=b.ides||[],y=!!t&&Se(t)&&!ye(t),k=l||(t?Wn(t)?"terminal":"chat":null),[j,v]=a.useState(!1),[T,S]=a.useState(!1),[C,_]=a.useState(!1),B=a.useRef(null),H=a.useRef(null),E=r?"#22c55e":n==="connected"?"#eab308":"#ef4444",N=r?"0 0 4px #22c55e80":n==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",A=f.filter(F=>F.type==="adhdev-daemon"),P=a.useMemo(()=>St(f),[f]),I=Object.values(w),q=I.filter(F=>F==="connected").length,L=I.filter(F=>F==="connecting"||F==="new"||F==="checking").length,D=n!=="connected"||A.length===0?null:L>0&&q===0?"P2P connecting...":q>0&&s===0?"Waiting for IDE...":null,V=a.useMemo(()=>i.filter(F=>!pi(F,i,P)),[i,P]),ae=a.useMemo(()=>V.filter(F=>zt(F,P).requiresAction),[V,P]),G=a.useMemo(()=>V.filter(F=>{const K=(t==null?void 0:t.tabKey)===F.tabKey;return zt(F,P,{hideOpenTaskCompleteUnread:!0,isOpenConversation:K}).unread}),[t,V,P]),W=ae.length+G.length;a.useEffect(()=>{if(!j)return;const F=K=>{var M;(M=B.current)!=null&&M.contains(K.target)||v(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[j]),a.useEffect(()=>{if(!T)return;const F=K=>{var M;(M=H.current)!=null&&M.contains(K.target)||S(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[T]);const ee=F=>{if(!F)return;const K=i.find(M=>M.tabKey===F);K&&(x==null||x(K))};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(rt,{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:E,boxShadow:N}})})]}),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:r?"Connected":n==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:E,boxShadow:N}}),D&&e.jsxs("span",{className:"header-subtitle-status",children:["· ",D]})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(y||!ye(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:[p&&k&&e.jsx(Ms,{mode:k,onChange:p,compact:!0}),e.jsx("button",{onClick:d,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(Rn,{size:14})})]}),!ye(t)&&e.jsx("button",{onClick:()=>o(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(ks,{size:14})}),!y&&!ye(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(Be,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:B,children:[e.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:H,onDragEnter:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),_(!0))},onDragOver:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),F.dataTransfer.dropEffect="move",_(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||_(!1)},onDrop:F=>{const K=F.dataTransfer.getData("text/tab-key");F.preventDefault(),_(!1),ee(K)},children:[e.jsxs("button",{type:"button",onClick:()=>S(F=>!F),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx(va,{size:16}),m.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:m.length})]}),T&&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"}),m.length>0&&g&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{g(),S(!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})]}),m.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(F=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(F),S(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:F.displayPrimary}),e.jsx("span",{className:"dashboard-header-inbox-item-meta",children:F.displaySecondary})]},F.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>v(F=>!F),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(Xt,{size:16}),W>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:W})]}),j&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ae.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),ae.map(F=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item is-attention",onClick:()=>{u==null||u(F),v(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:F.displayPrimary}),e.jsx("span",{className:"dashboard-header-inbox-item-meta",children:F.displaySecondary})]},F.tabKey))]}),G.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),G.map(F=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{u==null||u(F),v(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:F.displayPrimary}),e.jsx("span",{className:"dashboard-header-inbox-item-meta",children:F.displaySecondary})]},F.tabKey))]}),W===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function fi(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 bi({activeConv:t,ides:s,isCreatingChat:n,isRefreshingHistory:r,savedSessions:i=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:l,onSwitchSession:p,onRefreshHistory:u,onResumeSavedSession:x}){var w;const m=s.find(f=>f.id===t.ideId),h=(m==null?void 0:m.chats)||[],g=(w=m==null?void 0:m.activeChat)==null?void 0:w.id,b=Se(t)&&!ye(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:b?"Saved Sessions":"Chat History"}),e.jsxs("div",{className:"text-xs text-text-muted mt-0.5",children:[t.displayPrimary," — ",Ne(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:[!b&&e.jsx("button",{onClick:l,disabled:n,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:n?"⌛ Creating...":"+ Start New Chat Session"}),b?e.jsx(e.Fragment,{children:i.map(f=>{const y=t.providerSessionId===f.providerSessionId,k=y||!f.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{k||!x||x(f)},disabled:k,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${y?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${k?"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 ${y?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:f.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:f.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:fi(f.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:f.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:[f.workspace||"Workspace unknown",f.currentModel?` · ${f.currentModel}`:"",f.messageCount>0?` · ${f.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:y?"ACTIVE":f.canResume?c===f.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},f.id)})}):h.map(f=>e.jsxs("div",{onClick:()=>{p(t.ideId,f.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${g===f.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 ${g===f.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:f.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:[f.id.substring(0,12),"..."]}),g===f.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},f.id)),(b&&!o&&i.length===0||!b&&h.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(Sa,{size:32})}),e.jsx("div",{className:"text-[13px]",children:b?"No saved sessions found yet.":"No recent chat sessions found."})]}),b&&o&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:u,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ns,{size:13})," ",b?"Refresh Sessions":"Refresh History"]})})})]})]})}const Xs={success:"rgba(16, 185, 129, 0.95)",warning:"color-mix(in srgb, var(--status-warning) 95%, transparent)",info:"rgba(99, 102, 241, 0.95)"};function Hn({toasts:t,onDismiss:s,onClickToast:n}){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(r=>e.jsxs("div",{className:"fade-in text-white px-5 py-3 rounded-xl text-[13px] font-semibold shadow-[0_8px_32px_rgba(0,0,0,0.3)] backdrop-blur-lg pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[360px] relative group",style:{background:Xs[r.type]||Xs.info},onClick:()=>{var i;(i=r.actions)!=null&&i.length||(n&&n(r),s(r.id))},children:[e.jsx("button",{className:"absolute top-1.5 right-1.5 w-5 h-5 rounded-full flex items-center justify-center text-white/50 hover:text-white hover:bg-white/20 transition-all text-[11px] leading-none opacity-0 group-hover:opacity-100 cursor-pointer",onClick:i=>{i.stopPropagation(),s(r.id)},"aria-label":"Dismiss",children:"×"}),e.jsx("div",{className:"pr-4",children:r.message}),r.actions&&r.actions.length>0&&e.jsx("div",{className:"flex gap-2 mt-2",children:r.actions.map((i,o)=>e.jsx("button",{className:`text-xs px-3 py-1 rounded-md font-bold transition-all cursor-pointer ${i.variant==="primary"?"bg-white text-text-primary hover:bg-gray-100":i.variant==="danger"?"bg-red-500/30 text-white hover:bg-red-500/50":"bg-white/20 text-white hover:bg-white/30"}`,onClick:c=>{c.stopPropagation(),i.onClick(),s(r.id)},children:i.label},o))})]},r.id))})}function Vn(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 gi=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function yi(t){const s=t.workspace||"";if(!s)return"";const n=s.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:s}function vi(t){return t.sessionId||t.instanceId||t.agentType}function cs(t,s){return t||s}function Tt(t){return Vn(t)}function Js(t,s){const n=new Set,r=[];for(const i of s)if(i)for(const o of t[i]||[]){const c=o._localId||`${o.role}:${o.timestamp}:${o.content}`;n.has(c)||(n.add(c),r.push(o))}return r.sort((i,o)=>i.timestamp-o.timestamp)}function qn(t=[]){const s={};for(const n of t){const r=n;(r.type==="adhdev-daemon"||r.daemonMode)&&(s[r.id]=qe(r,{fallbackId:r.id}))}return s}function Yn(t,s,n={}){var m,h,g,b,w,f;const r=[],i=n.machineName,o=n.connectionState,c=yi(t),d=Ne(t.type),l=Array.isArray(t.childSessions)?t.childSessions.map(y=>{var k,j;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,agentType:y.providerType,agentName:y.providerName,status:y.status,title:y.title,messages:((k=y.activeChat)==null?void 0:k.messages)||[],activeModal:((j=y.activeChat)==null?void 0:j.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],p=gi(t),u=t.activeChat||{title:""},x=u.title&&String(u.title).trim()?String(u.title).trim():"";if(p){const y=t.sessionId||t.instanceId,k=qs(t.type),j=(m=t.activeChat)==null?void 0:m.activeModal,v=j&&Array.isArray(j.buttons)&&j.buttons.length>0,T=_e((h=t.activeChat)==null?void 0:h.status,{activeModal:(g=t.activeChat)==null?void 0:g.activeModal})||_e((w=(b=t.agents)==null?void 0:b[0])==null?void 0:w.status)||"idle",S=t.activeChat||{title:"",messages:[]};let C=S.title&&String(S.title).trim()?String(S.title).trim():"";const _=(f=t.activeChat)==null?void 0:f.id,B=t.chats;if(_&&Array.isArray(B)&&B.length>0){const P=B.find(I=>I.id===_||I.id&&String(I.id)===String(_));P!=null&&P.title&&String(P.title).trim()&&(C=String(P.title).trim())}const H=S.messages||[],E=Js(s,[t.id,y]),N=new Map;H.filter(P=>P.role==="user").forEach(P=>{const I=Tt(P.content);I&&N.set(I,(N.get(I)||0)+1)});const A=E.filter(P=>{const I=Tt(P.content),q=N.get(I)||0;return q>0?(N.set(I,q-1),!1):!0});r.push({ideId:t.id,sessionId:y,providerSessionId:t.providerSessionId,nativeSessionId:y,transport:t.transport,daemonId:t.daemonId||void 0,mode:Se(t)?t.mode||"terminal":"chat",agentName:k,agentType:(Se(t)||ye(t))&&(t.cliType||t.acpType)||t.type,status:T,title:C,messages:[...H,...A],resume:t.resume,ideType:t.cliType||t.acpType||t.type,workspaceName:c,displayPrimary:C||c||(Se(t)?t.mode==="chat"?k:"Terminal":k),displaySecondary:d,cdpConnected:t.cdpConnected,modalButtons:v?j.buttons:void 0,modalMessage:v?j.message:void 0,streamSource:"native",tabKey:cs(y,t.id),machineName:i,connectionState:o})}if(p&&(Se(t)||ye(t)))return r;for(const y of l){const k=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,j=Qa(y),v=vi(y),T=`${t.id}:${v}`,S=y.title&&String(y.title).trim()||"",C=Za(S,y.agentName,y.agentType)?"":S,_=y.messages||[],B=Js(s,[T,y.sessionId,y.instanceId]),H=new Map;_.filter(A=>A.role==="user").forEach(A=>{const P=Tt(A.content);P&&H.set(P,(H.get(P)||0)+1)});const E=B.filter(A=>{const P=Tt(A.content),I=H.get(P)||0;return I>0?(H.set(P,I-1),!1):!0});(_.length>0||E.length>0||k||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(j))&&r.push({ideId:t.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:y.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:j,title:C,messages:[..._,...E],ideType:y.agentType,workspaceName:c,displayPrimary:C||x||c||d,displaySecondary:`${d}·${y.agentName}`,cdpConnected:t.cdpConnected,modalButtons:k?y.activeModal.buttons:void 0,modalMessage:k?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:cs(y.sessionId||y.instanceId,T),machineName:i,connectionState:o})}return r.length===0&&r.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:qs(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:cs(t.sessionId||t.instanceId,t.id),connectionState:o}),r}function ji(t){const s=[],n=new Map;for(const r of t)if(r.parentId){const i=n.get(r.parentId)||[];i.push(r),n.set(r.parentId,i)}else s.push(r);return{topLevel:s,childrenByParent:n}}function wi(t,s){const n=[],{daemonId:r,existingDaemon:i,timestamp:o}=s,c=o||t.timestamp||Date.now(),d=t.sessions||[],{topLevel:l,childrenByParent:p}=ji(d),u=l.filter(h=>h.kind==="workspace"&&h.transport==="cdp-page"),x=l.filter(h=>h.kind==="agent"&&h.transport==="pty"),m=l.filter(h=>h.kind==="agent"&&h.transport==="acp");n.push({...i||{},id:r,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:u.some(h=>!!h.cdpConnected)});for(const h of u){const g=p.get(h.id)||[];n.push({id:`${r}:ide:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId,parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,ideType:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:r,instanceId:h.id,workspace:h.workspace,terminals:0,childSessions:g,agents:g.map(b=>({id:b.id,name:b.providerName,type:b.providerType,status:b.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,currentModel:h.currentModel,currentPlan:h.currentPlan,currentAutoApprove:h.currentAutoApprove,lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,controlValues:h.controlValues,providerControls:h.providerControls,timestamp:c})}for(const h of x)n.push({id:`${r}:cli:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId,parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,ideType:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:r,instanceId:h.id,cliName:h.providerName,mode:h.mode||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,resume:h.resume,runtimeKey:h.runtimeKey,runtimeDisplayName:h.runtimeDisplayName,runtimeWorkspaceLabel:h.runtimeWorkspaceLabel,runtimeWriteOwner:h.runtimeWriteOwner??null,runtimeAttachedClients:h.runtimeAttachedClients??[],lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,controlValues:h.controlValues,providerControls:h.providerControls,timestamp:c,_isCli:!0});for(const h of m)n.push({id:`${r}:acp:${h.id}`,sessionId:h.id,providerSessionId:h.providerSessionId,parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,ideType:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:r,instanceId:h.id,cliName:h.providerName,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,runtimeKey:h.runtimeKey,runtimeDisplayName:h.runtimeDisplayName,runtimeWorkspaceLabel:h.runtimeWorkspaceLabel,runtimeWriteOwner:h.runtimeWriteOwner??null,runtimeAttachedClients:h.runtimeAttachedClients??[],currentModel:h.currentModel,currentPlan:h.currentPlan,lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,acpConfigOptions:h.acpConfigOptions,acpModes:h.acpModes,controlValues:h.controlValues,providerControls:h.providerControls,timestamp:c,_isAcp:!0});return n}function ki(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 Ni(t,s){const n=ki(t);return{daemonId:n.daemonId,payload:{...s,...n.targetSessionId&&!s.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Gn=[{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:"💚"}],Xn=[{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:"🧩"}],Jn=[{id:"copilot",name:"GitHub Copilot",icon:"🤖"},{id:"cline",name:"Cline",icon:"🧠"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"continue",name:"Continue",icon:"▶️"}],Zn="adhdev_notification_prefs",Zs={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0,chatTaskCompletionBubble:!1};function Si(){try{const t=localStorage.getItem(Zn);if(t){const s=JSON.parse(t);return{...Zs,...s}}}catch{}return{...Zs}}function Ci(t){try{localStorage.setItem(Zn,JSON.stringify(t))}catch{}}let Ue=Si(),Et=[];function Ii(){Et.forEach(t=>t())}function Mi(){return{...Ue}}function Ti(t){Ue={...Ue,...t},Ci(Ue),Ii()}function Ai(){const[,t]=a.useState(0);a.useEffect(()=>{const n=()=>t(r=>r+1);return Et.push(n),()=>{Et=Et.filter(r=>r!==n)}},[]);const s=a.useCallback(n=>{Ti(n)},[]);return[{...Ue},s]}function ft(t){if(!Ue.globalEnabled)return!1;switch(t){case"disconnect":return Ue.disconnectAlert;case"completion":return Ue.completionAlert;case"approval":return Ue.approvalAlert;case"browser":return Ue.browserNotifications;default:return!0}}const Ri={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Li(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Qn(){return"Notification"in window&&Notification.permission==="granted"}let et=null;async function Di(){if(et!==null)return et;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return et=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(et=!!await t.pushManager.getSubscription(),et):(et=!1,!1)}catch{return et=!1,!1}}function bs(t,s,n){if(Qn())try{const r=new Notification(t,{body:s,icon:"/otter-logo.png",tag:n||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function _i(t,s={}){const n={...Ri,...s},r=a.useRef(new Map),i=a.useRef(0),o=a.useRef(null);a.useEffect(()=>{Di().then(d=>{o.current=d})},[]);const c=a.useCallback((d,l,p)=>{const u=Date.now();u-i.current<n.throttleMs||(i.current=u,bs(d,l,p))},[n.throttleMs]);a.useEffect(()=>{var d;if(!(!n.enabled||!Qn())&&ft("browser")&&o.current!==!0){if(document.hasFocus()){for(const l of t)r.current.set(l.id,_e(l.status,{activeModal:l.activeModal}));return}for(const l of t){const p=r.current.get(l.id),u=_e(l.status,{activeModal:l.activeModal}),x=l.name||l.id;if(n.onApproval&&ft("approval")&&u==="waiting_approval"&&p!=="waiting_approval"){const m=((d=l.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,m.slice(0,120),`approval-${l.id}`)}n.onComplete&&ft("completion")&&Pn(p)&&u==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${l.id}`),n.onError&&u==="error"&&p!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${l.id}`),r.current.set(l.id,u)}}},[t,n.enabled,n.onApproval,n.onComplete,n.onError,c])}class Ei{constructor(){Ie(this,"dedupMap",new Map);Ie(this,"DEDUP_WINDOW_MS",5e3);Ie(this,"DEDUP_MAX_SIZE",50);Ie(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ie(this,"toastCallbacks",[]);Ie(this,"systemMessageCallbacks",[]);Ie(this,"clearSystemMessageCallbacks",[]);Ie(this,"resolveActionFn",null);Ie(this,"viewRequestRespondFn",null);Ie(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(n=>n!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(n=>n!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(n=>n!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const n of this.toastCallbacks)n(s)}showToast(s,n="info",r){const i=(r==null?void 0:r.id)||Date.now();this.emitToast({id:i,message:s,type:n,timestamp:i,duration:5e3,...r})}emitSystemMessage(s,n){for(const r of this.systemMessageCallbacks)r(s,n)}emitClearSystemMessage(s,n){for(const r of this.clearSystemMessageCallbacks)r(s,n)}isDuplicate(s){const n=Date.now(),r=this.dedupMap.get(s)||0;if(n-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,n),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[i,o]of this.dedupMap)n-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 n;if(s.targetSessionId&&(n=this.findOwningSession(s.targetSessionId)||void 0),s.ideId&&(n=n||this.ides.find(i=>i.id===s.ideId)),!n&&s.instanceId&&(n=this.ides.find(i=>i.id.endsWith(`:ide:${s.instanceId}`)||i.id.endsWith(`:cli:${s.instanceId}`))),n){const i=n.daemonId;if(i){const o=this.ides.find(c=>c.id===i&&c.type==="adhdev-daemon");if(o)return o}}const r=this.ides.filter(i=>i.type==="adhdev-daemon");return r.length===1?r[0]:null}resolveRouteId(s,n){for(const r of this.ides)if(r.id.startsWith(s)&&(!n||n===r.type))return r.id;return s}findOwningSession(s){for(const n of this.ides)if(n.id===s||n.sessionId===s||(Array.isArray(n.childSessions)?n.childSessions:[]).some(i=>(i==null?void 0:i.id)===s))return n;return null}resolveActionRouteTarget(s){if(s.ideId){const n=s.agentType||s.ideType||"";return this.resolveRouteId(s.ideId,n)}if(s.targetSessionId){const n=this.findOwningSession(s.targetSessionId);return(n==null?void 0:n.id)||(n==null?void 0:n.daemonId)||null}return null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.ideId?s.ideId:null}handleRawEvent(s,n){var u,x;if(!s.ideId&&s.instanceId){for(const m of this.ides)if(m.id.endsWith(`:ide:${s.instanceId}`)||m.id.endsWith(`:cli:${s.instanceId}`)){s.ideId=m.id;break}}const r=this.resolveConversationKey(s),o=`${r||s.instanceId||s.ideType||s.providerType||""}:${s.event}:${s.chatTitle||""}`;if(this.isDuplicate(o))return;let c=Ne(s.ideType||"");const d=this.resolveOwningDaemon(s);if(d){const m=qe(d,{fallbackId:d.id});m&&(c=s.ideType==="adhdev-daemon"?m:`${m}/${c}`)}let l="",p="info";if(s.event==="agent:generating_completed"){const m=s.duration?` (${s.duration}s)`:"";l=`✅ ${c} agent task completed${m}`,p="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}r&&Mi().chatTaskCompletionBubble&&this.emitSystemMessage(r,{role:"system",timestamp:Date.now(),content:`✅ Task completed${m}`,_localId:`sys_complete_${Date.now()}`})}else if(s.event==="agent:generating_started")r&&this.emitClearSystemMessage(r,"sys_complete_");else if(s.event==="agent:waiting_approval"){if(l=`⚡ ${c} approval needed`,p="warning",r){const m=s.modalMessage||"Approval requested",h=(u=s.modalButtons)!=null&&u.length?s.modalButtons.map(g=>`[${g}]`).join(" "):"[Approve] [Reject]";this.emitSystemMessage(r,{role:"system",timestamp:Date.now(),content:`⚡ Approval requested: ${m}
42
- ${h}`,_localId:`sys_approval_${Date.now()}`})}if((x=s.modalButtons)!=null&&x.length&&this.resolveActionFn){const m=this.resolveActionRouteTarget(s);if(!m)return;const h=s.agentType||s.ideType||"",g=s.ideType||"",b=s.modalButtons,w=v=>v.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim(),f=this.resolveActionFn,y=b.map((v,T)=>{const S=w(v).toLowerCase(),C=/^(run|approve|accept|yes|allow|always)/.test(S),_=/^(reject|deny|delete|remove|abort|cancel|no)/.test(S);return{label:w(v),variant:C?"primary":_?"danger":"default",onClick:()=>{const B=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S);f(m,"resolve_action",{action:B?"approve":"reject",button:v,buttonIndex:T,agentType:h,ideType:g,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}}}),k=s.modalMessage?`⚡ ${c}: ${s.modalMessage.replace(/[\n\r]+/g," ").slice(0,80)}`:l,j=Date.now();this.emitToast({id:j,message:k,type:p,timestamp:j,targetKey:r||m,actions:y,duration:15e3}),l=""}}else if(s.event==="monitor:long_generating"){const m=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";l=`⚠️ ${c} agent is taking a long time${m}`,p="warning",ft("browser")&&!document.hasFocus()&&bs(`⚠️ ${c} — Long Running`,`Agent has been generating for over ${m.replace(/[()]/g,"")}`,`long-${s.ideId||s.agentType}`)}else if(s.event==="team:view_request"){const m=s.requesterName||"A team member",h=s.requestId,g=s.orgId;if(l=`👁️ ${m} wants to view your session`,p="warning",h&&g&&this.viewRequestRespondFn){const b=this.viewRequestRespondFn,w=Date.now(),f=[{label:"Approve",variant:"primary",onClick:()=>{b(g,h,"approve").catch(y=>console.error("[EventManager] approve view request failed:",y))}},{label:"Decline",variant:"danger",onClick:()=>{b(g,h,"reject").catch(y=>console.error("[EventManager] reject view request failed:",y))}}];this.emitToast({id:w,message:l,type:p,timestamp:w,actions:f,duration:3e4}),l=""}ft("browser")&&!document.hasFocus()&&bs("👁️ View Request",`${m} wants to view your session`,`view-request-${h}`)}else s.event==="team:view_request_approved"?(l="✅ View request approved",p="success"):s.event==="team:view_request_rejected"&&(l=`❌ ${s.targetName||"Team member"} declined your view request`,p="warning");if(l){const m=Date.now();this.emitToast({id:m,message:l,type:p,timestamp:m,targetKey:r||s.ideId,duration:5e3})}}}const Je=new Ei;function at(...t){return Gr(Xr(t))}function Pi({icon:t,title:s,subtitle:n,badge:r,actions:i,className:o}){return e.jsxs("div",{className:at("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,r&&e.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&e.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),i&&e.jsx("div",{className:"flex gap-2",children:i})]})}function Ft({icon:t,title:s,subtitle:n,badge:r,actions:i,widthClassName:o="max-w-6xl",contentClassName:c,children:d}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Pi,{icon:t,title:s,subtitle:n,badge:r,actions:i}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:at("mx-auto flex w-full flex-col gap-4",o,c),children:d})})]})}function Re({title:t,icon:s,description:n,accentColor:r,className:i,children:o}){return e.jsxs("div",{className:at("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",i),style:r?{borderLeftColor:r}:void 0,children:[(t||n)&&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]}),n&&e.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o]})}function Ts({icon:t,title:s,description:n,action:r,className:i}){return e.jsxs("div",{className:at("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:n}),r]})}const $i={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"},Bi={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ki({variant:t,children:s,onDismiss:n,className:r}){return e.jsxs("div",{className:at("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",$i[t],r),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Bi[t]}),e.jsx("span",{children:s})]}),n&&e.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Wi={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"},Oi={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Ui({status:t,label:s,className:n}){const r=s||t;return e.jsxs("span",{className:at("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Wi[t],n),children:[e.jsx("span",{className:at("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Oi[t])}),r]})}function zi(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"dark"}function Pt(t){return t==="system"?zi():t}function Fi(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Pt(gs()))}function er(){const[t,s]=a.useState(gs),[n,r]=a.useState(()=>Pt(gs()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",n)},[n]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=l=>{t==="system"&&r(l.matches?"light":"dark")};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]);const i=a.useCallback(c=>{s(c),r(Pt(c));try{localStorage.setItem("theme",c)}catch{}},[]),o=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark";r(Pt(d));try{localStorage.setItem("theme",d)}catch{}return d})},[]);return{theme:n,preference:t,setPreference:i,cycleTheme:o,isDark:n==="dark"}}function Ze({label:t,description:s,checked:n,disabled:r,onChange:i,extra:o}){return e.jsxs("label",{className:"flex justify-between items-center cursor-pointer",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:t}),e.jsx("div",{className:"text-[11px] text-text-muted",children:s})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[o,e.jsx("input",{type:"checkbox",checked:n,disabled:r,onChange:c=>i(c.target.checked),className:"w-5 h-5 accent-accent"})]})]})}function Hi({onPrefChange:t}){const[s,n]=Ai(),r=(i,o)=>{n({[i]:o}),t==null||t(i,o)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Xt,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:i=>r("globalEnabled",i)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:i=>r("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(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:i=>r("completionAlert",i)}),e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ia,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:i=>r("approvalAlert",i)}),e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ct,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:i=>r("disconnectAlert",i)})]}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-2"}),s.globalEnabled&&e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(rt,{size:15})," Task Completion Bubble"]}),description:"Show a system message bubble in chat when an agent finishes a task",checked:s.chatTaskCompletionBubble,onChange:i=>r("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 Vi({ides:t,emptyMessage:s,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:i}){const o=t.filter(c=>c.type==="adhdev-daemon");return o.length===0?e.jsx(Ts,{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(Yi,{ide:c,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:i},c.id))})}function Qs({title:t,message:s,confirmLabel:n,confirmColor:r,onConfirm:i,onCancel:o}){const c=r==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Jr.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:r==="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:n})]})]})}),document.body)}function qi(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...Gn,...Xn,...Jn].find(i=>i.id===s||s.includes(i.id)||i.id.includes(s));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:t}}function Yi({ide:t,allIdes:s,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:i}){var A,P;const[o,c]=a.useState("idle"),[d,l]=a.useState(""),[p,u]=a.useState(null),[x,m]=a.useState("idle"),[h,g]=a.useState(""),b=t,w=b.version||b.daemonVersion||null,f=((A=b.machine)==null?void 0:A.platform)||((P=b.system)==null?void 0:P.platform)||"",y=qe(b,{fallbackId:t.id}),k=f==="win32"?"🪟":f==="darwin"?"🍎":"🐧",j=s.filter(I=>I.daemonId===t.id&&I.transport==="cdp-page"),v=s.filter(I=>I.daemonId===t.id&&I.transport==="pty"),T=s.filter(I=>I.daemonId===t.id&&I.transport==="acp"),S=b.p2p,C=async()=>{var I,q,L,$;if(n){c("upgrading"),l("Starting upgrade...");try{const D=await n(t.id,"daemon_upgrade",{});(I=D==null?void 0:D.result)!=null&&I.alreadyLatest?(c("done"),l(`Already on v${D.result.version||"latest"}.`)):(q=D==null?void 0:D.result)!=null&&q.upgraded||(L=D==null?void 0:D.result)!=null&&L.success?(c("done"),l(`Upgrade to v${D.result.version||"latest"} started. Daemon is restarting...`)):(c("error"),l((($=D==null?void 0:D.result)==null?void 0:$.error)||"Upgrade failed"))}catch(D){c("error"),l((D==null?void 0:D.message)||"Connection lost during upgrade")}}},_=async()=>{if(u(null),!!r){m("loading");try{await r(t.id),m("done"),g("Machine disconnected.")}catch(I){m("error"),g((I==null?void 0:I.message)||"Failed to disconnect")}}},B=async()=>{if(u(null),!!i){m("loading");try{await i(t.id),m("done"),g('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(I){m("error"),g((I==null?void 0:I.message)||"Failed to revoke token")}}},H="0.7.46",E=!w||w!==H,N=j.length+v.length+T.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:k}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),w&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${E?"":"bg-bg-secondary"}`,style:E?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",w,!E&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&E&&e.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${H}`,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${H}`}`}),r&&e.jsx("button",{onClick:()=>u("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),i&&e.jsx("button",{onClick:()=>u("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(Ui,{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:[S&&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 ${S.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${S.state==="connecting"||S.state==="new"?"animate-pulse":""}`,style:S.state==="connecting"||S.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",S.state==="connected"?"connected":S.state==="connecting"||S.state==="new"?"connecting...":S.state||"off"]}),S.peers!==void 0&&S.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",S.peers," peer",S.peers!==1?"s":"",")"]})]}),S&&N>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),N>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(I=>{const q=qi(I.type),L=I.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:q.icon}),e.jsx("span",{children:q.name}),L!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L?"bg-green-400":"animate-pulse"}`,style:L?void 0:{background:"var(--status-warning)"},title:L?"CDP connected":"CDP connecting..."})]},I.id)}),v.map(I=>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:I.cliName||"CLI"})]},I.id)),T.map(I=>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:I.cliName||"ACP"})]},I.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||h)&&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:h||d})]}),p==="disconnect"&&e.jsx(Qs,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
43
-
44
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
45
-
46
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:_,onCancel:()=>u(null)}),p==="revoke"&&e.jsx(Qs,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
47
-
48
- This will:
49
- • Immediately disconnect the machine
50
- • Delete the machine registration
51
- • Require restarting "adhdev-standalone" on that machine
52
-
53
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:B,onCancel:()=>u(null)})]})}const Gi=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Xi(){const{preference:t,setPreference:s}=er();return e.jsx("div",{className:"flex gap-2",children:Gi.map(n=>e.jsxs("button",{onClick:()=>s(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${t===n.id?"bg-accent border-accent text-white":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,children:[e.jsx("span",{children:n.icon}),n.label]},n.id))})}const ys={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},vs={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},Ji=[{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"}}}],tr="adhdev-chat-theme",sr="adhdev-chat-theme-custom";function $t(){return typeof window>"u"?"ember":localStorage.getItem(tr)||"ember"}function We(t){try{const s=localStorage.getItem(sr);if(s){const n=JSON.parse(s);return{...t==="dark"?ys:vs,...n[t]}}}catch{}return t==="dark"?ys:vs}function At(t,s){localStorage.setItem(sr,JSON.stringify({dark:t,light:s}))}function Pe(t,s){const n=parseInt(t.slice(1,3),16),r=parseInt(t.slice(3,5),16),i=parseInt(t.slice(5,7),16);return`rgba(${n}, ${r}, ${i}, ${s})`}function Ht(t,s){const n=Math.min(255,parseInt(t.slice(1,3),16)+s),r=Math.min(255,parseInt(t.slice(3,5),16)+s),i=Math.min(255,parseInt(t.slice(5,7),16)+s);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}const Zi={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function bt(t,s){var i;const n=(i=Zi[t])==null?void 0:i[s];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Ht(n,24)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Ht(n,18)})`),r.style.setProperty("--border-accent",Pe(n,.35)),r.style.setProperty("--nav-active-bg",Pe(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Pe(n,.06)}`)}function st(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",Pe(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",Pe(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Pe(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",Pe(t.borderSubtle,.5)),s.style.setProperty("--border-default",Pe(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",Ht(t.accentColor,30)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${Ht(t.accentColor,40)})`),s.style.setProperty("--border-accent",Pe(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",Pe(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${Pe(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 ${Pe(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 As(){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-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(n=>t.style.removeProperty(n))}function Qi(t){if(localStorage.setItem(tr,t),document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=nt()?"dark":"light";st(We(s))}else As(),bt(t,nt()?"dark":"light")}function eo(){const t=$t();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=nt()?"dark":"light";st(We(s))}else As(),bt(t,nt()?"dark":"light")}function nt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ae({label:t,value:s,onChange:n}){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)",minWidth:110},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("input",{type:"color",value:s,onChange:r=>n(r.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:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:72,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 ut({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 to({dark:t,onColorsChange:s}){const n=t?"dark":"light",[r,i]=a.useState(()=>We(n));a.useEffect(()=>{i(We(n))},[n]);const o=a.useCallback((c,d)=>{i(l=>{const p={...l,[c]:d},x=We(n==="dark"?"light":"dark");return n==="dark"?At(p,x):At(x,p),st(p),s(p),p})},[n,s]);return e.jsxs("div",{style:{marginTop:12,padding:"16px 18px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12},children:[e.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8},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",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[e.jsxs("div",{children:[e.jsxs(ut,{title:"App Background",children:[e.jsx(Ae,{label:"Background",value:r.bgPrimary,onChange:c=>o("bgPrimary",c)}),e.jsx(Ae,{label:"Surface",value:r.bgSecondary,onChange:c=>o("bgSecondary",c)}),e.jsx(Ae,{label:"Card",value:r.surfacePrimary,onChange:c=>o("surfacePrimary",c)})]}),e.jsxs(ut,{title:"App Text",children:[e.jsx(Ae,{label:"Primary",value:r.textPrimary,onChange:c=>o("textPrimary",c)}),e.jsx(Ae,{label:"Secondary",value:r.textSecondary,onChange:c=>o("textSecondary",c)}),e.jsx(Ae,{label:"Muted",value:r.textMuted,onChange:c=>o("textMuted",c)})]}),e.jsxs(ut,{title:"Borders & Accent",children:[e.jsx(Ae,{label:"Border subtle",value:r.borderSubtle,onChange:c=>o("borderSubtle",c)}),e.jsx(Ae,{label:"Border default",value:r.borderDefault,onChange:c=>o("borderDefault",c)}),e.jsx(Ae,{label:"Accent",value:r.accentColor,onChange:c=>o("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(ut,{title:"Chat Bubbles",children:[e.jsx(Ae,{label:"User bubble",value:r.userBubble,onChange:c=>o("userBubble",c)}),e.jsx(Ae,{label:"User text",value:r.userText,onChange:c=>o("userText",c)}),e.jsx(Ae,{label:"Agent bubble",value:r.assistantBubble,onChange:c=>o("assistantBubble",c)}),e.jsx(Ae,{label:"Agent text",value:r.assistantText,onChange:c=>o("assistantText",c)})]}),e.jsxs(ut,{title:"Chat Layout",children:[e.jsx(Ae,{label:"Chat BG",value:r.containerBg,onChange:c=>o("containerBg",c)}),e.jsx(Ae,{label:"Send button",value:r.sendButton,onChange:c=>o("sendButton",c)}),e.jsx(Ae,{label:"Input border",value:r.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)",minWidth:110},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:r.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:[r.bubbleRadius,"px"]})]})]})]})]})]}),e.jsx("button",{onClick:()=>{const c=t?ys:vs,l=We(t?"light":"dark");t?At(c,l):At(l,c),i(c),st(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 so(){const[t,s]=a.useState($t),[n,r]=a.useState(!0),[i,o]=a.useState(()=>We("dark"));a.useEffect(()=>{r(nt());const l=new MutationObserver(()=>{const x=nt();r(x);const m=$t();m==="custom"?st(We(x?"dark":"light")):bt(m,x?"dark":"light")});l.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=nt();r(x);const m=$t();m==="custom"?st(We(x?"dark":"light")):bt(m,x?"dark":"light")};return p.addEventListener("change",u),()=>{l.disconnect(),p.removeEventListener("change",u)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?st(We(n?"dark":"light")):(As(),bt(t,n?"dark":"light"))},[t,n]),a.useEffect(()=>{o(We(n?"dark":"light"))},[n]);const c=l=>{s(l),Qi(l)},d=[...Ji,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText},light:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText}}}];return e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(l=>{const p=t===l.id,u=n?l.preview.dark:l.preview.light,x=l.id==="honey"||l.id==="ember"?"#1a1a1a":l.id==="custom"?i.userText:"#fff";return e.jsxs("button",{onClick:()=>c(l.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:x},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:l.id==="custom"?"🎨 Custom":l.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:l.description})]})]})]},l.id)})}),t==="custom"&&e.jsx(to,{dark:n,onColorsChange:l=>o(l)})]})}const nr="adhdev_mobileDashboardMode_v1";function rr(){try{return localStorage.getItem(nr)==="workspace"?"workspace":"chat"}catch{return"chat"}}function no(t){try{localStorage.setItem(nr,t)}catch{}}function ro(){const[t,s]=a.useState(!1);return a.useEffect(()=>{s(rr()==="workspace")},[]),e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(rt,{size:15})," Mobile dashboard layout"]}),description:t?"Use the full workspace layout on phones and tablets.":"Use the chat-first mobile inbox by default. This keeps mobile closer to a messaging app.",checked:t,onChange:n=>{s(n),no(n?"workspace":"chat")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Workspace":"Chat mode"})})}const ar="adhdev_hiddenTabs";function ao(){try{const t=localStorage.getItem(ar);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function it(t){try{localStorage.setItem(ar,JSON.stringify([...t]))}catch{}}function io(){const[t,s]=a.useState(ao),n=a.useCallback(p=>{s(u=>{const x=new Set(u);return x.has(p)?x.delete(p):x.add(p),it(x),x})},[]),r=a.useCallback(p=>{s(u=>{if(u.has(p))return u;const x=new Set(u);return x.add(p),it(x),x})},[]),i=a.useCallback(p=>{s(u=>{if(!u.has(p))return u;const x=new Set(u);return x.delete(p),it(x),x})},[]),o=a.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return it(u),u})},[]),c=a.useCallback((p,u)=>{s(x=>{const m=new Set(x);for(const h of u)m.add(h);return it(m),m})},[]),d=a.useCallback((p,u)=>{s(x=>{const m=new Set(x);for(const h of u)m.delete(h);return it(m),m})},[]),l=a.useCallback(p=>t.has(p),[t]);return{hiddenTabs:t,toggleTab:n,hideTab:r,showTab:i,showAllTabs:o,hideAllForDaemon:c,showAllForDaemon:d,isHidden:l}}function oo({visibleConversations:t,clearedTabs:s,setClearedTabs:n,setActionLogs:r}){a.useEffect(()=>{Li()},[]);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 _i(i),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{n(d=>{const l=Date.now(),p={};for(const[u,x]of Object.entries(d))l-x<5e3&&(p[u]=x);return Object.keys(p).length===Object.keys(d).length?d:p})},5500);return()=>clearTimeout(c)},[s,n]),a.useEffect(()=>{const o=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const l=d.filter(p=>p.timestamp>c).slice(-100);return l.length===d.length?d:l})},6e4);return()=>clearInterval(o)},[r]),null}function ls(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 Jt(t){const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1];return ls(s==null?void 0:s.timestamp)||ls(s==null?void 0:s.receivedAt)||ls(s==null?void 0:s.createdAt)||0}function en(t,s=0){return Jt(t)||s||0}function gt(t){return Jt(t)}function ir(t,s){const n=gt(s)-gt(t);if(n!==0)return n;const r=(t.machineName||"").localeCompare(s.machineName||"");if(r!==0)return r;const i=t.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const o=t.displaySecondary.localeCompare(s.displaySecondary);return o!==0?o:t.tabKey.localeCompare(s.tabKey)}function co(t){const s=t.filter(r=>r.type!=="adhdev-daemon"),n=new Map;for(const r of s){const i=n.get(r.id);if(!i){n.set(r.id,r);continue}const o=(i.workspace?1:0)+(i.activeChat?1:0);((r.workspace?1:0)+(r.activeChat?1:0)>o||(r.timestamp||0)>(i.timestamp||0))&&n.set(r.id,r)}return Array.from(n.values())}function Rt(t,s){if(t.length!==s.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==s[n])return!1;return!0}function lo(t,s){const n=Date.now();return t.map(r=>{const i=s[r.tabKey];return i&&n-i<5e3?{...r,messages:[],title:""}:r})}function uo(t,s){const n=[],r=t.sessionId||t.instanceId;n.push({key:t.id,ref:s[t.id]}),r&&n.push({key:r,ref:s[r]});for(const i of t.childSessions||[]){const o=i.id||i.providerType,c=`${t.id}:${o}`;n.push({key:c,ref:s[c]}),n.push({key:i.id,ref:s[i.id]})}return n}function ho(t,s){if(t.length!==s.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n].key!==s[n].key||t[n].ref!==s[n].ref)return!1;return!0}function mo({ides:t,connectionStates:s,localUserMessages:n,clearedTabs:r,hiddenTabs:i}){const o=a.useRef([]),c=a.useRef([]),d=a.useRef([]),l=a.useRef([]),p=a.useMemo(()=>{const j=co(t);return Rt(o.current,j)?o.current:(o.current=j,j)},[t]),u=a.useMemo(()=>qn(t),[t]),x=a.useRef(new Map),m=a.useMemo(()=>{var T;const j=new Map,v=[];for(const S of p){const C=S.daemonId||((T=S.id)==null?void 0:T.split(":")[0])||S.id,_=s[C]||"new",B=S.daemonId&&u[S.daemonId]||void 0,H=uo(S,n),E=x.current.get(S.id);if(E&&E.ide===S&&E.connectionState===_&&E.machineName===B&&ho(E.localRefs,H)){j.set(S.id,E),v.push(...E.conversations);continue}const N=Yn(S,n,{machineName:B,connectionState:_}),A={ide:S,connectionState:_,machineName:B,localRefs:H,conversations:N};j.set(S.id,A),v.push(...N)}return x.current=j,[...v].sort(ir)},[p,n,s,u]),h=a.useMemo(()=>{const j=lo(m,r);return Rt(c.current,j)?c.current:(c.current=j,j)},[m,r]),g=a.useMemo(()=>{const j=new Map;for(const v of h)v.sessionId&&j.set(v.sessionId,v);return j},[h]),b=a.useMemo(()=>{const j=new Map;for(const v of h)v.sessionId&&j.set(v.sessionId,v),j.set(v.ideId,v),j.set(v.tabKey,v);return j},[h]),w=a.useCallback(j=>{if(j)return g.get(j)},[g]),f=a.useCallback(j=>{if(j)return b.get(j)},[b]),y=a.useMemo(()=>{const j=h.filter(v=>!i.has(v.tabKey));return Rt(d.current,j)?d.current:(d.current=j,j)},[h,i]),k=a.useMemo(()=>{const j=y.map(v=>v.tabKey);return Rt(l.current,j)?l.current:(l.current=j,j)},[y]);return{chatIdes:p,conversations:h,visibleConversations:y,visibleTabKeys:k,resolveConversationBySessionId:w,resolveConversationByTarget:f}}function po({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:n,setSearchParams:r}){const i=a.useMemo(()=>{var d;return t||!s?null:((d=n(s))==null?void 0:d.tabKey)??null},[t,n,s]),o=a.useMemo(()=>{var d;return!t||!s?null:((d=n(s))==null?void 0:d.tabKey)??null},[t,n,s]),c=a.useCallback(()=>{s&&r(d=>{const l=new URLSearchParams(d);return l.delete("activeTab"),l},{replace:!0})},[r,s]);return{requestedDesktopTabKey:i,requestedMobileTabKey:o,consumeRequestedActiveTab:c}}function xo({ides:t,sendDaemonCommand:s,setToasts:n,setLocalUserMessages:r,resolveConversationByTarget:i}){a.useEffect(()=>{Je.setIdes(t)},[t]),a.useEffect(()=>{Je.setResolveAction((o,c,d)=>{s(o,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const o=Je.onToast(l=>{n(u=>u.some(m=>m.message===l.message&&l.timestamp-m.timestamp<3e3)?u:[...u.slice(-4),{id:l.id,message:l.message,type:l.type,timestamp:l.timestamp,targetKey:l.targetKey,actions:l.actions}]);const p=l.duration||5e3;setTimeout(()=>n(u=>u.filter(x=>x.id!==l.id)),p)}),c=Je.onSystemMessage((l,p)=>{r(u=>({...u,[l]:[...u[l]||[],p]}))}),d=Je.onClearSystemMessage((l,p)=>{r(u=>{var x;return(x=u[l])!=null&&x.length?{...u,[l]:u[l].filter(m=>{var h;return!(m.role==="system"&&((h=m._localId)!=null&&h.startsWith(p)))})}:u})});return()=>{o(),c(),d()}},[n,r]),a.useEffect(()=>{const o=Un.on("status_event",c=>Je.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 p=l.targetSessionId||l.targetKey||l.ideId,u=i(p),x=(u==null?void 0:u.ideId)||l.ideId;x&&s(x,"resolve_action",{action:"approve",button:"Approve",...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(m=>console.error("[SW Action] approve failed:",m))};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 fo="adhdev_dashboardLayout_v1",bo="adhdev_dashboardDockview_v1",ht={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function or(t,s){try{const n=localStorage.getItem(t);return n?JSON.parse(n):s}catch{return s}}function cr(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function lr(t){return`${fo}:${t}`}function go(t){const s=lr(t);return or(s,null)}function yo(t,s){try{const n=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,r=lr(t);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function dr(t){return`${bo}:${t}`}function vo(t){const s=dr(t);return or(s,null)}function jo(t,s){try{const n=dr(t);if(!s){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function wo(){return{groupAssignments:[...ht.groupAssignments],focusedGroup:ht.focusedGroup,groupActiveTabIds:{...ht.groupActiveTabIds},groupTabOrders:{...ht.groupTabOrders},groupSizes:[...ht.groupSizes]}}function ko(){const[t]=a.useState(()=>cr(typeof window<"u"?window.innerWidth:1280)),[s,n]=a.useState(()=>new Map),[r,i]=a.useState(0),[o,c]=a.useState({}),[d,l]=a.useState({}),[p,u]=a.useState([]),[x,m]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[h,g]=a.useState(!1),b=a.useCallback(()=>{if(h)return;const w=go(t)??wo();n(new Map(w.groupAssignments)),i(w.focusedGroup),c(w.groupActiveTabIds),l(w.groupTabOrders),u(w.groupSizes),g(!0)},[h,t]);return a.useEffect(()=>{h&&yo(t,{groupAssignments:[...s.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:d,groupSizes:p})},[h,t,s,r,o,d,p]),a.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),f=y=>m(y.matches);return w.addEventListener("change",f),()=>w.removeEventListener("change",f)},[]),{groupAssignments:s,setGroupAssignments:n,focusedGroup:r,setFocusedGroup:i,groupActiveTabIds:o,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:l,groupSizes:p,setGroupSizes:u,isMobile:x,hasHydratedStoredLayout:h,hydrateStoredLayout:b}}function No({urlActiveTab:t,conversations:s,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:i,hydrateStoredLayout:o,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:l,historyModalOpen:p,activeConv:u,isRefreshingHistory:x,ides:m,handleRefreshHistory:h}){const g=a.useRef(!1),b=a.useRef(!1),w=a.useRef(null),f=a.useRef(!1);a.useEffect(()=>{if(!t||g.current||s.length===0)return;if(!i){o();return}const y=n(t);if(!y)return;const k=r.get(y.tabKey)??0;c(j=>({...j,[k]:y.tabKey})),d(k),g.current=!0,b.current=!0,w.current!=null&&(window.clearTimeout(w.current),w.current=null),l(j=>{const v=new URLSearchParams(j);return v.delete("activeTab"),v},{replace:!0})},[t,s,n,r,i,o,c,d,l]),a.useEffect(()=>{if(!(b.current||i)&&s.length!==0){if(!t){o(),b.current=!0;return}if(g.current){b.current=!0;return}if(w.current==null)return w.current=window.setTimeout(()=>{w.current=null,!(b.current||i)&&(o(),b.current=!0)},1500),()=>{w.current!=null&&(window.clearTimeout(w.current),w.current=null)}}},[t,s.length,i,o]),a.useEffect(()=>{if(!p){f.current=!1;return}if(!u||f.current||x)return;const y=m.find(k=>k.id===u.ideId);y&&(!y.chats||y.chats.length===0)&&(f.current=!0,h())},[p,u,x,m,h]),a.useEffect(()=>{if(!u)return;let y=null,k=0,j=-1,v=0;const T=()=>{y=null;const S=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(_=>_.offsetParent!==null);if(S.length===0){k<18&&(k+=1,y=requestAnimationFrame(T));return}let C=0;for(const _ of S)_.scrollTop=_.scrollHeight,C+=_.scrollHeight;C===j?v+=1:(v=0,j=C),k+=1,!(v>=2||k>=18)&&(y=requestAnimationFrame(T))};return y=requestAnimationFrame(T),()=>{y!=null&&cancelAnimationFrame(y)}},[u==null?void 0:u.tabKey])}function So({isMobile:t,location:s,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:i,conversations:o,ides:c,resolveConversationByTarget:d}){const[l,p]=a.useState(null),[u,x]=a.useState(null),m=a.useMemo(()=>{if(t||!r)return null;const f=d(r);return f&&!Se(f)&&!ye(f)?f:null},[t,r,d]),h=a.useMemo(()=>{const f=l==null?void 0:l.ideId;if(!f)return null;const y=l!=null&&l.tabKey?o.find(k=>k.tabKey===l.tabKey):i?o.find(k=>k.tabKey===i):null;return(y==null?void 0:y.ideId)===f?y:o.find(k=>k.ideId===f&&k.streamSource==="native")||o.find(k=>k.ideId===f)||null},[o,l,i]),g=a.useMemo(()=>{if(h)return c.find(f=>f.id===h.ideId)},[c,h]);a.useEffect(()=>{m&&(p({ideId:m.ideId,tabKey:m.streamSource==="native"?"native":m.tabKey}),x(m),n({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,n,m]);const b=a.useCallback(f=>{f&&(p({ideId:f.ideId,tabKey:f.streamSource==="native"?"native":f.tabKey}),x(f))},[]),w=a.useCallback(()=>{p(null),x(null)},[]);return{remoteDialogConv:h,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:b,closeRemoteDialog:w}}function yt(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return Se(t)||ye(t)?{...s,agentType:t.agentType||t.ideType}:t.streamSource==="agent-stream"?{...s,agentType:t.agentType}:s}function Vt(t){return t&&(t.ideId||t.daemonId)||""}function Lt(t,s){t(n=>[...n,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function tn({sendDaemonCommand:t,activeConv:s,updateIdeChats:n,setToasts:r,setLocalUserMessages:i,setClearedTabs:o}){const[c,d]=a.useState(!1),[l,p]=a.useState(!1),u=a.useCallback(async g=>{try{await t("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),x=a.useCallback(async(g,b)=>{try{const w=g||(s==null?void 0:s.daemonId)||"",f=await t(w,"switch_chat",{id:b,sessionId:b,...yt(s)}),y=f==null?void 0:f.result;if((f==null?void 0:f.success)===!0||y==="switched"||y==="switched-by-title")return;y===!1||y==="not_found"?Lt(r,"⚠️ Session tab not found — try refreshing history"):typeof y=="string"&&y.startsWith("error:")?Lt(r,`⚠️ Switch error: ${y}`):Lt(r,"⚠️ Session switch failed")}catch(w){console.error("Switch failed",w),Lt(r,`❌ Switch failed: ${w.message||"connection error"}`)}},[s,t,r]),m=a.useCallback(async()=>{if(!(!s||c)){d(!0);try{const g=Vt(s);await t(g,"new_chat",{...yt(s)}),o(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(g){console.error("New chat failed",g)}finally{d(!1)}}},[s,c,t,o,i]),h=a.useCallback(async()=>{var g;if(!(!s||l)){p(!0);try{const b=Vt(s),w=await t(b,"list_chats",{forceExpand:!0,...yt(s)}),f=(w==null?void 0:w.chats)||((g=w==null?void 0:w.result)==null?void 0:g.chats);w!=null&&w.success&&Array.isArray(f)&&n(s.ideId,f)}catch(b){console.error("Refresh history failed",b)}finally{p(!1)}}},[s,l,t,n]);return{isCreatingChat:c,isRefreshingHistory:l,handleLaunchIde:u,handleSwitchSession:x,handleNewChat:m,handleRefreshHistory:h}}function Co(t,s){if(t.size!==s.size)return!1;for(const[n,r]of t)if(s.get(n)!==r)return!1;return!0}function Io(t,s){return t.length!==s.length?!1:t.every((n,r)=>n===s[r])}function sn(t,s){const n=Object.keys(t),r=Object.keys(s);return n.length!==r.length?!1:n.every(i=>s[Number(i)]===t[Number(i)])}function Dt(t,s){const n=new Set(s),r=s.length>0?[0]:[];for(const[c,d]of t)!n.has(c)||d<=0||r.includes(d)||r.push(d);r.sort((c,d)=>c-d);const i={};r.forEach((c,d)=>{i[c]=d}),r.length===0&&(i[0]=0);const o=new Map;for(const[c,d]of t){if(!n.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,r.length),mapping:i,usedGroups:r}}function nn(t,s){const n={};for(const[r,i]of Object.entries(t)){const o=s[Number(r)];typeof o=="number"&&(n[o]=i)}return n}function Mo(t,s,n){if(s.length===0)return 0;if(typeof n[t]=="number")return n[t];const r=[...s].reverse().find(i=>i<t)??s[0];return n[r]??0}function To(t,s,n){if(s.length<=1)return[];const r=s.map(c=>t[c]).filter(c=>Number.isFinite(c)),i=r.length===s.length?r:Array(n).fill(100/n),o=i.reduce((c,d)=>c+d,0);return o>0?i.map(c=>c/o*100):Array(n).fill(100/n)}function rn(t,s){const n={};for(const[r,i]of Object.entries(t)){const o=Number(r);n[o>=s?o+1:o]=i}return n}function an(t){return Array(t).fill(100/t)}function Ao({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:n,setGroupActiveTabIds:r,setGroupTabOrders:i,groupSizes:o,setGroupSizes:c,isMobile:d,visibleConversations:l,visibleTabKeys:p}){const u=a.useRef(null),x=a.useMemo(()=>Dt(t,p),[t,p]),m=x.assignments,h=a.useMemo(()=>d?1:x.groupCount,[x.groupCount,d]),g=h>1,b=a.useCallback((v,T)=>{s(S=>{const C=new Map(Dt(S,p).assignments);return T===0?C.delete(v):C.set(v,T),C}),r(S=>({...S,[T]:v})),n(T)},[s,p,r,n]),w=a.useCallback(v=>{s(T=>{const S=Dt(T,p).assignments,C=new Map;for(const[_,B]of S)B!==v&&(B>v?C.set(_,B-1):C.set(_,B));return C}),c(T=>{if(T.length<=1)return[];const S=[...T];S.splice(v,1);const C=S.reduce((_,B)=>_+B,0);return C>0?S.map(_=>_/C*100):[]}),n(0)},[s,p,c,n]),f=a.useCallback((v,T)=>{T.preventDefault();const S=u.current;if(!S)return;const C=T.clientX,_=S.offsetWidth,B=o.length===h?[...o]:an(h),H=N=>{const P=(N.clientX-C)/_*100,I=[...B];I[v]=Math.max(15,B[v]+P),I[v+1]=Math.max(15,B[v+1]-P),c(I)},E=()=>{document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",E),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",H),document.addEventListener("mouseup",E)},[o,h,c]),y=a.useCallback((v,T,S)=>{if(h>=4)return;const C=S==="left"?T:T+1;s(_=>{const B=Dt(_,p).assignments,H=new Map;for(const E of l){const N=B.get(E.tabKey)??0,A=N>=C?N+1:N;A>0&&H.set(E.tabKey,A)}return C>0&&H.set(v,C),H}),c(_=>{const B=_.length===h?[..._]:an(h),H=B[T]??100/h,E=Math.max(15,H/2),N=Math.max(15,H/2),A=[...B];A[T]=E,A.splice(C,0,N);const P=A.reduce((I,q)=>I+q,0);return A.map(I=>I/P*100)}),r(_=>{const B=rn(_,C);return B[C]=v,B}),i(_=>{const B=rn(_,C);return B[C]=[v],B}),n(C)},[h,s,p,l,c,r,i,n]);a.useEffect(()=>{Co(t,m)||s(m)},[t,m,s]),a.useEffect(()=>{const{mapping:v,usedGroups:T}=x;r(S=>{const C=nn(S,v);return sn(S,C)?S:C}),i(S=>{const C=nn(S,v);return sn(S,C)?S:C}),n(S=>{const C=d?0:Mo(S,T,v);return S===C?S:C}),c(S=>{const C=d?[]:To(S,T,x.groupCount);return Io(S,C)?S:C})},[x,d,r,i,n,c]);const k=a.useMemo(()=>{const v=Array.from({length:h},()=>[]);for(const T of l){const S=m.get(T.tabKey)??0,C=Math.min(S,h-1);v[C].push(T)}return v},[l,m,h]),j=a.useCallback(()=>{s(new Map),n(0)},[s,n]);return{containerRef:u,normalizedGroupAssignments:m,numGroups:h,isSplitMode:g,groupedConvs:k,moveTabToGroup:b,closeGroup:w,handleResizeStart:f,splitTabRelative:y,clearAllSplits:j}}function Ro({ides:t,sendDaemonCommand:s}){const n="0.7.46",r=a.useMemo(()=>t.filter(p=>{if(p.type!=="adhdev-daemon")return!1;const u=p.version||p.daemonVersion||null;return!u||!n?!1:u!==n}),[n,t]),[i,o]=a.useState(!1),[c,d]=a.useState({}),l=a.useCallback(async p=>{var u,x;d(m=>({...m,[p]:"upgrading"}));try{const m=await s(p,"daemon_upgrade",{});(u=m==null?void 0:m.result)!=null&&u.upgraded||(x=m==null?void 0:m.result)!=null&&x.success?d(h=>({...h,[p]:"done"})):d(h=>({...h,[p]:"error"}))}catch{d(m=>({...m,[p]:"error"}))}},[s]);return{versionMismatchDaemons:r,appVersion:n,versionBannerDismissed:i,setVersionBannerDismissed:o,upgradingDaemons:c,handleBannerUpgrade:l}}function Zt({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:n,setActionLogs:r,isStandalone:i}){const[o,c]=a.useState(!1),[d,l]=a.useState(!1),p=a.useRef(!1),u=a.useCallback(async g=>{if(!s)return;const b=g.trim();if(!b||p.current)return;const w=s.tabKey;p.current=!0,l(!0);const f=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,y={role:"user",content:b,timestamp:Date.now(),_localId:f};n(k=>({...k,[w]:[...k[w]||[],y]}));try{const k=Vt(s);if(!k)return;await t(k,"send_chat",{message:b,text:b,...yt(s)}),setTimeout(()=>{const j=Date.now()-6e4;n(v=>{const T=v[w];if(!T)return v;const S=T.filter(C=>C.timestamp>j);return S.length===T.length?v:{...v,[w]:S}})},6e4)}catch(k){console.error("Send failed",k),n(j=>({...j,[w]:(j[w]||[]).filter(v=>v._localId!==f)}))}finally{p.current=!1,l(!1)}},[s,t,n]),x=a.useCallback(async()=>{if(s)try{await t(s.ideId,"launch_ide",{ideType:s.ideType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[s,t]),m=a.useCallback(async g=>{if(s){r(b=>[...b,{ideId:s.tabKey,text:`🖱️ **${g}** clicked`,timestamp:Date.now()}]);try{const w=(s.modalButtons||[]).indexOf(g),f=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(f),k=Vt(s);if(!k)return;(await t(k,"resolve_action",{button:g,action:y?"approve":"reject",...w>=0&&{buttonIndex:w},...yt(s)})).success||r(v=>[...v,{ideId:s.tabKey,text:`⚠️ **${g}** failed — button not found`,timestamp:Date.now()}])}catch(b){console.error("[ModalButton] Error:",b),r(w=>[...w,{ideId:s.tabKey,text:`❌ **${g}** error`,timestamp:Date.now()}])}}},[s,t,r]),h=a.useCallback(async()=>{if(!(!s||o)){c(!0);try{await t(s.ideId,"focus_session",{agentType:s.agentType,...s.sessionId&&{targetSessionId:s.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{c(!1)}}},[s,o,t]);return{isSendingChat:d,isFocusingAgent:o,handleSendChat:u,handleRelaunch:x,handleModalButton:m,handleFocusAgent:h}}function Lo({selectedConversation:t,isAcp:s,selectedIdeEntry:n,actionLogs:r,userName:i,isSendingChat:o,isFocusingAgent:c,onBack:d,onOpenNativeConversation:l,onOpenMachine:p,onOpenHistory:u,onOpenRemote:x,cliViewMode:m,onSetCliViewMode:h,handleSendChat:g,handleFocusAgent:b}){const w=a.useRef(null),f=Se(t)&&!s,y=f&&m==="terminal";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-mobile-chat-header",children:[e.jsxs("div",{className:"dashboard-mobile-chat-header-row",children:[e.jsx("button",{className:"dashboard-mobile-chat-back",onClick:d,type:"button","aria-label":"Back",children:e.jsx(Cn,{size:18})}),e.jsxs("div",{className:"dashboard-mobile-chat-title-block",children:[e.jsx("div",{className:"dashboard-mobile-chat-title",children:t.displayPrimary||t.agentName}),e.jsx("div",{className:"dashboard-mobile-chat-subtitle",children:e.jsx(Kn,{conversation:t,onOpenNativeConversation:()=>l(t),onOpenMachine:()=>p(t)})})]})]}),e.jsxs("div",{className:"dashboard-mobile-chat-toolbar",children:[f&&m&&e.jsx(Ms,{mode:m,onChange:h,compact:!0}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(t),type:"button",children:e.jsx(ks,{size:14})}),!s&&!f&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(t),type:"button",children:e.jsx(Be,{size:14})})]})]}),e.jsx("div",{className:"dashboard-mobile-chat-thread",children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:y?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(zn,{activeConv:t,terminalRef:w,handleSendChat:g,isSendingChat:o,isVisible:y})}),!y&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(wt,{activeConv:t,ideEntry:n,showMetaChips:!1,handleSendChat:g,isSendingChat:o,handleFocusAgent:b,isFocusingAgent:c,actionLogs:r,userName:i})})]}):e.jsx(wt,{activeConv:t,ideEntry:n,showMetaChips:!1,handleSendChat:g,isSendingChat:o,handleFocusAgent:b,isFocusingAgent:c,actionLogs:r,userName:i},t.tabKey)})]})}const ds={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 Do(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ur(){const[t,s]=a.useState("unix"),[n,r]=a.useState("powershell"),[i,o]=a.useState(!1),c=t==="unix"?"unix":n;a.useEffect(()=>{s(Do())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(ds[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/15 text-accent border border-accent/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/15 text-accent border border-accent/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 ${n==="powershell"?"bg-accent/10 text-accent":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),e.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent/10 text-accent":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-accent cursor-pointer group",onClick:d,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:ds[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:ds[c].cmd}),e.jsx("span",{className:"text-[9px] font-sans text-text-muted 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 mt({icon:t,title:s,subtitle:n,children:r}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:"48px 24px 32px",textAlign:"center"},children:[e.jsx("div",{style:{marginBottom:8},children:t}),e.jsx("div",{style:{fontSize:18,fontWeight:700,letterSpacing:"-0.02em",color:"var(--text-primary)"},children:s}),e.jsx("div",{style:{fontSize:13,lineHeight:1.5,color:"var(--text-secondary)",maxWidth:320},children:n}),r]})}function on({size:t=32,label:s}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:10},children:[e.jsx("div",{style:{width:t,height:t,borderRadius:"50%",border:"2.5px solid color-mix(in srgb, var(--accent-primary) 18%, transparent)",borderTopColor:"var(--accent-primary-light)",animation:"spin 0.9s linear infinite"}}),s&&e.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--accent-primary-light)",letterSpacing:"-0.01em"},children:s})]})}function _o({section:t,attentionItems:s,unreadItems:n,workingItems:r,completedItems:i,hiddenConversations:o,machineCards:c,getAvatarText:d,onOpenConversation:l,onShowConversation:p,onShowAllHidden:u,onOpenMachine:x,onOpenSettings:m,onSectionChange:h,wsStatus:g="connected",isStandalone:b=!1}){const w=g==="disconnected"||g==="reconnecting"||g==="offline"||g==="auth_failed",f=c.length>0,y=s.length>0||n.length>0||r.length>0||i.length>0,k=t==="machines"?"Machines":t==="settings"?"Settings":"Chats";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-mobile-chat-inbox-header",children:[e.jsx("div",{className:"dashboard-mobile-chat-inbox-title",children:e.jsx("div",{className:"dashboard-mobile-chat-app-title",children:e.jsx("span",{children:k})})}),t==="chats"&&(s.length>0||n.length>0)&&e.jsxs("div",{className:"dashboard-mobile-chat-header-pill",children:[e.jsx(Xt,{size:13}),e.jsx("span",{children:s.length+n.length})]})]}),e.jsxs("div",{className:"dashboard-mobile-chat-inbox",children:[t==="chats"&&s.length>0&&e.jsx("section",{className:"dashboard-mobile-chat-section",children:e.jsxs("div",{className:"dashboard-mobile-chat-alert-panel",children:[e.jsx("span",{className:"dashboard-mobile-chat-alert-title",children:"Needs attention"}),e.jsxs("span",{className:"dashboard-mobile-chat-alert-meta",children:[s.length," action needed"]})]})}),t==="chats"&&n.length>0&&e.jsx("section",{className:"dashboard-mobile-chat-section",children:e.jsxs("div",{className:"dashboard-mobile-chat-alert-panel",children:[e.jsx("span",{className:"dashboard-mobile-chat-alert-title",children:"Task complete"}),e.jsxs("span",{className:"dashboard-mobile-chat-alert-meta",children:[n.length," unread"]})]})}),t==="machines"&&e.jsx("section",{className:"dashboard-mobile-chat-section",children:w?e.jsx(mt,{icon:e.jsx(on,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:g==="offline"?"Your device appears to be offline. Waiting for network…":g==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(mt,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:48,height:48,objectFit:"contain",animation:"bounce 3s infinite"}}),title:b?"Waiting for your IDE":"Connect your first machine",subtitle:b?"Launch any supported IDE or CLI agent — it will appear here automatically.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!b&&e.jsx("div",{style:{width:"100%",maxWidth:360,marginTop:16},children:e.jsx(ur,{})})}):c.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card",onClick:()=>x(j.id),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar machine",children:d(j.label)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.label}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:j.unread>0?`${j.unread} new`:j.total>0?`${j.total} chats`:"Idle"})]}),e.jsx("div",{className:"dashboard-mobile-chat-card-subtitle",children:j.subtitle}),j.total>0?e.jsxs("div",{className:"dashboard-mobile-chat-card-preview",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:"No active chats"})]})]},j.id))}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Needs attention"}),s.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card is-unread",onClick:()=>l(j.conversation),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar unread",children:d(j.conversation.displayPrimary)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.conversation.displayPrimary}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:pt(j.timestamp)})]}),e.jsxs("div",{className:"dashboard-mobile-chat-card-subtitle",children:[j.conversation.displaySecondary,j.conversation.machineName&&e.jsxs(e.Fragment,{children:[" · 🖥 ",j.conversation.machineName]})," · Action needed"]}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:j.preview})]}),e.jsx("span",{className:"dashboard-mobile-chat-unread-dot"})]},j.conversation.tabKey))]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Task complete"}),n.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card is-unread",onClick:()=>l(j.conversation),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar unread",children:d(j.conversation.displayPrimary)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.conversation.displayPrimary}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:pt(j.timestamp)})]}),e.jsxs("div",{className:"dashboard-mobile-chat-card-subtitle",children:[j.conversation.displaySecondary,j.conversation.machineName&&e.jsxs(e.Fragment,{children:[" · 🖥 ",j.conversation.machineName]})]}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:j.preview})]}),e.jsx("span",{className:"dashboard-mobile-chat-unread-dot"})]},j.conversation.tabKey))]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Working now"}),r.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card",onClick:()=>l(j.conversation),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar working",children:d(j.conversation.displayPrimary)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.conversation.displayPrimary}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:pt(j.timestamp)})]}),e.jsxs("div",{className:"dashboard-mobile-chat-card-subtitle",children:[j.conversation.displaySecondary,j.conversation.machineName&&e.jsxs(e.Fragment,{children:[" · 🖥 ",j.conversation.machineName]})]}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:j.preview})]}),e.jsx("span",{className:"dashboard-mobile-chat-status-badge",children:"Live"})]},j.conversation.tabKey))]}),t==="chats"&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[i.length>0&&e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Earlier"}),i.length>0?i.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card is-muted",onClick:()=>l(j.conversation),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar",children:d(j.conversation.displayPrimary)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.conversation.displayPrimary}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:pt(j.timestamp)})]}),e.jsxs("div",{className:"dashboard-mobile-chat-card-subtitle",children:[j.conversation.displaySecondary,j.conversation.machineName&&e.jsxs(e.Fragment,{children:[" · 🖥 ",j.conversation.machineName]})]}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:j.preview})]})]},j.conversation.tabKey)):y?e.jsx("div",{className:"dashboard-mobile-chat-empty",children:"All caught up."}):w?e.jsx(mt,{icon:e.jsx(on,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):f?e.jsx(mt,{icon:e.jsx("div",{style:{width:44,height:44,borderRadius:14,display:"flex",alignItems:"center",justifyContent:"center",background:"color-mix(in srgb, var(--accent-primary) 10%, transparent)",color:"var(--accent-primary-light)",fontSize:20},children:"💬"}),title:"No conversations yet",subtitle:"Your machines are connected. Open an IDE or launch a CLI agent to start your first conversation."}):e.jsx(mt,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,objectFit:"contain",opacity:.7}}),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:"dashboard-mobile-chat-section",children:[e.jsxs("div",{className:"dashboard-mobile-chat-section-title dashboard-mobile-chat-section-title-row",children:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"dashboard-mobile-chat-inline-action",onClick:u,children:"Restore all"})]}),o.map(j=>e.jsxs("button",{className:"dashboard-mobile-chat-card is-muted",onClick:()=>p(j),type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar",children:d(j.displayPrimary)}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsxs("div",{className:"dashboard-mobile-chat-card-top",children:[e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:j.displayPrimary}),e.jsx("span",{className:"dashboard-mobile-chat-card-time",children:"Hidden"})]}),e.jsxs("div",{className:"dashboard-mobile-chat-card-subtitle",children:[j.displaySecondary,j.machineName&&e.jsxs(e.Fragment,{children:[" · 🖥 ",j.machineName]})]}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:"Tap to restore and open"})]})]},j.tabKey))]}),t==="settings"&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsxs("button",{className:"dashboard-mobile-chat-card",onClick:m,type:"button",children:[e.jsx("span",{className:"dashboard-mobile-chat-avatar settings",children:e.jsx(Gt,{size:16})}),e.jsxs("div",{className:"dashboard-mobile-chat-card-main",children:[e.jsx("div",{className:"dashboard-mobile-chat-card-top",children:e.jsx("span",{className:"dashboard-mobile-chat-card-title",children:"Appearance & chat settings"})}),e.jsx("div",{className:"dashboard-mobile-chat-card-subtitle",children:"Theme, accent, chat visuals"}),e.jsx("div",{className:"dashboard-mobile-chat-card-preview",children:"Open the full settings page for theme, notifications, and provider preferences."})]})]}),e.jsx("div",{className:"dashboard-mobile-chat-settings-note",children:"Notifications panel: unread and action-needed conversations are surfaced in the Chats section. Mobile workspace mode can be enabled from Settings."})]})]}),e.jsx("div",{className:"dashboard-mobile-chat-nav",children:[["machines","Machines"],["chats","Chats"],["settings","Settings"]].map(([j,v])=>e.jsx("button",{className:`dashboard-mobile-chat-nav-tab${t===j?" is-active":""}`,onClick:()=>h(j),type:"button",children:v},j))})]})}function Eo({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:i,selectedMachineNeedsUpgrade:o,appVersion:c,machineAction:d,onBack:l,onOpenConversation:p,onOpenRecent:u,onOpenMachineDetails:x,onMachineUpgrade:m,onLaunchDetectedIde:h,onAddWorkspace:g,onLaunchWorkspaceProvider:b}){var V,ae,G;const w=(W,ee,F)=>W?"ide":ee>0?"cli":F>0?"acp":null,[f,y]=a.useState(!1),k=W=>W==="ide"?"IDE":W==="cli"?"CLI":"ACP",j=n.slice(0,4),v=s.slice(0,3),T=a.useMemo(()=>{const W=j.map(F=>({key:`recent-launch:${F.id}`,type:"session",primary:F.label,secondary:`${k(F.kind)}${F.subtitle?` · ${F.subtitle}`:""}`,unread:!1,onClick:()=>u(F)})),ee=v.map(F=>({key:`recent-chat:${F.conversation.tabKey}`,type:"conversation",primary:F.conversation.displayPrimary,secondary:`Chat${F.conversation.displaySecondary?` · ${F.conversation.displaySecondary}`:""}${F.timestamp?` · ${pt(F.timestamp)}`:""}`,unread:F.unread,onClick:()=>p(F.conversation)}));return[...W,...ee]},[p,u,v,j]),S=f?T:T.slice(0,5),C=T.length>0,_=(((V=t.detectedIdes)==null?void 0:V.length)||0)>0,B=a.useMemo(()=>t.workspaces||[],[t]),H=t.defaultWorkspaceId||null,[E,N]=a.useState(H||((ae=B[0])==null?void 0:ae.id)||""),[A,P]=a.useState(""),[I,q]=a.useState(w(_,r.length,i.length)),L=a.useRef(null),$=E==="__custom__"?A.trim():((G=B.find(W=>W.id===E))==null?void 0:G.path)||"",D=E==="__custom__"&&!!$&&d.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(d.message);return a.useEffect(()=>{var W;L.current!==t.id&&(L.current=t.id,N(H||((W=B[0])==null?void 0:W.id)||"__custom__"),P(""),q(w(_,r.length,i.length)))},[i.length,r.length,H,_,t.id,B]),a.useEffect(()=>{var W;E!=="__custom__"&&(E&&B.some(ee=>ee.id===E)||N(H||((W=B[0])==null?void 0:W.id)||"__custom__"))},[H,E,B]),a.useEffect(()=>{I==="ide"&&_||I==="cli"&&r.length>0||I==="acp"&&i.length>0||q(w(_,r.length,i.length))},[I,i.length,r.length,_]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"dashboard-mobile-chat-header",children:e.jsxs("div",{className:"dashboard-mobile-chat-header-row",children:[e.jsx("button",{className:"dashboard-mobile-chat-back",onClick:l,type:"button","aria-label":"Back",children:e.jsx(Cn,{size:18})}),e.jsxs("div",{className:"dashboard-mobile-chat-title-block",children:[e.jsx("div",{className:"dashboard-mobile-chat-title",children:qe(t,{fallbackId:t.id})}),e.jsxs("div",{className:"dashboard-mobile-chat-subtitle",children:[t.platform||"machine",t.version?` · v${t.version}`:""]})]})]})}),e.jsxs("div",{className:"dashboard-mobile-chat-inbox",children:[C&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Recent"}),e.jsx("div",{className:"dashboard-mobile-machine-command-grid",children:S.map(W=>e.jsxs("button",{className:`dashboard-mobile-machine-command-card${W.unread?" is-primary":""}`,type:"button",onClick:W.onClick,children:[e.jsx("span",{className:"dashboard-mobile-machine-command-label",children:W.primary}),e.jsx("span",{className:"dashboard-mobile-machine-command-meta",children:W.secondary})]},W.key))}),T.length>5&&e.jsx("div",{className:"dashboard-mobile-machine-more-row",children:e.jsx("button",{type:"button",className:"dashboard-mobile-machine-more-btn",onClick:()=>y(W=>!W),children:f?"Show fewer":`Show ${T.length-5} more`})})]}),(_||r.length>0||i.length>0)&&e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Start"}),e.jsx("div",{className:"dashboard-mobile-machine-command-grid",children:e.jsxs("div",{className:"dashboard-mobile-machine-workspace-card",children:[e.jsx("div",{className:"dashboard-mobile-machine-command-label",children:"Workspace"}),e.jsx("div",{className:"dashboard-mobile-machine-command-meta",children:"Pick a saved workspace or enter a path before choosing IDE, CLI, or ACP."}),e.jsx("select",{value:E,onChange:W=>{N(W.target.value),W.target.value!=="__custom__"&&P("")},className:"dashboard-mobile-machine-workspace-select",children:B.length>0?e.jsxs(e.Fragment,{children:[B.map(W=>e.jsxs("option",{value:W.id,children:[W.id===H?"⭐ ":"",W.label||W.path.split("/").filter(Boolean).pop()||W.path]},W.id)),e.jsx("option",{value:"__custom__",children:"Custom path…"})]}):e.jsx("option",{value:"__custom__",children:"Enter workspace path…"})}),E==="__custom__"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",value:A,onChange:W=>P(W.target.value),placeholder:"/absolute/path",className:"dashboard-mobile-machine-workspace-input"}),e.jsx("button",{type:"button",className:"dashboard-mobile-machine-workspace-save",onClick:()=>{$&&g($)},children:"Save workspace"})]}),$&&e.jsx("div",{className:"dashboard-mobile-machine-workspace-preview",children:$})]})}),e.jsxs("div",{className:"dashboard-mobile-machine-openwith",children:[_&&e.jsx("button",{className:`dashboard-mobile-machine-openwith-btn${I==="ide"?" is-active":""}`,type:"button",onClick:()=>q("ide"),children:"IDE"}),r.length>0&&e.jsx("button",{className:`dashboard-mobile-machine-openwith-btn${I==="cli"?" is-active":""}`,type:"button",onClick:()=>q("cli"),children:"CLI"}),i.length>0&&e.jsx("button",{className:`dashboard-mobile-machine-openwith-btn${I==="acp"?" is-active":""}`,type:"button",onClick:()=>q("acp"),children:"ACP"})]}),I&&e.jsxs("div",{className:"dashboard-mobile-machine-provider-picker",children:[e.jsx("div",{className:"dashboard-mobile-machine-provider-title",children:I==="ide"?"Choose an IDE":I==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"dashboard-mobile-machine-provider-grid",children:I==="ide"?(t.detectedIdes||[]).slice(0,6).map(W=>e.jsxs("button",{type:"button",className:"dashboard-mobile-machine-provider-btn",onClick:()=>h(W.type,{workspacePath:$||null}),children:[e.jsx("span",{className:"dashboard-mobile-machine-provider-name",children:W.name}),e.jsx("span",{className:"dashboard-mobile-machine-provider-meta",children:$||"Use selected workspace"})]},W.type)):(I==="cli"?r:i).map(W=>e.jsxs("button",{type:"button",className:"dashboard-mobile-machine-provider-btn",onClick:()=>b(I,W.type,{workspaceId:E!=="__custom__"?E:null,workspacePath:$||null}),children:[e.jsxs("span",{className:"dashboard-mobile-machine-provider-name",children:[W.icon?`${W.icon} `:"",W.displayName]}),e.jsx("span",{className:"dashboard-mobile-machine-provider-meta",children:$||"Use selected workspace"})]},W.type))})]}),d.message&&e.jsxs("div",{className:`dashboard-mobile-machine-action-note is-${d.state}`,children:[d.message,D&&e.jsx("div",{className:"dashboard-mobile-machine-action-cta-row",children:e.jsx("button",{type:"button",className:"dashboard-mobile-machine-action-cta",onClick:()=>g($,{createIfMissing:!0}),children:"Create folder"})})]})]}),e.jsxs("section",{className:"dashboard-mobile-chat-section",children:[e.jsx("div",{className:"dashboard-mobile-chat-section-title",children:"Inspect"}),e.jsxs("div",{className:"dashboard-mobile-machine-command-grid",children:[o&&e.jsxs("button",{className:"dashboard-mobile-machine-command-card is-primary",type:"button",onClick:m,children:[e.jsxs("span",{className:"dashboard-mobile-machine-command-label",children:["Update to v",c]}),e.jsx("span",{className:"dashboard-mobile-machine-command-meta",children:"Restart this machine with the latest daemon"})]}),e.jsxs("button",{className:"dashboard-mobile-machine-command-card",type:"button",onClick:x,children:[e.jsx("span",{className:"dashboard-mobile-machine-command-label",children:"Machine details"}),e.jsx("span",{className:"dashboard-mobile-machine-command-meta",children:"Sessions, providers, system info, and logs"})]})]})]})]})]})}function Po(t){return Vn(t)}function cn(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1],n=Po(s==null?void 0:s.content);return n||(t.title?t.title:t.displaySecondary||"No messages yet")}function $o(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function _t(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${t}`,s)}catch{}}function Bo({conversations:t,hiddenConversations:s,ides:n,actionLogs:r,sendDaemonCommand:i,setLocalUserMessages:o,setActionLogs:c,isStandalone:d,userName:l,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:m,onOpenHistory:h,onOpenRemote:g,wsStatus:b,isConnected:w,onShowHiddenConversation:f,onShowAllHiddenConversations:y}){const[k,j]=a.useState(()=>{var U;return((U=t[0])==null?void 0:U.tabKey)||null}),[v,T]=a.useState(()=>t[0]?"chat":"inbox"),[S,C]=a.useState("chats"),[_,B]=a.useState(null),[H,E]=a.useState("inbox"),[N,A]=a.useState("idle"),[P,I]=a.useState(""),q=a.useRef(null),L=dt(),$="0.7.46",D=a.useMemo(()=>t.find(U=>U.tabKey===k)||t[0]||null,[t,k]),V=a.useMemo(()=>D?n.find(U=>U.id===D.ideId):void 0,[n,D]),ae=a.useMemo(()=>!D||ye(D)||!Se(D)?null:lt(D),[D]),G=a.useMemo(()=>n.filter(U=>U.type==="adhdev-daemon"||U.daemonMode).sort(ri),[n]),W=a.useMemo(()=>G.find(U=>U.id===_)||null,[G,_]),ee=a.useMemo(()=>St(n),[n]),F=Zt({sendDaemonCommand:i,activeConv:D||void 0,setLocalUserMessages:o,setActionLogs:c,isStandalone:d}),K=a.useCallback(U=>{if(!U||!U.sessionId)return;const z=kt(U,ee),se=Math.max(Date.now(),Jt(U),z.lastUpdated||0);_t("mark_read:start",{tabKey:U.tabKey,sessionId:U.sessionId,displayPrimary:U.displayPrimary,inboxBucket:z.inboxBucket,unread:z.unread,lastSeenAt:z.lastSeenAt,lastUpdated:z.lastUpdated,activityAt:en(U,z.lastUpdated),readAt:se}),i(U.daemonId||U.ideId,"mark_session_seen",{sessionId:U.sessionId,seenAt:se}).then(ie=>{_t("mark_read:result",{tabKey:U.tabKey,sessionId:U.sessionId,result:ie})}).catch(ie=>{_t("mark_read:error",{tabKey:U.tabKey,sessionId:U.sessionId,error:ie instanceof Error?ie.message:String(ie)})})},[ee,i]);a.useEffect(()=>{var z;if(!D){T("inbox"),j(((z=t[0])==null?void 0:z.tabKey)||null),q.current=null;return}if(v!=="chat"){q.current=null;return}const U=`${D.tabKey}:${D.sessionId||""}`;q.current!==U&&(q.current=U,K(D))},[t,K,v,D]),a.useEffect(()=>{if(!p)return;const U=t.find(z=>z.tabKey===p);U&&(j(U.tabKey),T("chat"),u==null||u())},[t,u,p]),a.useEffect(()=>{if(!x)return;const U=G.find(z=>z.id===x);U&&(B(U.id),A("idle"),I(""),C("machines"),E("inbox"),T("machine"),m==null||m())},[G,m,x]);const M=a.useMemo(()=>t.map(U=>{const z=gt(U),se=cn(U),ie=v==="chat"&&(D==null?void 0:D.tabKey)===U.tabKey,fe=zt(U,ee,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ie});return{conversation:U,timestamp:z,preview:se,unread:fe.unread,requiresAction:fe.requiresAction,isWorking:fe.isWorking,inboxBucket:fe.inboxBucket}}).sort((U,z)=>{const se=z.timestamp-U.timestamp;return se!==0?se:ir(U.conversation,z.conversation)}),[t,ee,v,D]);a.useEffect(()=>{const U=M.filter(z=>z.inboxBucket==="task_complete"||z.unread);U.length!==0&&_t("inbox_state",{screen:v,selectedTabKey:k,items:U.map(z=>{const se=kt(z.conversation,ee);return{liveState:se,tabKey:z.conversation.tabKey,sessionId:z.conversation.sessionId,displayPrimary:z.conversation.displayPrimary,serverBucket:se.inboxBucket,computedBucket:z.inboxBucket,serverUnread:se.unread,computedUnread:z.unread,lastSeenAt:se.lastSeenAt,lastUpdated:se.lastUpdated,activityAt:en(z.conversation,se.lastUpdated)}})})},[M,ee,v,k]);const Y=a.useMemo(()=>M.filter(U=>U.requiresAction),[M]),X=a.useMemo(()=>M.filter(U=>U.unread&&!U.requiresAction),[M]),Q=a.useMemo(()=>M.filter(U=>!U.unread&&!U.requiresAction&&U.isWorking),[M]),J=a.useMemo(()=>M.filter(U=>!U.unread&&!U.requiresAction&&!U.isWorking),[M]),oe=a.useMemo(()=>W?M.filter(U=>U.conversation.daemonId===W.id||U.conversation.ideId===W.id):[],[M,W]),me=a.useMemo(()=>{if(!W)return[];const U=W.recentLaunches||[];return U.length>0?U.map(z=>({id:z.id,label:z.title||z.providerName||z.providerType,kind:z.kind,providerType:z.providerType,providerSessionId:z.providerSessionId,subtitle:z.currentModel||z.workspace||void 0,workspace:z.workspace,currentModel:z.currentModel})):n.filter(z=>!z.daemonMode&&z.daemonId===W.id).map(z=>{var ie,fe,be,ge,ue;const se=Ot(z)?"cli":xt(z)?"acp":"ide";return{id:`${se}:${z.type}:${z.workspace||""}`,label:((ie=z.activeChat)==null?void 0:ie.title)||(Ot(z)?z.cliName||z.type:xt(z)&&z.cliName||z.type),kind:se,providerType:z.type,providerSessionId:z.providerSessionId,subtitle:xt(z)?z.currentModel||z.workspace||void 0:z.workspace||void 0,workspace:z.workspace||void 0,currentModel:z.currentModel,timestamp:((ue=(ge=(be=(fe=z.activeChat)==null?void 0:fe.messages)==null?void 0:be.at)==null?void 0:ge.call(be,-1))==null?void 0:ue.timestamp)||0}}).sort((z,se)=>se.timestamp-z.timestamp).map(({timestamp:z,...se})=>se)},[n,W]),he=(W==null?void 0:W.version)||(W==null?void 0:W.daemonVersion)||null,pe=!!W&&!!he&&!0&&he!==$,Z=a.useMemo(()=>(W==null?void 0:W.availableProviders)||[],[W]),R=a.useMemo(()=>Z.filter(U=>U.category==="cli").map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Z]),O=a.useMemo(()=>Z.filter(U=>U.category==="acp").map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Z]),te=a.useMemo(()=>{const U=new Map;for(const z of M){const se=z.conversation.daemonId||z.conversation.ideId,ie=U.get(se);ie?ie.push(z):U.set(se,[z])}return G.map(z=>{const se=U.get(z.id)||[],ie=[...se].sort((Fe,ts)=>ts.timestamp-Fe.timestamp)[0]||null,fe=(ie==null?void 0:ie.conversation)||null,be=se.filter(Fe=>Fe.unread||Fe.requiresAction).length,ge=z.status==="online"?"Connected":z.status||"Unknown",ue=[z.platform||"machine",ge].filter(Boolean);return{id:z.id,label:qe(z,{fallbackId:z.id}),subtitle:ue.join(" · "),unread:be,total:se.length,latestConversation:fe,preview:fe?`${fe.displayPrimary} · ${cn(fe)}`:"No active conversations yet. Open the machine to launch an IDE, CLI, or ACP session."}}).sort((z,se)=>{const ie=Math.max(z.latestConversation?gt(z.latestConversation):0,Ut(G.find(be=>be.id===z.id))),fe=Math.max(se.latestConversation?gt(se.latestConversation):0,Ut(G.find(be=>be.id===se.id)));return fe!==ie?fe-ie:z.label.localeCompare(se.label)})},[M,G]),ne=a.useCallback(U=>{j(U.tabKey),T("chat"),K(U)},[K]),de=a.useCallback(U=>{const z=t.find(se=>se.ideId===U.ideId&&se.streamSource==="native");z&&(j(z.tabKey),T("chat"),K(z))},[t,K]),re=a.useCallback(()=>{K(D),T("inbox")},[K,D]),we=a.useCallback(U=>{B(U),A("idle"),I(""),C("machines"),E("inbox"),T("machine")},[]),Ke=a.useCallback(U=>{var se;const z=U.daemonId||((se=U.ideId)==null?void 0:se.split(":")[0])||U.ideId;z&&(B(z),A("idle"),I(""),C("machines"),E("chat"),T("machine"))},[]),Me=a.useCallback(()=>{T(H)},[H]),De=a.useCallback(async(U,z,se)=>{var ie;try{A("loading"),I(`Launching ${z}…`);const fe={ideType:z,enableCdp:!0};(ie=se==null?void 0:se.workspacePath)!=null&&ie.trim()&&(fe.workspace=se.workspacePath.trim()),await i(U,"launch_ide",fe),A("done"),I(`${z} launch requested`)}catch(fe){A("error"),I(fe instanceof Error?fe.message:"Launch IDE failed"),console.error("Launch IDE failed",fe)}},[i]),Le=a.useCallback(async(U,z,se)=>{if(z.trim())try{A("loading"),I(se!=null&&se.createIfMissing?"Creating folder…":"Saving workspace…");const ie=await i(U,"workspace_add",{path:z.trim(),createIfMissing:(se==null?void 0:se.createIfMissing)===!0});if(ie!=null&&ie.success){A("done"),I(se!=null&&se.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}A("error"),I((ie==null?void 0:ie.error)||"Could not save workspace")}catch(ie){A("error"),I(ie instanceof Error?ie.message:"Could not save workspace")}},[i]),Ye=a.useCallback(async U=>{var z,se,ie,fe,be,ge;try{A("loading"),I("Starting daemon upgrade…");const ue=await i(U,"daemon_upgrade",{});if((z=ue==null?void 0:ue.result)!=null&&z.alreadyLatest){A("done"),I(`Already on v${((se=ue==null?void 0:ue.result)==null?void 0:se.version)||"latest"}.`);return}if((ie=ue==null?void 0:ue.result)!=null&&ie.upgraded||(fe=ue==null?void 0:ue.result)!=null&&fe.success){A("done"),I(`Upgrade to v${((be=ue==null?void 0:ue.result)==null?void 0:be.version)||"latest"} started. Daemon is restarting…`);return}A("error"),I(((ge=ue==null?void 0:ue.result)==null?void 0:ge.error)||"Upgrade failed")}catch(ue){A("error"),I(ue instanceof Error?ue.message:"Upgrade failed")}},[i]),Oe=a.useCallback(async(U,z,se,ie)=>{var fe;try{A("loading"),I(`Launching ${se}…`);const be={cliType:se};(fe=ie==null?void 0:ie.workspacePath)!=null&&fe.trim()?be.dir=ie.workspacePath.trim():ie!=null&&ie.workspaceId&&(be.workspaceId=ie.workspaceId),ie!=null&&ie.resumeSessionId&&(be.resumeSessionId=ie.resumeSessionId);const ge=await i(U,"launch_cli",be),ue=(ge==null?void 0:ge.result)||ge,Fe=(ue==null?void 0:ue.sessionId)||(ue==null?void 0:ue.id);if(ge!=null&&ge.success&&Fe){A("done"),I(`${se} launched`),L(`/dashboard?activeTab=${encodeURIComponent(Fe)}`);return}A("error"),I((ge==null?void 0:ge.error)||(ue==null?void 0:ue.error)||`Could not launch ${z.toUpperCase()} workspace`)}catch(be){A("error"),I(be instanceof Error?be.message:`Could not launch ${z.toUpperCase()} workspace`)}},[L,i]),ze=a.useCallback(async U=>{if(W){if(U.kind==="ide"&&U.providerType){await De(W.id,U.providerType,{workspacePath:U.workspace||null});return}if((U.kind==="cli"||U.kind==="acp")&&U.providerType){await Oe(W.id,U.kind,U.providerType,{workspacePath:U.workspace||null,resumeSessionId:U.providerSessionId||null});return}}},[De,Oe,W]);return e.jsx("div",{className:"dashboard-mobile-chat",children:v==="chat"&&D?e.jsx(Lo,{selectedConversation:D,isAcp:ye(D),selectedIdeEntry:V,actionLogs:r,userName:l,isSendingChat:F.isSendingChat,isFocusingAgent:F.isFocusingAgent,onBack:re,onOpenNativeConversation:de,onOpenMachine:Ke,onOpenHistory:h,onOpenRemote:g,cliViewMode:ae,onSetCliViewMode:async U=>{if(D&&ae!==U)try{await i(D.daemonId||D.ideId,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.ideType||D.agentType,mode:U})}catch(z){console.error("Failed to switch CLI view mode:",z)}},handleSendChat:F.handleSendChat,handleFocusAgent:F.handleFocusAgent}):v==="machine"&&W?e.jsx(Eo,{selectedMachineEntry:W,selectedMachineConversations:oe,selectedMachineRecentLaunches:me,cliProviders:R,acpProviders:O,selectedMachineNeedsUpgrade:pe,appVersion:$,machineAction:{state:N,message:P},onBack:Me,onOpenConversation:ne,onOpenRecent:ze,onOpenMachineDetails:()=>L(`/machines/${W.id}`),onMachineUpgrade:()=>Ye(W.id),onLaunchDetectedIde:(U,z)=>De(W.id,U,z),onAddWorkspace:(U,z)=>Le(W.id,U,z),onLaunchWorkspaceProvider:(U,z,se)=>Oe(W.id,U,z,se)}):e.jsx(_o,{section:S,attentionItems:Y,unreadItems:X,workingItems:Q,completedItems:J,hiddenConversations:s,machineCards:te,getAvatarText:$o,onOpenConversation:ne,onShowConversation:f,onShowAllHidden:y,onOpenMachine:we,onOpenSettings:()=>L("/settings"),onSectionChange:C,wsStatus:b,isConnected:w,isStandalone:d})})}function us(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Ko({conversations:t,numGroups:s,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:i,onClearPreviewOrder:o}){const c=a.useRef(0),[d,l]=a.useState(!1),[p,u]=a.useState(null),x=a.useCallback(()=>{c.current=0,l(!1),u(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const m=a.useCallback(w=>{w.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,l(!0))},[]),h=a.useCallback(w=>{if(!w.dataTransfer.types.includes("text/tab-key"))return;if(w.preventDefault(),!us(s,n)){u("merge");return}const f=w.currentTarget.getBoundingClientRect(),y=w.clientX-f.left,k=f.width/3;y<k?u("split-left"):y>k*2?u("split-right"):u("merge")},[s,n]),g=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,l(!1),u(null))},[]),b=a.useCallback(w=>{c.current=0,l(!1);const f=w.dataTransfer.getData("text/tab-key"),y=f?t.some(j=>j.tabKey===f):!1,k=p;if(u(null),o(),!!f){if(w.preventDefault(),k==="split-left"&&us(s,n)){n==null||n(f,"split-left");return}if(k==="split-right"&&us(s,n)){n==null||n(f,"split-right");return}if(y){i(f);return}r==null||r(f)}},[t,p,s,n,r,i,o]);return{dragOver:d,dropAction:p,resetDragState:x,handleDragEnter:m,handleDragOver:h,handleDragLeave:g,handleDrop:b}}function Wo(t,s){const n=new Set(s.map(o=>o.tabKey)),r=t.filter(o=>n.has(o)),i=s.filter(o=>!t.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...i]}function Oo({conversations:t,initialActiveTabId:s,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:i}){const[o,c]=a.useState(s??null),[d,l]=a.useState(n??[]),[p,u]=a.useState(null),x=a.useRef(null),m=a.useRef(null),h=a.useRef(r),g=a.useRef(i);a.useEffect(()=>{h.current=r},[r]),a.useEffect(()=>{g.current=i},[i]),a.useEffect(()=>{s&&s!==o&&c(s)},[s,o]),a.useEffect(()=>{l(S=>{const C=Wo(S,t);return C.length===S.length&&C.every((_,B)=>_===S[B])?S:C})},[t]);const b=a.useMemo(()=>{const S=p??d;if(S.length===0)return t;const C=new Map(S.map((_,B)=>[_,B]));return[...t].sort((_,B)=>{const H=C.get(_.tabKey)??999,E=C.get(B.tabKey)??999;return H-E})},[t,p,d]);a.useEffect(()=>{var C,_;if(b.length===0){o!==null&&(c(null),(C=h.current)==null||C.call(h,null));return}if(o&&b.some(B=>B.tabKey===o))return;const S=b[0].tabKey;S!==o&&(c(S),(_=h.current)==null||_.call(h,S))},[b,o]);const w=a.useMemo(()=>b.find(S=>S.tabKey===o),[b,o]),f=a.useCallback(S=>{var C;c(S),(C=h.current)==null||C.call(h,S)},[]),y=a.useCallback((S,C,_)=>{l(B=>{var A;const H=B.filter(P=>P!==S),E=H.indexOf(C);if(E<0)return B;const N=_==="left"?E:E+1;return H.splice(N,0,S),(A=g.current)==null||A.call(g,H),H}),u(null)},[]),k=a.useCallback((S,C,_)=>{const H=(d.length>0?d:t.map(A=>A.tabKey)).filter(A=>A!==S),E=H.indexOf(C);if(E<0)return;const N=_==="left"?E:E+1;H.splice(N,0,S),x.current=H,u(H)},[d,t]),j=a.useCallback(()=>{var C;const S=x.current;S&&(l(S),(C=g.current)==null||C.call(g,S))},[]),v=a.useCallback(()=>{x.current=null,u(null)},[]),T=a.useCallback(S=>{l(C=>{var B;const _=C.filter(H=>H!==S);return _.push(S),(B=g.current)==null||B.call(g,_),_})},[]);return{activeTabId:o,activeConv:w,sortedConversations:b,previewOrderRef:x,draggingTabRef:m,selectTab:f,handleTabReorder:y,updatePreviewOrder:k,commitPreviewOrder:j,clearPreviewOrder:v,moveTabToEnd:T,setDraggingTabKey:S=>{m.current=S}}}const hr=a.memo(function({activeConv:s,clearToken:n,isCliTerminal:r,ideEntry:i,screenshotUrl:o,clearScreenshot:c,terminalRef:d,handleModalButton:l,handleRelaunch:p,handleSendChat:u,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:g,userName:b}){const w=a.useCallback(()=>{c()},[c]);return e.jsxs(e.Fragment,{children:[e.jsx(En,{activeConv:s,onModalButton:l}),s.transport!=="pty"&&s.transport!=="acp"&&o?e.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:e.jsx(Oa,{screenshotUrl:o,mode:"preview",onDismiss:w})}):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(Ss,{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:p,children:"Relaunch with CDP"})]})}):null,s.transport==="pty"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:r?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(zn,{activeConv:s,clearToken:n,terminalRef:d,handleSendChat:u,isSendingChat:x,isVisible:r})}),!r&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(wt,{activeConv:s,ideEntry:i,handleSendChat:u,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:g,userName:b})})]}):e.jsx(wt,{activeConv:s,ideEntry:i,handleSendChat:u,isSendingChat:x,handleFocusAgent:m,isFocusingAgent:h,actionLogs:g,userName:b})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.screenshotUrl===s.screenshotUrl&&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);function Uo({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 Rs({conversationsCount:t,isSplitMode:s,isStandalone:n,detectedIdes:r,handleLaunchIde:i}){return t===0&&!s&&r&&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:n?"Launch any supported IDE or CLI agent to start monitoring automatically.":"Install the ADHDev daemon and link your dashboard to start."}),!n&&e.jsx(ur,{}),n&&r.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:"Fast Launch"}),e.jsx("div",{className:"flex flex-wrap gap-2.5 justify-center mt-1",children:r.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(Ln,{size:14,className:"opacity-70"})," Launch ",o.name]},o.type))})]}),!n&&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 mr="adhdev-tab-shortcuts";function zo(){try{return JSON.parse(localStorage.getItem(mr)||"{}")}catch{return{}}}function Fo({sortedTabKeys:t,onFocus:s,onSelectTab:n}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,o]=a.useState(()=>zo()),[c,d]=a.useState(null),l=a.useCallback(u=>{const x=[];return u.metaKey&&x.push(r?"⌘":"Meta"),u.ctrlKey&&x.push("Ctrl"),u.altKey&&x.push(r?"⌥":"Alt"),u.shiftKey&&x.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(x.push(u.key.length===1?u.key.toUpperCase():u.key),x.join("+"))},[r]),p=a.useCallback(u=>{o(u);try{localStorage.setItem(mr,JSON.stringify(u))}catch{}},[]);return a.useEffect(()=>{if(!c)return;const u=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const m=l(x);if(!m)return;const h={...i};for(const[g,b]of Object.entries(h))b===m&&delete h[g];h[c]=m,p(h),d(null)};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[c,i,p,l]),a.useEffect(()=>{const u=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[m,h]of Object.entries(i))if(t.includes(m)&&l(x)===h){x.preventDefault(),s(),n(m);return}}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[i,t,s,n,l]),{isMac:r,tabShortcuts:i,shortcutListening:c,setShortcutListening:d,saveShortcuts:p}}const Ho=a.memo(function({conv:s,isActive:n,isDraggedTab:r,isTaskCompleteUnread:i,shortcut:o,conversationKeys:c,draggingTabRef:d,onFocus:l,onSelectTab:p,onConversationActivated:u,onPreviewReorder:x,onReorderTab:m,onCommitPreviewOrder:h,onClearPreviewOrder:g,onDragStateReset:b,onDragTabKeyChange:w,onReceiveTab:f,onOpenContextMenu:y,longPressTimer:k,isGroupActive:j}){const v=s.status==="generating"?"agent-tab-generating":s.status==="waiting_approval"?"agent-tab-waiting":"",T=s.connectionState==="failed"||s.connectionState==="closed",S=a.useCallback(I=>{d.current=s.tabKey,w(s.tabKey),I.dataTransfer.setData("text/tab-key",s.tabKey),I.dataTransfer.effectAllowed="move"},[s.tabKey,d,w]),C=a.useCallback(()=>{d.current=null,w(null),h(),g(),b()},[d,w,h,g,b]),_=a.useCallback(I=>{const q=d.current;if(!(!q||q===s.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const L=I.currentTarget.getBoundingClientRect(),$=I.clientX<L.left+L.width/2?"left":"right";x(q,s.tabKey,$)}},[s.tabKey,d,x]),B=a.useCallback(I=>{I.preventDefault(),I.stopPropagation();const q=I.dataTransfer.getData("text/tab-key");if(q&&q!==s.tabKey){const L=I.currentTarget.getBoundingClientRect(),$=I.clientX<L.left+L.width/2?"left":"right";c.includes(q)?m(q,s.tabKey,$):f&&f(q)}g()},[s.tabKey,c,m,f,g]),H=a.useCallback(I=>{I.stopPropagation(),l(),p(s.tabKey),u(s)},[s,u,l,p]),E=a.useCallback(I=>{I.preventDefault(),y(I.clientX,I.clientY,s.tabKey)},[s.tabKey,y]),N=a.useCallback(I=>{const q=I.touches[0];k.current=setTimeout(()=>{y(q.clientX,q.clientY,s.tabKey)},600)},[s.tabKey,k,y]),A=a.useCallback(()=>{k.current&&clearTimeout(k.current)},[k]),P=["adhdev-dockview-tab",v,n&&"is-active",j&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:P,draggable:!0,onDragStart:S,onDragEnd:C,onDragOver:_,onDrop:B,onClick:H,onContextMenu:E,onTouchStart:N,onTouchEnd:A,onTouchMove:A,style:{cursor:"pointer",opacity:r?.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:s.status==="generating"?e.jsx("div",{className:"tab-spinner"}):s.status==="waiting_approval"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):s.connectionState==="connecting"||s.connectionState==="new"?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:T?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"Reconnecting…"}):s.connectionState==="connecting"||s.connectionState==="new"?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 Vo({conversations:t,activeTabId:s,groupIndex:n,numGroups:r,unreadTabKeys:i,draggingTabRef:o,onFocus:c,onSelectTab:d,onConversationActivated:l,onPreviewReorder:p,onReorderTab:u,onCommitPreviewOrder:x,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onMoveTab:b,onReceiveTab:w,onHideTab:f,isGroupActive:y}){const[k,j]=a.useState(null),v=a.useRef(null),T=a.useRef(null),S=a.useMemo(()=>t.map(A=>A.tabKey),[t]);Nt("PaneGroupTabBar",{groupIndex:n,activeTabId:s,tabCount:t.length,ctxMenuTab:(k==null?void 0:k.tabKey)||null});const{isMac:C,tabShortcuts:_,shortcutListening:B,setShortcutListening:H,saveShortcuts:E}=Fo({sortedTabKeys:t.map(A=>A.tabKey),onFocus:c,onSelectTab:d});a.useEffect(()=>{if(!k)return;const A=P=>{const I=document.querySelector("[data-pane-context-menu]");I&&I.contains(P.target)||j(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[k]),a.useEffect(()=>{const A=T.current;if(!A)return;const P=I=>{Math.abs(I.deltaY)>Math.abs(I.deltaX)&&(I.preventDefault(),A.scrollLeft+=I.deltaY)};return A.addEventListener("wheel",P,{passive:!1}),()=>A.removeEventListener("wheel",P)},[]);const N=a.useCallback((A,P,I)=>{j({x:A,y:P,tabKey:I})},[]);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:T,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(A=>e.jsx(Ho,{conv:A,isActive:s===A.tabKey,isDraggedTab:o.current===A.tabKey,isTaskCompleteUnread:i.has(A.tabKey),shortcut:_[A.tabKey],conversationKeys:S,draggingTabRef:o,onFocus:c,onSelectTab:d,onConversationActivated:l,onPreviewReorder:p,onReorderTab:u,onCommitPreviewOrder:x,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:w,onOpenContextMenu:N,longPressTimer:v,isGroupActive:y},A.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),k&&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:k.x,top:k.y},children:[b&&n>0&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:()=>{b(k.tabKey,"left"),j(null)},children:"← Move to Left Group"}),b&&n<r-1&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:()=>{b(k.tabKey,"right"),j(null)},children:"Move to Right Group →"}),b&&r<4&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:()=>{b(k.tabKey,"split-left"),j(null)},children:"⇤ Split Left"}),b&&r<4&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:()=>{b(k.tabKey,"split-right"),j(null)},children:"Split Right ⇥"}),e.jsx("div",{className:"border-t border-border-subtle my-1 "}),e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:A=>{A.stopPropagation(),H(k.tabKey),j(null)},children:["⌨ ",_[k.tabKey]?`Change shortcut (${_[k.tabKey]})`:"Set shortcut"]}),_[k.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={..._};delete A[k.tabKey],E(A),j(null)},children:"✕ Remove shortcut"}),f&&e.jsxs(e.Fragment,{children:[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:()=>{f(k.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]}),!b&&!f&&e.jsx("div",{className:"px-3 py-1.5 text-[11px] text-text-muted opacity-50 italic",children:"No actions available"})]}),B&&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:()=>H(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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+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 qo({conversations:t,ides:s,clearedTabs:n,actionLogs:r,screenshotMap:i,setScreenshotMap:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:p,userName:u,groupIndex:x,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:b,onReceiveTab:w,style:f,detectedIdes:y,handleLaunchIde:k,onActiveTabChange:j,initialActiveTabId:v,initialTabOrder:T,onTabOrderChange:S,onHideTab:C,isFocused:_}){const{sendCommand:B}=Qe(),H=a.useRef(null),{activeTabId:E,activeConv:N,sortedConversations:A,draggingTabRef:P,selectTab:I,handleTabReorder:q,updatePreviewOrder:L,commitPreviewOrder:$,clearPreviewOrder:D,moveTabToEnd:V,setDraggingTabKey:ae}=Oo({conversations:t,initialActiveTabId:v,initialTabOrder:T,onActiveTabChange:j,onTabOrderChange:S}),G=Zt({sendDaemonCommand:c,activeConv:N,setLocalUserMessages:d,setActionLogs:l,isStandalone:p}),{dragOver:W,dropAction:ee,resetDragState:F,handleDragEnter:K,handleDragOver:M,handleDragLeave:Y,handleDrop:X}=Ko({conversations:t,numGroups:g,onMoveTab:b,onReceiveTab:w,onOwnTabDrop:V,onClearPreviewOrder:D}),Q=N&&!ye(N)&&lt(N)==="terminal",J=a.useMemo(()=>N?s.find(O=>O.id===N.ideId):void 0,[s,N]),oe=N?i[N.ideId]:void 0,me=a.useCallback(()=>{if(!N||!(N.ideId in i))return;const O={...i};delete O[N.ideId],o(O)},[N,i,o]),he=a.useMemo(()=>N?r.filter(O=>O.ideId===N.tabKey):[],[r,N]),pe=a.useMemo(()=>St(s),[s]),Z=a.useMemo(()=>new Set(A.filter(O=>Fn(O,pe,{isOpenConversation:O.tabKey===E})).map(O=>O.tabKey)),[E,pe,A]);Nt("PaneGroup",{groupIndex:x,conversationCount:t.length,activeTabId:E,dragOver:W});const R=a.useCallback(O=>{O.streamSource==="agent-stream"&&O.agentType&&B(O.ideId,"focus_session",{agentType:O.agentType,...O.sessionId&&{targetSessionId:O.sessionId}}).catch(()=>{})},[B]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...f,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(Vo,{conversations:A,activeTabId:E,groupIndex:x,numGroups:g,unreadTabKeys:Z,draggingTabRef:P,onFocus:m,onSelectTab:I,onConversationActivated:R,onPreviewReorder:L,onReorderTab:q,onCommitPreviewOrder:$,onClearPreviewOrder:D,onDragStateReset:F,onDragTabKeyChange:ae,onMoveTab:b,onReceiveTab:w,onHideTab:C,isGroupActive:_??!1}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:K,onDragOver:M,onDragLeave:Y,onDrop:X,children:[W&&e.jsx(Uo,{dropAction:ee,canSplit:!!(g<4&&b)}),N?e.jsx(hr,{activeConv:N,clearToken:n[N.tabKey]||0,isCliTerminal:!!Q,ideEntry:J,screenshotUrl:oe,clearScreenshot:me,terminalRef:H,handleModalButton:G.handleModalButton,handleRelaunch:G.handleRelaunch,handleSendChat:G.handleSendChat,isSendingChat:G.isSendingChat,handleFocusAgent:G.handleFocusAgent,isFocusingAgent:G.isFocusingAgent,actionLogs:he,userName:u}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Rs,{conversationsCount:t.length,isSplitMode:h,isStandalone:p,detectedIdes:y,handleLaunchIde:k})})]})]})}function Yo({containerRef:t,isSplitMode:s,numGroups:n,groupSizes:r,groupedConvs:i,clearedTabs:o,ides:c,actionLogs:d,screenshotMap:l,setScreenshotMap:p,sendDaemonCommand:u,setLocalUserMessages:x,setActionLogs:m,isStandalone:h,userName:g,focusedGroup:b,setFocusedGroup:w,moveTabToGroup:f,splitTabRelative:y,closeGroup:k,handleResizeStart:j,detectedIdes:v,handleLaunchIde:T,groupActiveTabIds:S,setGroupActiveTabIds:C,groupTabOrders:_,setGroupTabOrders:B,toggleHiddenTab:H}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:i.map((E,N)=>{const A=s&&r.length===n?`${r[N]}%`:void 0;return e.jsxs(vn.Fragment,{children:[s&&N>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:P=>j(N-1,P),onDoubleClick:()=>k(N),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(qo,{style:s?{flexBasis:A??`${100/n}%`,flexGrow:A?0:1,flexShrink:A?0:1}:void 0,conversations:E,clearedTabs:o,ides:c,actionLogs:d,screenshotMap:l,setScreenshotMap:p,sendDaemonCommand:u,setLocalUserMessages:x,setActionLogs:m,isStandalone:h,userName:g,groupIndex:N,isFocused:s&&b===N,onFocus:()=>w(N),isSplitMode:s,numGroups:n,onMoveTab:(P,I)=>{I==="left"&&N>0?f(P,N-1):I==="right"&&N<n-1?f(P,N+1):I==="split-left"&&n<4?y(P,N,"left"):I==="split-right"&&n<4&&y(P,N,"right")},onReceiveTab:P=>f(P,N),detectedIdes:N===0?v:void 0,handleLaunchIde:N===0?T:void 0,onActiveTabChange:P=>C(I=>(I[N]??null)===(P??null)?I:{...I,[N]:P}),initialActiveTabId:S[N],initialTabOrder:_[N],onTabOrderChange:P=>B(I=>{const q=I[N]||[];return q.length===P.length&&q.every((L,$)=>L===P[$])?I:{...I,[N]:P}}),onHideTab:H})]},N)})})}function pr({doId:t,ideId:s,ideType:n,connState:r,viewMode:i,instanceId:o}){const[c,d]=a.useState(null),[l,p]=a.useState(null),u=a.useMemo(()=>{if(!s)return n;const m=s.split(":");return m.length>=3&&m[1]==="ide"?m.slice(2).join(":"):n},[s,n]);a.useEffect(()=>t?je.onScreenshot("ide-page",(h,g)=>{if(h!==t)return;const b=new FileReader;b.onload=()=>d(b.result),b.readAsDataURL(g)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&d(null)},[r]),a.useEffect(()=>{var h;return t?((h=je.onStatus)==null?void 0:h.call(je,(g,b)=>{g===t&&b!=null&&b.screenshotUsage&&p(b.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{d(null)},[t,s,u]),a.useEffect(()=>{const m=t?je.get(t):null;if(!(!m||r!=="connected"))return i!=="chat"&&u?m.startScreenshots(u):m.stopScreenshots(u),()=>{m.stopScreenshots(u)}},[i,r,u,t]);const x=a.useCallback(async(m,h)=>{const g=t?je.get(t):null;return!g||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):g.sendInput(m,h,o||u)},[t,r,o,u]);return{connScreenshot:c,screenshotUsage:l,handleRemoteAction:x}}const xr=a.createContext(null);function Qt(){const t=a.useContext(xr);if(!t)throw new Error("DashboardDockviewContext missing");return t}function Bt(t){return t.displayPrimary||t.title||t.agentName||t.tabKey}function Go(t){return`remote:${t}`}function qt(t){return t.startsWith("remote:")}function es(t,s){return t.find(n=>n.ideId===s&&n.streamSource==="native")??t.find(n=>n.ideId===s)??null}function Xo(t){const[,s]=a.useState(0);a.useEffect(()=>{const n=()=>s(i=>i+1),r=[t.api.onDidActiveGroupChange(n),t.api.onDidTitleChange(n),t.api.onDidGroupChange(n),t.containerApi.onDidActivePanelChange(n)];return()=>{for(const i of r)i.dispose()}},[t.api,t.containerApi])}function Jo(t,s,n){var d;const r=[s];let i;for(const l of r){let p;for(const u of l){const x=t.addPanel({id:u.tabKey,component:"conversation",title:Bt(u),params:{kind:"conversation",tabKey:u.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:i?{position:{referencePanel:i,direction:"right"},inactive:!0}:{}});p||(p=x.id)}i=p??i}const o=n??((d=s[0])==null?void 0:d.tabKey)??null;if(!o)return;const c=t.getPanel(o);c&&c.group.model.openPanel(c)}function ln(t,s){const n=new Set(s.map(r=>r.tabKey));for(const r of[...t.panels])qt(r.id)||n.has(r.id)||t.removePanel(r);for(const r of s){const i=t.getPanel(r.tabKey);if(i){i.update({params:{tabKey:r.tabKey}}),i.title!==Bt(r)&&i.api.setTitle(Bt(r));continue}t.addPanel({id:r.tabKey,component:"conversation",title:Bt(r),params:{kind:"conversation",tabKey:r.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 dn(t,s,n){var l,p;const r=n?Go(n):null;for(const u of[...t.panels])qt(u.id)&&(!r||u.id!==r)&&t.removePanel(u);if(!n||!r)return;const i=es(s,n);if(!i&&t.totalPanels===0)return;const o=t.getPanel(r),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)??((p=t.panels.find(u=>!qt(u.id)))==null?void 0:p.id);t.addPanel({id:r,component:"remote",title:c,params:{kind:"remote",ideId:n},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function Zo({params:t}){const s=Qt(),n=a.useRef(null),r=s.conversationsByTabKey.get(t.tabKey),i=Zt({sendDaemonCommand:s.sendDaemonCommand,activeConv:r,setLocalUserMessages:s.setLocalUserMessages,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone}),o=a.useMemo(()=>r?s.ides.find(u=>u.id===r.ideId):void 0,[s.ides,r]),c=r?s.screenshotMap[r.ideId]:void 0,d=a.useCallback(()=>{if(!r||!(r.ideId in s.screenshotMap))return;const u={...s.screenshotMap};delete u[r.ideId],s.setScreenshotMap(u)},[r,s]),l=a.useMemo(()=>r?s.actionLogs.filter(u=>u.ideId===r.tabKey):[],[s.actionLogs,r]);if(!r)return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:e.jsx(Rs,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,detectedIdes:s.detectedIdes,handleLaunchIde:s.handleLaunchIde})});const p=!ye(r)&&lt(r)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(hr,{activeConv:r,clearToken:s.clearedTabs[r.tabKey]||0,isCliTerminal:p,ideEntry:o,screenshotUrl:c,clearScreenshot:d,terminalRef:n,handleModalButton:i.handleModalButton,handleRelaunch:i.handleRelaunch,handleSendChat:i.handleSendChat,isSendingChat:i.isSendingChat,handleFocusAgent:i.handleFocusAgent,isFocusingAgent:i.isFocusingAgent,actionLogs:l,userName:s.userName})})}function Qo({params:t}){var l;const s=Qt(),n=a.useMemo(()=>es([...s.conversationsByTabKey.values()],t.ideId),[s.conversationsByTabKey,t.ideId]),r=a.useMemo(()=>s.ides.find(p=>p.id===t.ideId),[s.ides,t.ideId]),i=(n==null?void 0:n.daemonId)||((l=n==null?void 0:n.ideId)==null?void 0:l.split(":")[0])||t.ideId.split(":")[0]||t.ideId,{connScreenshot:o,screenshotUsage:c,handleRemoteAction:d}=pr({doId:i,ideId:t.ideId,ideType:(n==null?void 0:n.ideType)||(r==null?void 0:r.type),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote",instanceId:r==null?void 0:r.instanceId});return n?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(_n,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:c,transportType:n.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 ec(){const t=Qt();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Rs,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function tc(t){var u,x;Xo(t);const s=Qt();if(t.params.kind==="remote"){const m=es([...s.conversationsByTabKey.values()],t.params.ideId),h=((u=t.api.group.activePanel)==null?void 0:u.id)===t.api.id,g=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${g?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(m==null?void 0:m.tabKey)||"",children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:m!=null&&m.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:m.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const r=((x=t.api.group.activePanel)==null?void 0:x.id)===t.api.id,i=t.api.isGroupActive,o=n.connectionState==="failed"||n.connectionState==="closed",c=n.connectionState==="connecting"||n.connectionState==="new",d=n.status==="generating",l=n.status==="waiting_approval",p=Fn(n,s.liveSessionInboxState,{isOpenConversation:r});return e.jsxs("div",{className:`adhdev-dockview-tab${r?" is-active":""}${i?" is-group-active":""}${o?" is-reconnecting":""}`,title:n.displayPrimary,"data-tab-key":t.params.tabKey,children:[p&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:d?e.jsx("div",{className:"tab-spinner"}):l?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):o?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):c?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:o?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"Reconnecting…"}):c?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]})]})]})})]})]})}function sc({visibleConversations:t,clearedTabs:s,ides:n,actionLogs:r,screenshotMap:i,setScreenshotMap:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:p,userName:u,detectedIdes:x,handleLaunchIde:m,toggleHiddenTab:h,onActiveTabChange:g,requestedActiveTabKey:b,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:f}){const{theme:y}=er(),{sendCommand:k}=Qe(),j=a.useRef(null),v=a.useRef(null),T=a.useRef(!1),[S,C]=a.useState(!1),[_,B]=a.useState(!1),H=a.useRef(null),E=a.useMemo(()=>cr(typeof window<"u"?window.innerWidth:1280),[]),N=a.useMemo(()=>new Map(t.map(G=>[G.tabKey,G])),[t]),A=a.useMemo(()=>St(n),[n]),P=a.useMemo(()=>({actionLogs:r,clearedTabs:s,conversationsByTabKey:N,detectedIdes:x,handleLaunchIde:m,ides:n,isStandalone:p,liveSessionInboxState:A,screenshotMap:i,sendDaemonCommand:c,setActionLogs:l,setLocalUserMessages:d,setScreenshotMap:o,toggleHiddenTab:h,userName:u}),[r,s,N,x,m,n,p,A,i,c,l,d,o,h,u]),I=a.useCallback(G=>{if(!G)return!1;const W=j.current;if(!W)return!1;const ee=W.getPanel(G);return ee?(ee.group.model.openPanel(ee),f==null||f(),!0):!1},[f]),q=a.useCallback(()=>{const G=v.current;if(!G)return;const W=G.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const ee of W)ee.setAttribute("data-adhdev-force-hidden","true")},[]),L=a.useCallback(()=>{const G=v.current;if(!G)return;const W=G.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const ee of W)ee.removeAttribute("data-adhdev-force-hidden")},[]),$=a.useCallback(()=>{const G=v.current;if(!G)return;const W=G.querySelectorAll(".dv-drop-target-container");for(const K of W)K.remove();const ee=G.querySelectorAll(".dv-drop-target-dropzone");for(const K of ee)K.remove();const F=G.querySelectorAll(".dv-drop-target");for(const K of F)K.classList.remove("dv-drop-target")},[]),D=a.useCallback(()=>{C(!1),B(!1),L(),q(),$(),!(typeof window>"u")&&(H.current!=null&&window.clearTimeout(H.current),window.requestAnimationFrame(()=>{q(),$()}),H.current=window.setTimeout(()=>{q(),$(),H.current=null},80))},[L,q,$]),V=a.useCallback(G=>{var ee;j.current=G.api;const W=vo(E);W!=null&&W.layout&&G.api.fromJSON(W.layout,{reuseExistingPanels:!1}),ln(G.api,t),dn(G.api,t,w),G.api.totalPanels===0&&t.length>0?Jo(G.api,t,b):I(b)||I(W==null?void 0:W.activeTabId),T.current=!0,G.api.onDidActivePanelChange(F=>{var M;if(F&&qt(F.id)){const Y=((M=F.params)==null?void 0:M.ideId)||F.id.slice(7),X=es(t,Y);g((X==null?void 0:X.tabKey)??null);return}if(g((F==null?void 0:F.id)??null),!F)return;const K=N.get(F.id);(K==null?void 0:K.streamSource)==="agent-stream"&&K.agentType&&k(K.ideId,"focus_session",{agentType:K.agentType,...K.sessionId&&{targetSessionId:K.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{var F;jo(E,{activeTabId:((F=G.api.activePanel)==null?void 0:F.id)??null,layout:G.api.toJSON()})}),G.api.onWillDragPanel(()=>{C(!0),B(!1),q()}),G.api.onWillDragGroup(()=>{C(!0),B(!1),q()}),G.api.onWillShowOverlay(()=>{L(),B(!0)}),G.api.onDidMovePanel(D),G.api.onDidDrop(D),g(((ee=G.api.activePanel)==null?void 0:ee.id)??null)},[I,D,L,N,E,q,$,g,b,k,t]);a.useEffect(()=>{const G=j.current;!G||!T.current||(ln(G,t),dn(G,t,w),!G.activePanel&&G.panels[0]&&G.panels[0].group.model.openPanel(G.panels[0]))},[w,t]),a.useEffect(()=>{T.current&&I(b)},[I,b]),a.useEffect(()=>{if(!S||typeof window>"u")return;const G=()=>D();return window.addEventListener("pointerup",G),window.addEventListener("mouseup",G),window.addEventListener("dragend",G),()=>{window.removeEventListener("pointerup",G),window.removeEventListener("mouseup",G),window.removeEventListener("dragend",G)}},[D,S]),a.useEffect(()=>()=>{typeof window>"u"||H.current!=null&&window.clearTimeout(H.current)},[]),a.useEffect(()=>{const G=W=>{const ee=W.target;if(!ee)return;const F=ee.querySelector("[data-tab-key]")||ee.closest("[data-tab-key]");if(F){const K=F.getAttribute("data-tab-key");K&&W.dataTransfer&&W.dataTransfer.setData("text/tab-key",K)}};return window.addEventListener("dragstart",G),()=>window.removeEventListener("dragstart",G)},[]);const ae=y==="light"?Qr:ea;return e.jsx(xr.Provider,{value:P,children:e.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Zr,{className:`h-full min-h-0 min-w-0 adhdev-dockview${S?" is-dragging-dockview":""}${_?" is-showing-dockview-overlay":""}`,components:{conversation:Zo,remote:Qo},defaultTabComponent:tc,watermarkComponent:ec,onReady:V,singleTabMode:"default",tabAnimation:"smooth",theme:ae})})})}function nc({showMobileChatMode:t,isMobile:s,activeConv:n,chatIdes:r,wsStatus:i,isConnected:o,onOpenHistory:c,onOpenRemote:d,onStopCli:l,activeCliViewMode:p,onSetActiveCliViewMode:u,mobileChatConversations:x,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:b,setLocalUserMessages:w,setActionLogs:f,isStandalone:y,userName:k,requestedMobileTabKey:j,onRequestedMobileTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:S,containerRef:C,isSplitMode:_,numGroups:B,groupSizes:H,groupedConvs:E,clearedTabs:N,screenshotMap:A,setScreenshotMap:P,focusedGroup:I,setFocusedGroup:q,moveTabToGroup:L,splitTabRelative:$,closeGroup:D,handleResizeStart:V,detectedIdes:ae,handleLaunchIde:G,groupActiveTabIds:W,setGroupActiveTabIds:ee,groupTabOrders:F,setGroupTabOrders:K,toggleHiddenTab:M,visibleConversations:Y,requestedDesktopTabKey:X,onRequestedDesktopTabConsumed:Q,onDesktopActiveTabChange:J,onOpenDesktopConversation:oe,onHideConversation:me,onShowHiddenConversation:he,onShowAllHiddenConversations:pe}){return vn.useEffect(()=>{const Z=R=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?R.metaKey&&R.key.toLowerCase()==="w":R.ctrlKey&&R.key.toLowerCase()==="w")&&(R.preventDefault(),n&&me&&me(n))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[n,me]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(xi,{activeConv:n,agentCount:r.length,wsStatus:i,isConnected:o,conversations:Y,hiddenConversations:m,onOpenHistory:c,onOpenConversation:oe,onHideConversation:me,onShowConversation:he,onShowAllHidden:pe,onOpenRemote:()=>{!n||Se(n)||ye(n)||d(n)},onStopCli:l,activeCliViewMode:p,onSetCliViewMode:u}),t?e.jsx(Bo,{conversations:x,hiddenConversations:m,ides:h,actionLogs:g,sendDaemonCommand:b,setLocalUserMessages:w,setActionLogs:f,isStandalone:y,userName:k,requestedActiveTabKey:j,onRequestedActiveTabConsumed:v,requestedMachineId:T,onRequestedMachineConsumed:S,onOpenHistory:c,onOpenRemote:d,wsStatus:i,isConnected:o,onShowHiddenConversation:he,onShowAllHiddenConversations:pe}):s?e.jsx(Yo,{containerRef:C,isSplitMode:_,numGroups:B,groupSizes:H,groupedConvs:E,clearedTabs:N,ides:h,actionLogs:g,screenshotMap:A,setScreenshotMap:P,sendDaemonCommand:b,setLocalUserMessages:w,setActionLogs:f,isStandalone:y,userName:k,focusedGroup:I,setFocusedGroup:q,moveTabToGroup:L,splitTabRelative:$,closeGroup:D,handleResizeStart:V,detectedIdes:ae,handleLaunchIde:G,groupActiveTabIds:W,setGroupActiveTabIds:ee,groupTabOrders:F,setGroupTabOrders:K,toggleHiddenTab:M}):e.jsx(sc,{visibleConversations:Y,clearedTabs:N,ides:h,actionLogs:g,screenshotMap:A,setScreenshotMap:P,sendDaemonCommand:b,setLocalUserMessages:w,setActionLogs:f,isStandalone:y,userName:k,detectedIdes:ae,handleLaunchIde:G,toggleHiddenTab:M,onActiveTabChange:J,requestedActiveTabKey:X,onRequestedActiveTabConsumed:Q})]})}const hs=[{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 rc({onClose:t}){const[s,n]=a.useState(0),r=hs[s],i=s===hs.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:hs.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:r.visual||r.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:r.icon})," ",r.title]}),e.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:r.desc}),r.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:"$"}),r.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():n(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:`
54
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
55
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
56
- `})]})}function ac({hasExtensions:t,ideName:s,activeChatTab:n,extensionTabs:r,onSelectTab:i}){return t?e.jsxs("div",{className:"ide-chat-tabs",children:[e.jsx("button",{className:`ide-chat-tab ${n==="native"?"active":""}`,onClick:()=>i("native"),children:s}),r.map(o=>{const c=n===o.tabKey,d=o.status==="waiting_approval",l=o.status==="generating";return e.jsxs("button",{className:`ide-chat-tab ${c?"active":""}`,onClick:()=>i(o.tabKey),children:[e.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",marginRight:5,background:d?"var(--status-warning)":l?"var(--accent-primary)":"#64748b",boxShadow:l?"0 0 6px var(--accent-primary)":"none"}}),o.title,d&&e.jsx("span",{className:"ide-ext-badge",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)",marginLeft:4},children:"!"})]},o.tabKey)})]}):null}function ic({ideData:t,allIdes:s,connectionStates:n,localUserMessages:r,ideName:i,preferredTabKey:o}){const[c,d]=a.useState(()=>o||"native"),l=a.useMemo(()=>qn(s),[s]),p=a.useMemo(()=>{var w;if(!t)return[];const b=t.daemonId||((w=t.id)==null?void 0:w.split(":")[0])||t.id;return Yn(t,r,{machineName:t.daemonId&&l[t.daemonId]||void 0,connectionState:n[b]||"new"})},[t,r,l,n]),u=a.useMemo(()=>p.find(b=>b.streamSource==="native"),[p]),x=a.useMemo(()=>p.filter(b=>b.streamSource==="agent-stream"),[p]);a.useEffect(()=>{o&&d(o)},[o]),a.useEffect(()=>{var b;c!=="native"&&(x.some(w=>w.tabKey===c)||d(((b=x[0])==null?void 0:b.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(u||x[0]&&d(x[0].tabKey))},[c,u,x]);const m=a.useMemo(()=>c==="native"&&u?u:x.find(b=>b.tabKey===c)||u||x[0],[c,u,x]),h=a.useMemo(()=>x.map(b=>({tabKey:b.tabKey,title:b.title||b.agentName||i,status:b.status})),[x,i]),g=a.useCallback(b=>{if(b)return p.find(w=>w.sessionId===b||w.ideId===b||w.tabKey===b||w.ideType===b||w.agentType===b)},[p]);return{activeChatTab:c,setActiveChatTab:d,activeConv:m,conversations:p,extensionTabs:h,hasExtensions:h.length>0,resolveConversationByTarget:g}}function oc({activeConv:t,ideEntry:s,ides:n,connectionStates:r,actionLogs:i,localUserMessages:o,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:l,isStandalone:p,userName:u,onOpenHistory:x,onConversationChange:m,onClose:h}){var P;const[g,b]=a.useState("split"),[w,f]=a.useState(()=>t.streamSource==="native"?"native":t.tabKey),y=a.useMemo(()=>s||n.find(I=>I.id===t.ideId),[t.ideId,s,n]),k=a.useMemo(()=>Ne((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:j,extensionTabs:v,hasExtensions:T}=ic({ideData:y,allIdes:n,connectionStates:r,localUserMessages:o,ideName:k||"IDE",preferredTabKey:t.streamSource==="native"?"native":t.tabKey});a.useEffect(()=>{f(t.streamSource==="native"?"native":t.tabKey)},[t.streamSource,t.tabKey]);const S=a.useMemo(()=>w==="native"?j.find(I=>I.streamSource==="native")||t:j.find(I=>I.tabKey===w)||t,[t,j,w]),C=S.daemonId||((P=S.ideId)==null?void 0:P.split(":")[0])||S.ideId,_=Zt({sendDaemonCommand:c,activeConv:S,setLocalUserMessages:d,setActionLogs:l,isStandalone:p}),{connScreenshot:B,screenshotUsage:H,handleRemoteAction:E}=pr({doId:C,ideId:S.ideId,ideType:S.ideType,connState:S.connectionState||"new",viewMode:g,instanceId:y==null?void 0:y.instanceId}),N=a.useMemo(()=>i.filter(I=>I.ideId===S.tabKey),[i,S.tabKey]);a.useEffect(()=>{m==null||m(S)},[S,m]),a.useEffect(()=>{const I=q=>{q.key==="Escape"&&h()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[h]);const A=a.useCallback(I=>{I.stopPropagation()},[]);return e.jsx("div",{className:"dashboard-remote-dialog-overlay",onClick:h,children:e.jsxs("div",{className:"dashboard-remote-dialog is-fullscreen",role:"dialog","aria-modal":"true",onClick:A,children:[e.jsxs("div",{className:"dashboard-remote-dialog-header",children:[e.jsx("div",{className:"dashboard-remote-dialog-title-block",children:e.jsxs("div",{className:"dashboard-remote-dialog-title",children:[e.jsx(Be,{size:16}),e.jsx("span",{children:S.displayPrimary||S.agentName||"Remote"})]})}),e.jsxs("div",{className:"dashboard-remote-dialog-actions",children:[["split","remote"].map(I=>e.jsx("button",{className:`btn btn-secondary btn-sm dashboard-remote-dialog-mode${g===I?" is-active":""}`,onClick:()=>b(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?"⊞":e.jsx(Be,{size:14})},I)),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(S),title:"Chat History",children:e.jsx(ks,{size:14})}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:h,children:"Close"})]})]}),e.jsxs("div",{className:`dashboard-remote-dialog-body view-${g}`,children:[g!=="remote"&&e.jsxs("div",{className:"dashboard-remote-dialog-chat",children:[e.jsx(ac,{hasExtensions:T,ideName:k||"IDE",activeChatTab:w,extensionTabs:v,onSelectTab:f}),e.jsx(En,{activeConv:S,onModalButton:_.handleModalButton}),e.jsx(wt,{activeConv:S,ideEntry:y,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:N,userName:u})]}),e.jsx("div",{className:"dashboard-remote-dialog-remote",children:e.jsx(_n,{addLog:()=>{},connState:S.connectionState||"new",connScreenshot:B,screenshotUsage:H,transportType:S.transport,onAction:E})})]})]})})}function cc({activeConv:t,onCancel:s,onStopNow:n,onSaveAndStop:r}){const i=t.agentName||t.ideType||"CLI";return e.jsxs("div",{className:"fixed inset-0 z-[1000] flex items-center justify-center",children:[e.jsx("div",{onClick:s,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-[92%] 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-6 py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[e.jsxs("h3",{className:"m-0 text-lg font-extrabold",children:["Stop ",i,"?"]}),e.jsx("div",{className:"mt-1 text-sm text-text-muted",children:"The CLI runtime will stop. Choose whether to stop immediately or ask the provider to save and exit first."})]}),e.jsxs("div",{className:"px-6 py-5 bg-bg-primary flex flex-col gap-3",children:[e.jsx("button",{onClick:r,className:"btn btn-primary w-full justify-center",children:"Save and stop"}),e.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Stop now"}),e.jsx("button",{onClick:s,className:"btn btn-secondary w-full justify-center",children:"Cancel"})]})]})]})}function lc({historyModalOpen:t,historyTargetConv:s,ides:n,isHistoryCreatingChat:r,isHistoryRefreshingHistory:i,savedHistorySessions:o,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:l,onNewHistoryChat:p,onSwitchHistorySession:u,onRefreshHistory:x,onResumeSavedHistorySession:m,remoteDialogConv:h,remoteDialogIdeEntry:g,connectionStates:b,actionLogs:w,localUserMessages:f,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:j,isStandalone:v,userName:T,onOpenRemoteHistory:S,onRemoteConversationChange:C,onCloseRemoteDialog:_,cliStopDialogOpen:B,activeConv:H,onCancelCliStop:E,onStopCliNow:N,onSaveCliAndStop:A,toasts:P,onDismissToast:I,onClickToast:q,showOnboarding:L,onCloseOnboarding:$}){return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(bi,{activeConv:s,ides:n,isCreatingChat:r,isRefreshingHistory:i,savedSessions:o,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:l,onNewChat:p,onSwitchSession:u,onRefreshHistory:x,onResumeSavedSession:m}),h&&e.jsx(oc,{activeConv:h,ideEntry:g,ides:n,connectionStates:b,actionLogs:w,localUserMessages:f,sendDaemonCommand:y,setLocalUserMessages:k,setActionLogs:j,isStandalone:v,userName:T,onOpenHistory:S,onConversationChange:C,onClose:_}),B&&H&&Se(H)&&!ye(H)&&e.jsx(cc,{activeConv:H,onCancel:E,onStopNow:N,onSaveAndStop:A}),e.jsx(Hn,{toasts:P,onDismiss:I,onClickToast:q}),L&&e.jsx(rc,{onClose:$})]})}function dc({daemons:t,targetVersion:s,upgradingDaemons:n,onUpgrade:r,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(Ns,{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=qe(o,{fallbackId:o.id}),d=n[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:()=>r(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:()=>r(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 uc(){var Es,Ps;const{sendCommand:t}=Qe(),s=js(),n=dt(),[r,i]=ta(),o=r.get("activeTab"),c=((Es=s.state)==null?void 0:Es.openRemoteForTabKey)||null,d=((Ps=s.state)==null?void 0:Ps.openMachineId)||null,l=Is(),{updateIdeChats:p,screenshotMap:u,setScreenshotMap:x}=l,m=l.ides||[],[h,g]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=l.toasts||[],w=l.setToasts||(()=>{}),f=l.wsStatus||"connected",y=l.isConnected??!0,k=l.connectionStates||{},j=l.showReconnected||!1,{groupAssignments:v,setGroupAssignments:T,focusedGroup:S,setFocusedGroup:C,groupActiveTabIds:_,setGroupActiveTabIds:B,groupTabOrders:H,setGroupTabOrders:E,groupSizes:N,setGroupSizes:A,isMobile:P,hasHydratedStoredLayout:I,hydrateStoredLayout:q}=ko(),[L,$]=a.useState(!1),[D,V]=a.useState(!1),[ae,G]=a.useState([]),[W,ee]=a.useState(!1),[F,K]=a.useState(null),[M]=a.useState(()=>rr()),[Y,X]=a.useState([]),[Q,J]=a.useState({}),[oe,me]=a.useState({}),[he,pe]=a.useState(null);Nt("Dashboard",{ideCount:m.length,toastCount:b.length,focusedGroup:S,groupCount:Object.keys(v).length,localMessageTabs:Object.keys(Q).length,actionLogCount:Y.length});const Z=m.find(le=>le.type==="adhdev-daemon"),R=(Z==null?void 0:Z.detectedIdes)||[],O=!!Z,te=(Z==null?void 0:Z.terminalBackend)||null,{hiddenTabs:ne,hideTab:de,toggleTab:re,showTab:we,showAllTabs:Ke}=io(),{chatIdes:Me,conversations:De,visibleConversations:Le,visibleTabKeys:Ye,resolveConversationBySessionId:Oe,resolveConversationByTarget:ze}=mo({ides:m,connectionStates:k,localUserMessages:Q,clearedTabs:oe,hiddenTabs:ne}),U=a.useMemo(()=>St(m),[m]),z=a.useRef(null),{containerRef:se,normalizedGroupAssignments:ie,numGroups:fe,isSplitMode:be,groupedConvs:ge,moveTabToGroup:ue,closeGroup:Fe,handleResizeStart:ts,splitTabRelative:fr}=Ao({groupAssignments:v,setGroupAssignments:T,setFocusedGroup:C,setGroupActiveTabIds:B,setGroupTabOrders:E,groupSizes:N,setGroupSizes:A,isMobile:P,visibleConversations:Le,visibleTabKeys:Ye}),ce=a.useMemo(()=>{var ve,ke;if(!P){if(he){const Ce=De.find(Ee=>Ee.tabKey===he);if(Ce)return Ce}return Le[0]}const le=_[S];if(le){const Ce=De.find(Ee=>Ee.tabKey===le);if(Ce)return Ce}return((ve=ge[S])==null?void 0:ve[0])||((ke=ge[0])==null?void 0:ke[0])},[he,P,_,S,De,ge,Le]);a.useEffect(()=>{if(P){z.current=null;return}if(!(ce!=null&&ce.sessionId)){z.current=null;return}const le=`${ce.tabKey}:${ce.sessionId}`;if(z.current===le)return;z.current=le;const ve=kt(ce,U),ke=Math.max(Date.now(),Jt(ce),ve.lastUpdated||0);t(ce.daemonId||ce.ideId,"mark_session_seen",{sessionId:ce.sessionId,seenAt:ke}).catch(()=>{})},[ce,P,U,t]);const{requestedDesktopTabKey:Ls,requestedMobileTabKey:br,consumeRequestedActiveTab:Ds}=po({isMobile:P,urlActiveTab:o,resolveConversationBySessionId:Oe,setSearchParams:i}),{remoteDialogConv:_s,remoteDialogIdeEntry:gr,remoteDialogActiveConv:yr,setRemoteDialogActiveConv:ss,openRemoteDialog:vr,closeRemoteDialog:jr}=So({isMobile:P,location:s,navigate:n,requestedRemoteTabTarget:c,requestedDesktopTabKey:Ls,conversations:De,ides:m,resolveConversationByTarget:ze}),Te=yr||_s||ce,Ge=!!Te&&Se(Te)&&!ye(Te),wr=a.useMemo(()=>Le,[Le]),Ct=P&&M==="chat",kr=a.useMemo(()=>De.filter(le=>ne.has(le.tabKey)),[De,ne]);oo({visibleConversations:Le,clearedTabs:oe,setClearedTabs:me,setActionLogs:X}),xo({ides:m,sendDaemonCommand:t,setToasts:w,setLocalUserMessages:J,resolveConversationByTarget:ze});const{isRefreshingHistory:Nr,handleLaunchIde:Sr,handleRefreshHistory:Cr}=tn({sendDaemonCommand:t,activeConv:ce,updateIdeChats:p,setToasts:w,setLocalUserMessages:J,setClearedTabs:me}),{isCreatingChat:Ir,isRefreshingHistory:Mr,handleSwitchSession:Tr,handleNewChat:Ar,handleRefreshHistory:Rr}=tn({sendDaemonCommand:t,activeConv:Te,updateIdeChats:p,setToasts:w,setLocalUserMessages:J,setClearedTabs:me}),ns=a.useCallback(async()=>{if(!(!Te||!Ge||W)){ee(!0);try{const le=Te.daemonId||Te.ideId,ve=Te.agentType||Te.ideType,ke=await t(le,"list_saved_sessions",{agentType:ve,providerType:ve,kind:"cli",limit:50}),Ce=(ke==null?void 0:ke.result)??ke;G(Array.isArray(Ce==null?void 0:Ce.sessions)?Ce.sessions:[])}catch(le){console.error("Refresh saved sessions failed",le),G([])}finally{ee(!1)}}},[Te,W,Ge,t]);a.useEffect(()=>{if(L){if(!Ge){G([]),ee(!1);return}ns()}},[ns,L,Ge]);const Lr=a.useCallback(async le=>{if(!Te||!Ge||!le.providerSessionId||!le.workspace)return;const ve=Te.daemonId||Te.ideId,ke=Te.agentType||Te.ideType;try{K(le.providerSessionId);const Ce=await t(ve,"launch_cli",{cliType:ke,dir:le.workspace,resumeSessionId:le.providerSessionId,initialModel:le.currentModel}),Ee=(Ce==null?void 0:Ce.result)??Ce,$s=typeof(Ee==null?void 0:Ee.sessionId)=="string"?Ee.sessionId:typeof(Ee==null?void 0:Ee.id)=="string"?Ee.id:"";$s&&i(Fr=>{const Bs=new URLSearchParams(Fr);return Bs.set("activeTab",$s),Bs},{replace:!0}),$(!1)}catch(Ce){console.error("Resume saved session failed",Ce)}finally{K(null)}},[Te,Ge,t,i]);No({urlActiveTab:P&&!Ct?o:null,conversations:De,resolveConversationBySessionId:Oe,normalizedGroupAssignments:ie,hasHydratedStoredLayout:P&&!Ct?I:!0,hydrateStoredLayout:P&&!Ct?q:()=>{},setGroupActiveTabIds:B,setFocusedGroup:C,setSearchParams:i,historyModalOpen:L,activeConv:ce,isRefreshingHistory:Nr,ides:m,handleRefreshHistory:Cr});const It=a.useCallback(async le=>{if(!ce||!Se(ce)||ye(ce))return;const ve=ce.ideType||ce.agentType||"",ke=ce.ideId||ce.daemonId||"";try{await t(ke,"stop_cli",{cliType:ve,targetSessionId:ce.sessionId,mode:le})}catch(Ce){console.error("Stop CLI failed:",Ce)}},[ce,t]),Dr=a.useCallback(async()=>{var ve;if(!ce||!Se(ce)||ye(ce))return;if((ve=ce.resume)!=null&&ve.supported){V(!0);return}const le=ce.ideType||ce.agentType||"CLI";window.confirm(`Stop ${le}?
57
- This will terminate the CLI process.`)&&await It("hard")},[ce,It]),_r=a.useMemo(()=>!ce||!Se(ce)||ye(ce)?null:lt(ce),[ce]),Er=a.useCallback(async le=>{if(!(!ce||!Se(ce)||ye(ce)||lt(ce)===le))try{await t(ce.daemonId||ce.ideId,"set_cli_view_mode",{targetSessionId:ce.sessionId,cliType:ce.ideType||ce.agentType,mode:le})}catch(ke){console.error("Failed to switch CLI view mode:",ke)}},[ce,t]),{versionMismatchDaemons:Pr,appVersion:$r,versionBannerDismissed:Br,setVersionBannerDismissed:Kr,upgradingDaemons:Wr,handleBannerUpgrade:Or}=Ro({ides:m,sendDaemonCommand:t}),rs=a.useCallback(le=>{pe(le.tabKey),i(ve=>{const ke=new URLSearchParams(ve);return le.sessionId?ke.set("activeTab",le.sessionId):ke.delete("activeTab"),ke},{replace:!0})},[i]),Ur=a.useCallback(le=>{we(le.tabKey),rs(le)},[rs,we]),zr=a.useCallback(le=>{de(le.tabKey)},[de]);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(di,{wsStatus:f,showReconnected:j}),e.jsx(ui,{terminalBackend:te,isStandalone:O}),!Br&&e.jsx(dc,{daemons:Pr,targetVersion:$r,upgradingDaemons:Wr,onUpgrade:Or,onDismiss:()=>Kr(!0)}),e.jsx(nc,{showMobileChatMode:Ct,isMobile:P,activeConv:ce,chatIdes:Me,wsStatus:f,isConnected:y,onOpenHistory:le=>{le&&ss(le),$(!0)},onOpenRemote:vr,onStopCli:Dr,activeCliViewMode:_r,onSetActiveCliViewMode:Er,mobileChatConversations:wr,ides:m,actionLogs:Y,sendDaemonCommand:t,setLocalUserMessages:J,setActionLogs:X,isStandalone:O,userName:l.userName,requestedMobileTabKey:br,onRequestedMobileTabConsumed:Ds,requestedMachineId:d,onRequestedMachineConsumed:()=>{n(s.pathname+s.search,{replace:!0,state:null})},containerRef:se,isSplitMode:be,numGroups:fe,groupSizes:N,groupedConvs:ge,clearedTabs:oe,screenshotMap:u,setScreenshotMap:x,focusedGroup:S,setFocusedGroup:C,moveTabToGroup:ue,splitTabRelative:fr,closeGroup:Fe,handleResizeStart:ts,detectedIdes:R,handleLaunchIde:Sr,groupActiveTabIds:_,setGroupActiveTabIds:B,groupTabOrders:H,setGroupTabOrders:E,toggleHiddenTab:re,visibleConversations:Le,hiddenConversations:kr,requestedDesktopTabKey:Ls,onRequestedDesktopTabConsumed:Ds,onDesktopActiveTabChange:pe,onOpenDesktopConversation:rs,onHideConversation:zr,onShowHiddenConversation:Ur,onShowAllHiddenConversations:Ke}),e.jsx("style",{children:`
58
- body { overflow: hidden; overscroll-behavior: none; }
59
- `}),e.jsx(lc,{historyModalOpen:L,historyTargetConv:Te,ides:m,isHistoryCreatingChat:Ir,isHistoryRefreshingHistory:Ge?!1:Mr,savedHistorySessions:ae,isSavedHistoryLoading:W,isResumingSavedHistorySessionId:F,onCloseHistory:()=>$(!1),onNewHistoryChat:Ar,onSwitchHistorySession:Tr,onRefreshHistory:Ge?ns:Rr,onResumeSavedHistorySession:Lr,remoteDialogConv:_s,remoteDialogIdeEntry:gr,connectionStates:k,actionLogs:Y,localUserMessages:Q,sendDaemonCommand:t,setLocalUserMessages:J,setActionLogs:X,isStandalone:O,userName:l.userName,onOpenRemoteHistory:le=>{le&&ss(le),$(!0)},onRemoteConversationChange:ss,onCloseRemoteDialog:jr,cliStopDialogOpen:D,activeConv:ce,onCancelCliStop:()=>V(!1),onStopCliNow:async()=>{V(!1),await It("hard")},onSaveCliAndStop:async()=>{V(!1),await It("save")},toasts:b,onDismissToast:le=>w(ve=>ve.filter(ke=>ke.id!==le)),onClickToast:le=>{if(le.targetKey){const ve=ze(le.targetKey);ve&&C(ie.get(ve.tabKey)??0)}},showOnboarding:h,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}g(!1)}})]})}function hc({machineId:t,registeredMachineId:s,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:i}){const[o,c]=a.useState([]),[d,l]=a.useState(null),[p,u]=a.useState(null),[x,m]=a.useState(!1),[h,g]=a.useState(null),[b,w]=a.useState(!1),[f,y]=a.useState(""),k=a.useRef(null),j=a.useCallback(L=>{k.current=L},[]),v=a.useCallback((L,$,D=!1)=>{c(V=>[...V.slice(-100),{timestamp:Date.now(),level:L,message:$}]),setTimeout(()=>{var V;return(V=i.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),D&&Je.showToast($,L==="error"||L==="warn"?"warning":"success")},[i]),T=a.useCallback(async(L,$)=>{var D;if(!t||d)return!1;l(L),v("info",`Launching ${Ne(L)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const V={ideType:L,enableCdp:!0};(D=$==null?void 0:$.workspace)!=null&&D.trim()?V.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(V.useDefaultWorkspace=!0);const ae=await n(t,"launch_ide",V);return v(ae!=null&&ae.success?"info":"error",ae!=null&&ae.success?`${Ne(L)} launched`:`Failed: ${ae==null?void 0:ae.error}`,!0),!!(ae!=null&&ae.success)}catch(V){return v("error",`Launch error: ${V.message}`,!0),!1}finally{l(null)}},[t,d,v,n]),S=a.useCallback(async L=>{if(!t)return{success:!1};const{cliType:$,dir:D,workspaceId:V,useDefaultWorkspace:ae,useHome:G,argsStr:W,model:ee,resumeSessionId:F}=L;if(!$)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const K=W?W.split(/\s+/).filter(Boolean):void 0,M=(D==null?void 0:D.trim())||(V?"(saved id)":ae?"(default workspace)":G?"(home)":"");v("info",`Launching ${$}${M?` in ${M}`:""}${ee?` (model: ${ee})`:""}...`),u($);try{const Y={cliType:$,cliArgs:K,initialModel:ee||void 0};D!=null&&D.trim()?Y.dir=D.trim():V?Y.workspaceId=V:ae?Y.useDefaultWorkspace=!0:G&&(Y.useHome=!0),F&&(Y.resumeSessionId=F);const X=await n(t,"launch_cli",Y),Q=(X==null?void 0:X.result)||X;return X!=null&&X.success?(v("info",`${$} launched`,!0),(Q==null?void 0:Q.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(Q==null?void 0:Q.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:Q==null?void 0:Q.sessionId}):(v("error",`Failed: ${(X==null?void 0:X.error)||(Q==null?void 0:Q.error)}`,!0),(X==null?void 0:X.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&g({cliType:$,argsStr:W,model:ee}),{success:!1,sessionId:Q==null?void 0:Q.sessionId})}catch(Y){return v("error",`Launch error: ${Y.message}`,!0),{success:!1}}finally{u(null)}},[t,v,n]),C=a.useCallback(async(L,$,D,V)=>t?L?$.trim()?S({cliType:L,dir:$,argsStr:D,model:V}):(g({cliType:L,argsStr:D,model:V}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[t,v,S]),_=a.useCallback(async(L,$,D)=>{if(t&&window.confirm(`Stop ${L}?
60
- This will terminate the process.`))try{const V=await n(t,"stop_cli",{cliType:L,dir:$,targetSessionId:D});V!=null&&V.success?v("info",`${L} stopped`,!0):v("error",`Stop failed: ${(V==null?void 0:V.error)||"Unknown error"}`,!0)}catch(V){v("error",`Stop failed: ${V.message}`,!0)}},[t,v,n]),B=a.useCallback(async L=>{try{await n(L.daemonId,"restart_ide",{ideType:L.type}),v("info",`${Ne(L.type)} restart initiated`,!0)}catch($){v("error",`Restart failed: ${$.message}`,!0)}},[v,n]),H=a.useCallback(async L=>{if(window.confirm(`Stop ${Ne(L.type)}?
61
- This will disconnect CDP and optionally kill the process.`))try{const $=await n(L.daemonId,"stop_ide",{ideType:L.type,killProcess:!0});$!=null&&$.success?v("info",`${Ne(L.type)} stopped`,!0):v("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){v("error",`Stop failed: ${$.message}`,!0)}},[v,n]),E=a.useCallback(async()=>{if(t)try{const L=await n(t,"detect_ides",{});v("info",`Found ${((L==null?void 0:L.result)||[]).length} IDE(s)`,!0)}catch(L){v("error",`Detection failed: ${L.message}`,!0)}},[t,v,n]),N=a.useCallback(async L=>{if(!(!t||!L.trim())){m(!0);try{const $=await n(t,"workspace_add",{path:L.trim()});$!=null&&$.success?v("info",`Workspace added: ${L.trim()}`):v("error",($==null?void 0:$.error)||"workspace_add failed")}catch($){v("error",$.message)}finally{m(!1)}return!0}},[t,v,n]),A=a.useCallback(async L=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const $=await n(t,"workspace_remove",{id:L});$!=null&&$.success?v("info","Workspace removed",!0):v("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){v("error",$.message,!0)}finally{m(!1)}}},[t,v,n]),P=a.useCallback(async L=>{var $;if(t){m(!0);try{const D=await n(t,"workspace_set_default",L===null?{clear:!0}:{id:L});if(D!=null&&D.success){v("info",L?"Default workspace updated":"Default workspace cleared",!0);const V=typeof D.defaultWorkspacePath=="string"?D.defaultWorkspacePath:"";V&&(($=k.current)==null||$.call(k,V))}else v("error",(D==null?void 0:D.error)||"workspace_set_default failed",!0)}catch(D){v("error",D.message,!0)}finally{m(!1)}}},[t,v,n]),I=a.useCallback(async L=>{var D;if(!t||!L.trim())return;const $=L.trim();m(!0);try{const V=await n(t,"workspace_set_default",{path:$});V!=null&&V.success?(v("info","Default workspace set from history"),(D=k.current)==null||D.call(k,$)):v("error",(V==null?void 0:V.error)||"Could not set default (path missing on disk?)")}catch(V){v("error",V.message)}finally{m(!1)}},[t,v,n]),q=a.useCallback(async()=>{if(t)try{if(await n(t,"set_machine_nickname",{nickname:f}),r)try{await r({machineRuntimeId:t,registeredMachineId:s,nickname:f})}catch(L){v("warn",`Live nickname updated, but account sync failed: ${L.message}`)}v("info",`Nickname set to "${f||"(cleared)"}"`),w(!1)}catch(L){v("error",`Failed: ${L.message}`)}},[t,f,s,v,r,n]);return{logs:o,launchingIde:d,launchingAgentType:p,workspaceBusy:x,launchPick:h,setLaunchPick:g,editingNickname:b,setEditingNickname:w,nicknameInput:f,setNicknameInput:y,addLog:v,handleLaunchIde:T,runLaunchCliCore:S,handleLaunchCli:C,handleStopCli:_,handleRestartIde:B,handleStopIde:H,handleDetectIdes:E,handleWorkspaceAdd:N,handleWorkspaceRemove:A,handleWorkspaceSetDefault:P,handleWorkspaceResumePath:I,handleSaveNickname:q,setOnDefaultWorkspaceChanged:j}}function mc({machine:t,ideSessions:s,cliSessions:n,acpSessions:r,actions:i}){const{workspaceBusy:o,handleWorkspaceAdd:c,handleWorkspaceRemove:d,handleWorkspaceSetDefault:l}=i,[p,u]=a.useState(""),x=t.availableMem??t.freeMem,m=t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-x)/t.totalMem*100))):0,h=t.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(Mt,{icon:e.jsx(An,{size:16}),label:"Uptime",value:qa(t.uptime)}),e.jsx(Mt,{icon:e.jsx(Be,{size:16}),label:"IDEs",value:`${s.length}`}),e.jsx(Mt,{icon:e.jsx(Cs,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Mt,{icon:e.jsx(ka,{size:16}),label:"ACPs",value:`${r.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(zs,{value:Math.min(Math.round(h/t.cpus*100),100),max:100,label:"CPU Load",color:"#8b5cf6",detail:`${h.toFixed(2)} avg / ${t.cpus} cores`}),e.jsx(zs,{value:m,max:100,label:"Memory",color:"#3b82f6",detail:`${Vs(t.totalMem-x)} / ${Vs(t.totalMem)}${t.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(xs,{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:o,value:t.defaultWorkspaceId||"",onChange:g=>void l(g.target.value===""?null:g.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(g=>e.jsx("option",{value:g.id,children:g.label||g.path},g.id))]}),t.defaultWorkspacePath&&e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-end",children:[e.jsx("input",{className:"flex-1 min-w-[200px] text-xs bg-bg-primary border border-border-subtle rounded-lg px-2.5 py-1.5",placeholder:"Add workspace path…",value:p,disabled:o,onChange:g=>u(g.target.value),onKeyDown:g=>g.key==="Enter"&&void(async()=>{await c(p)&&u("")})()}),e.jsx("button",{type:"button",className:"machine-btn text-xs px-3 py-1.5",disabled:o,onClick:async()=>{await c(p)&&u("")},children:"Add"})]}),(t.workspaces||[]).length>0&&e.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(g=>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:[g.id===t.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:$n(g.path,g.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:g.path,children:g.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:o,onClick:()=>void d(g.id),children:"Remove"})]},g.id))})]})]})}const un=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],pc=[{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 xc({machineId:t,provider:s,sendDaemonCommand:n,onClose:r}){const[i,o]=a.useState("config"),[c,d]=a.useState("codex-cli"),[l,p]=a.useState([]),[u,x]=a.useState(""),[m,h]=a.useState([]),[g,b]=a.useState(""),w=a.useRef(null),f=a.useRef(null),y=C=>{p(_=>_.includes(C)?_.filter(B=>B!==C):[..._,C])},k=()=>p([...un]),j=()=>p([]);a.useEffect(()=>{var C;(C=w.current)==null||C.scrollIntoView({behavior:"smooth"})},[m]),a.useEffect(()=>()=>{f.current&&clearInterval(f.current)},[]);const v=a.useCallback(()=>{f.current&&clearInterval(f.current),f.current=setInterval(async()=>{try{const C=await n(t,"provider_auto_fix_status",{providerType:s.type});(C==null?void 0:C.running)===!1&&i==="running"&&(o("done"),h(_=>[..._,`
62
- ✅ Auto-fix completed!`]),f.current&&clearInterval(f.current))}catch{}},3e3)},[t,s.type,n,i]),T=async()=>{if(l.length!==0){o("running"),h(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${l.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),b("");try{const C=await n(t,"provider_auto_fix",{providerType:s.type,functions:l,agent:c,...u?{comment:u}:{}});C!=null&&C.success&&(C!=null&&C.started||C!=null&&C.running)?(h(_=>[..._,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),b((C==null?void 0:C.error)||"Failed to start auto-fix"))}catch(C){o("error"),b((C==null?void 0:C.message)||"Connection failed")}}},S=async()=>{try{await n(t,"provider_auto_fix_cancel",{providerType:s.type}),h(C=>[...C,`
63
- ⚠️ Auto-fix cancelled.`]),o("done"),f.current&&clearInterval(f.current)}catch{}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:r,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:C=>C.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:r,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:pc.map(C=>e.jsxs("button",{onClick:()=>d(C.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===C.value?C.color+"66":"var(--border-subtle)",background:c===C.value?C.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===C.value?C.color:"var(--text-primary)"},children:C.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:C.desc})]},C.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:k,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),e.jsx("button",{onClick:j,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:un.map(C=>e.jsxs("button",{onClick:()=>y(C),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:l.includes(C)?"rgba(139,92,246,0.4)":"var(--border-subtle)",background:l.includes(C)?"rgba(139,92,246,0.08)":"transparent",color:l.includes(C)?"#a78bfa":"var(--text-secondary)"},children:[l.includes(C)?"☑ ":"☐ ",C]},C))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:u,onChange:C=>x(C.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:[m.map((C,_)=>e.jsx("div",{className:C.startsWith("✅")?"text-green-400":"",style:C.startsWith("❌")||C.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:C},_)),i==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:w})]}),g&&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:g})]})]}),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:r,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:T,disabled:l.length===0,className:"machine-btn",style:{background:l.length>0?"rgba(139,92,246,0.15)":void 0,borderColor:l.length>0?"rgba(139,92,246,0.4)":void 0,color:l.length>0?"#a78bfa":void 0,opacity:l.length===0?.4:1},children:"🚀 Start Fix"})]}),i==="running"&&e.jsx("button",{onClick:S,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"),h([]),b("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:r,className:"machine-btn",children:"Close"})]})]})]})]})})}function fc({machineId:t,providers:s,sendDaemonCommand:n,onClose:r,onCreated:i}){var v;const o=s.filter(T=>T.category==="ide"),[c,d]=a.useState(((v=o[0])==null?void 0:v.type)||""),[l,p]=a.useState(""),[u,x]=a.useState(""),[m,h]=a.useState(!1),[g,b]=a.useState(""),[w,f]=a.useState(!1),y=T=>{const S=T.toLowerCase().replace(/[^a-z0-9-]/g,"");p(S),(!u||u===k(l))&&x(k(S))},k=T=>T.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),j=async()=>{if(!(!l||!u||!c)){h(!0),b("");try{const T=await n(t,"provider_clone",{type:l,name:u,category:"ide",location:"user",cloneFrom:c});T!=null&&T.success||T!=null&&T.created?(f(!0),i==null||i(l)):b((T==null?void 0:T.error)||"Failed to create provider")}catch(T){b((T==null?void 0:T.message)||"Connection failed")}h(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:r,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:T=>T.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:w?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(T=>e.jsxs("button",{onClick:()=>d(T.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===T.type?"rgba(139,92,246,0.4)":"var(--border-subtle)",background:c===T.type?"rgba(139,92,246,0.08)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:T.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===T.type?"#a78bfa":"var(--text-secondary)"},children:T.displayName})]},T.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:T=>y(T.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",e.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",l||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:u,onChange:T=>x(T.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"})]}),g&&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:g})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:w?e.jsx("button",{onClick:r,className:"machine-btn",children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:r,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:j,disabled:!l||!u||m,className:"machine-btn",style:{background:l&&u?"rgba(34,197,94,0.12)":void 0,borderColor:l&&u?"rgba(34,197,94,0.3)":void 0,color:l&&u?"#86efac":void 0,opacity:!l||!u||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function bc({machineId:t,providers:s,sendDaemonCommand:n}){const[r,i]=a.useState([]),[o,c]=a.useState(!1),[d,l]=a.useState(null),[p,u]=a.useState("all"),[x,m]=a.useState(null),[h,g]=a.useState(!1),b=a.useCallback(async()=>{var f;if(t){c(!0);try{const y=await n(t,"get_provider_settings",{}),k=(y==null?void 0:y.result)||y;if(y!=null&&y.success&&(k!=null&&k.settings)){const j=[];for(const[v,T]of Object.entries(k.settings)){const S=s.find(C=>C.type===v);j.push({type:v,displayName:(S==null?void 0:S.displayName)||v,icon:(S==null?void 0:S.icon)||"",category:(S==null?void 0:S.category)||"unknown",schema:T,values:((f=k.values)==null?void 0:f[v])||{}})}j.sort((v,T)=>v.category.localeCompare(T.category)||v.displayName.localeCompare(T.displayName)),i(j)}}catch{}c(!1)}},[t,s,n]);a.useEffect(()=>{r.length===0&&b()},[]);const w=async(f,y,k)=>{l(`${f}.${y}`),i(j=>j.map(v=>v.type===f?{...v,values:{...v.values,[y]:k}}:v));try{const j=await n(t,"set_provider_setting",{providerType:f,key:y,value:k});j!=null&&j.success||b()}catch{b()}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(f=>e.jsx("button",{onClick:()=>u(f),className:`machine-btn text-[10px] px-2 py-0.5 ${p===f?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:f.toUpperCase()},f))]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>g(!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:b,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),p!=="all"&&r.filter(f=>f.category===p).length>1&&(()=>{const f=r.filter(v=>v.category===p),y=new Map;for(const v of f)for(const T of v.schema){if(T.type!=="boolean")continue;const S=y.get(T.key),C=!!(v.values[T.key]??T.default);S?(S.onCount+=C?1:0,S.total+=1):y.set(T.key,{label:T.label||T.key,onCount:C?1:0,total:1})}const k=[...y.entries()].filter(([,v])=>v.total===f.length);if(k.length===0)return null;const j=async(v,T)=>{for(const S of f)await w(S.type,v,T)};return e.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[e.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",p.toUpperCase()," providers (",f.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(([v,T])=>{const S=T.onCount===T.total,C=T.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:T.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",T.onCount,"/",T.total,")"]}),e.jsx("button",{onClick:()=>void j(v,!0),disabled:S,className:`machine-btn text-[9px] px-1.5 py-px ${S?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void j(v,!1),disabled:C,className:`machine-btn text-[9px] px-1.5 py-px ${C?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},v)})})]})})(),o&&r.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:r.filter(f=>p==="all"||f.category===p).map(f=>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:f.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:f.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:f.category==="acp"?"rgba(139,92,246,0.08)":f.category==="cli"?"rgba(59,130,246,0.08)":f.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:f.category==="acp"?"#a78bfa":f.category==="cli"?"#60a5fa":f.category==="ide"?"#86efac":"var(--status-warning)"},children:f.category}),f.category==="ide"&&e.jsx("button",{onClick:()=>m(s.find(y=>y.type===f.type)||{type:f.type,name:f.displayName,displayName:f.displayName,icon:f.icon,category:f.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:f.schema.map(y=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[y.label||y.key,d===`${f.type}.${y.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),y.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:y.description})]}),e.jsx("div",{className:"shrink-0",children:y.type==="boolean"?e.jsx("button",{onClick:()=>w(f.type,y.key,!(f.values[y.key]??y.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:f.values[y.key]??y.default?"#8b5cf6":"var(--border-subtle)"},children:e.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:f.values[y.key]??y.default?21:3}})}):y.type==="number"?e.jsx("input",{type:"number",value:f.values[y.key]??y.default??0,min:y.min,max:y.max,onChange:k=>{const j=parseInt(k.target.value)||0;y.min!==void 0&&j<y.min||y.max!==void 0&&j>y.max||w(f.type,y.key,j)},className:"machine-input w-20 text-center text-[11px]"}):y.type==="select"&&y.options?e.jsx("select",{value:f.values[y.key]??y.default??"",onChange:k=>w(f.type,y.key,k.target.value),className:"machine-input text-[11px]",children:y.options.map(k=>e.jsx("option",{value:k,children:k},k))}):e.jsx("input",{type:"text",value:f.values[y.key]??y.default??"",onBlur:k=>w(f.type,y.key,k.target.value),className:"machine-input w-[120px] text-[11px]"})})]},y.key))})]},f.type))}),x&&e.jsx(xc,{machineId:t,provider:x,sendDaemonCommand:n,onClose:()=>m(null)}),h&&e.jsx(fc,{machineId:t,providers:s,sendDaemonCommand:n,onClose:()=>g(!1),onCreated:()=>{g(!1),b()}})]})}function gc({machineId:t,sendDaemonCommand:s}){const[n,r]=a.useState([]),[i,o]=a.useState(0),[c,d]=a.useState(!0),[l,p]=a.useState("debug"),u=a.useRef(null),x=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const m=async()=>{try{const g=await s(t,"get_logs",{count:200,minLevel:l,since:i}),b=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray(b==null?void 0:b.logs)&&b.logs.length>0){r(f=>[...f,...b.logs.map(k=>({timestamp:k.ts,level:k.level,message:`[${k.category}] ${k.message}`}))].slice(-300));const w=Math.max(...b.logs.map(f=>f.ts));o(w)}}catch{}};m();const h=setInterval(m,3e3);return()=>clearInterval(h)},[t,c,i,l,s]),a.useEffect(()=>{if(c&&n.length>0){const m=x.current?"smooth":"instant";setTimeout(()=>{var h;(h=u.current)==null||h.scrollIntoView({behavior:m}),x.current=!0},50)}},[n.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(m=>e.jsx("button",{onClick:()=>{p(m),r([]),o(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${l===m?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:m.toUpperCase()},m))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:[n.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:()=>{r([]),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:[n.length===0&&e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading daemon logs..."}),n.map((m,h)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:m.level==="error"?"#ef4444":m.level==="warn"?"var(--status-warning)":m.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(m.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:m.level==="error"?"#ef4444":m.level==="warn"?"var(--status-warning)":m.level==="debug"?"#475569":"#8b5cf6"},children:m.level==="error"?"ERR":m.level==="warn"?"WRN":m.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:m.message})]},h)),e.jsx("div",{ref:u})]})]})}function yc({machine:t,launchPick:s,actions:n}){const{runLaunchCliCore:r,setLaunchPick:i}=n;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),r({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),r({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),r({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 hn({children:t}){return e.jsx("div",{className:"machine-command-section-title",children:t})}function vc({machineEntry:t,providers:s,recentLaunches:n,onUpgradeDaemon:r,onOpenLogs:i,onOpenRecent:o,onOpenWorkspace:c,onGoTab:d}){const l=t.detectedIdes||[],p=s.filter(g=>g.category==="cli"),u=s.filter(g=>g.category==="acp"),x=n.slice(0,4),m=[l.length>0?{id:"ide",kind:"ide",label:"IDE"}:null,p.length>0?{id:"cli",kind:"cli",label:"CLI"}:null,u.length>0?{id:"acp",kind:"acp",label:"ACP"}:null].filter(Boolean),h=g=>g==="ide"?"IDE":g==="cli"?"CLI":"ACP";return e.jsxs("div",{className:"machine-command-center",children:[x.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(hn,{children:"Recent"}),e.jsx("div",{className:"machine-command-links",children:x.map(g=>e.jsxs("button",{type:"button",className:"machine-command-link",onClick:()=>o(g),children:[e.jsx("span",{className:"machine-command-link-title",children:g.label}),e.jsxs("span",{className:"machine-command-link-meta",children:[h(g.kind),g.subtitle?` · ${g.subtitle}`:""]})]},g.id))})]}),m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(hn,{children:"Start"}),e.jsx("div",{className:"machine-command-launch-grid",children:m.map(g=>e.jsxs("button",{type:"button",className:"machine-command-launch-btn",onClick:()=>c(g.kind),children:[e.jsx("span",{className:"machine-command-launch-title",children:g.label}),e.jsx("span",{className:"machine-command-launch-meta",children:"Choose workspace and provider"})]},g.id))})]}),e.jsxs("div",{className:"machine-command-secondary",children:[t.versionMismatch&&e.jsx("button",{type:"button",className:"machine-command-secondary-link machine-command-secondary-link-accent",onClick:r,children:"Update daemon"}),e.jsx("button",{type:"button",className:"machine-command-secondary-link",onClick:i,children:"Logs"}),e.jsx("button",{type:"button",className:"machine-command-secondary-link",onClick:()=>d("providers"),children:"Providers"}),e.jsx("button",{type:"button",className:"machine-command-secondary-link",onClick:()=>d("overview"),children:"System"})]})]})}function jc(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const wc={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 ms({category:t,machine:s,machineId:n,providers:r,managedEntries:i,getIcon:o,actions:c,sendDaemonCommand:d,initialWorkspaceId:l,initialWorkspacePath:p}){const u=dt(),{handleLaunchIde:x,handleLaunchCli:m,handleStopCli:h,handleRestartIde:g,handleStopIde:b,handleDetectIdes:w,launchingIde:f,launchingAgentType:y}=c,[k,j]=a.useState(null),v=a.useCallback(R=>{R&&u({pathname:"/",search:`?activeTab=${encodeURIComponent(R)}`})},[u]),T=wc[t],S=t==="ide",C=t==="acp",_=r.filter(R=>R.category===t),B=new Map(_.map(R=>[R.type,R.displayName||R.type])),[H,E]=a.useState(""),[N,A]=a.useState(""),[P,I]=a.useState(""),[q,L]=a.useState(p?"__custom__":l||s.defaultWorkspaceId||""),[$,D]=a.useState(p||""),[V,ae]=a.useState([]),G=V.filter(R=>!i.some(O=>O.type===R&&_e(O.status)!=="stopped")),W=a.useRef({});a.useEffect(()=>{!H&&_.length>0&&E(_[0].type)},[H,_.length]),a.useEffect(()=>{s.defaultWorkspaceId&&!q&&L(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(p){L("__custom__"),D(p);return}l&&(L(l),D(""))},[l,p]);const ee=(()=>{if(q==="__custom__")return $.trim();if(!q)return"";const R=(s.workspaces||[]).find(O=>O.id===q);return(R==null?void 0:R.path)||""})(),F=a.useCallback(R=>{const O=W.current[R];O&&(clearTimeout(O),delete W.current[R]),ae(te=>te.filter(ne=>ne!==R))},[]),K=a.useCallback(R=>{if(!R)return;ae(te=>te.includes(R)?te:[...te,R]);const O=W.current[R];O&&clearTimeout(O),W.current[R]=setTimeout(()=>{ae(te=>te.filter(ne=>ne!==R)),delete W.current[R]},2e4)},[]);a.useEffect(()=>{for(const R of i)_e(R.status)!=="stopped"&&F(R.type)},[i,F]),a.useEffect(()=>()=>{Object.values(W.current).forEach(clearTimeout),W.current={}},[]);const[M,Y]=a.useState({}),[X,Q]=a.useState(null);a.useEffect(()=>{if(!S||!n||!d)return;(async()=>{try{const O=await d(n,"get_ide_extensions",{}),te=(O==null?void 0:O.result)||O;te!=null&&te.success&&(te!=null&&te.ideExtensions)&&Y(te.ideExtensions)}catch{}})()},[S,n,d]);const J=R=>S?Ne(R.type):t==="cli"?R.cliName:R.acpName,oe=S?s.detectedIdes||[]:[],me=()=>{(async()=>{if(S){await x(H,ee?{workspace:ee}:void 0)&&K(H);return}const R=await m(H,ee,N||void 0,C&&P||void 0);R.success&&(K(H),R.sessionId&&v(R.sessionId))})()},he=R=>{S?b(R):h(R.type,R.workspace,R.id)},pe=a.useCallback(async(R,O,te=!1)=>{if(R.mode===O){te&&R.sessionId&&v(R.sessionId);return}if(!d||!R.sessionId){te&&R.sessionId&&v(R.sessionId);return}try{await d(n,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:O}),te&&v(R.sessionId)}catch(ne){console.error("Failed to switch CLI view mode:",ne)}},[n,v,d]),Z=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:q,onChange:R=>{L(R.target.value),R.target.value!=="__custom__"&&D("")},className:"machine-input min-w-[200px] flex-1",children:(s.workspaces||[]).length>0?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(R=>e.jsxs("option",{value:R.id,children:[R.id===s.defaultWorkspaceId?"⭐ ":"",$n(R.path,R.label)]},R.id)),e.jsx("option",{value:"__custom__",children:"✏️ 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:"✏️ Custom path…"})]})}),q==="__custom__"&&e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:$,onChange:R=>D(R.target.value),className:"machine-input flex-1 min-w-[200px]",autoFocus:!0})]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:q==="__custom__"?ee?e.jsx("span",{className:"font-mono truncate block",title:ee,children:ee}):"Enter an absolute path to launch there.":ee?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:q===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:ee,children:ee})]}):"No workspace selected. This launches in the home directory."})]});return e.jsxs("div",{children:[e.jsxs("div",{className:`px-5 py-4 rounded-xl mb-5 bg-bg-secondary border ${T.accent}`,children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Launch ",T.label]}),Z,S?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[oe.map(R=>{const O=i.find(re=>(re.type||"").toLowerCase()===(R.type||"").toLowerCase()&&_e(re.status)!=="stopped"),te=R.running||!!O,ne=!!O&&O.cdpConnected,de=V.includes(R.type||R.id||"");return e.jsxs("button",{onClick:()=>{if(ne&&O){const re=O.sessionId;re?u(`/dashboard?activeTab=${encodeURIComponent(re)}`,{state:{openRemoteForTabKey:re}}):u("/dashboard",{state:{openRemoteForTabKey:O.id}});return}de||(async()=>await x(R.type||R.id||"",ee?{workspace:ee}:void 0)&&K(R.type||R.id||""))()},disabled:!!f||de,className:`machine-btn-primary flex items-center gap-1.5 ${te?"!border-green-500/30":""}`,style:{opacity:f&&f!==R.type?.4:1},children:[e.jsx("span",{children:o(R.type)}),te&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500 shadow-[0_0_4px_rgba(34,197,94,0.4)]"}),de?`⏳ Waiting for ${R.name||Ne(R.type)}...`:ne?`Open ${R.name||Ne(R.type)}`:f===R.type?"⏳ Launching...":`▶ ${R.name||Ne(R.type)}`,te&&ne&&e.jsx("span",{className:"text-[9px] text-green-400 font-normal",children:"running"})]},R.type)}),oe.length===0&&e.jsxs("div",{className:"text-xs text-text-muted italic",children:["No IDEs detected.",e.jsxs("button",{onClick:w,className:"machine-btn ml-2 flex items-center gap-1",children:[e.jsx(ya,{size:12})," Scan"]})]})]})}):e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:H,onChange:R=>E(R.target.value),className:"machine-input",children:_.length>0?_.map(R=>e.jsxs("option",{value:R.type,children:[R.icon," ",R.displayName]},R.type)):e.jsxs("option",{value:"",disabled:!0,children:["No ",t.toUpperCase()," providers available"]})}),C&&e.jsx("input",{type:"text",placeholder:"Model (default)",value:P,onChange:R=>I(R.target.value),className:"machine-input min-w-[120px]"}),e.jsx("input",{type:"text",placeholder:"Args (optional)",value:N,onChange:R=>A(R.target.value),className:"machine-input min-w-[120px]"}),e.jsx("button",{onClick:me,disabled:!!y,className:"machine-btn-primary",children:y===H?"⏳ Launching...":"▶ Launch"})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",i.length+V.filter(R=>!i.some(O=>O.type===R&&_e(O.status)!=="stopped")).length,")"]}),i.length===0&&G.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 ",T.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[G.map(R=>e.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:o(R)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?Ne(R):B.get(R)||R}),e.jsx("div",{className:"text-[11px] text-text-muted",children:y===R?"Launching process...":"Waiting for process and session to register..."})]})]}),e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${R}`)),i.map(R=>{const O=S?R:null,te=C?R:null,ne=!S&&!C?R:null,de=_e(R.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:o(R.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[J(R),(O==null?void 0:O.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",O.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:R.workspace||"—"}),(te==null?void 0:te.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",te.currentModel]}),(te==null?void 0:te.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",te.currentPlan]}),(ne==null?void 0:ne.mode)&&e.jsx("span",{className:ne.mode==="chat"?"text-violet-400":"text-text-secondary",children:ne.mode==="chat"?"Chat view":"Terminal view"})]}),ne&&(ne.runtimeKey||ne.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ne.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 ",ne.runtimeKey]}),e.jsx("button",{type:"button",className:"machine-btn text-[9px] px-1.5 py-px",onClick:()=>{var re;(re=navigator.clipboard)==null||re.writeText(`adhdev attach ${ne.runtimeKey}`),j(ne.runtimeKey||null),window.setTimeout(()=>{j(we=>we===ne.runtimeKey?null:we)},1200)},children:k===ne.runtimeKey?"Copied":"Copy"})]}),ne.runtimeWriteOwner&&e.jsx("span",{style:{color:ne.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ne.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:jc(ne.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 ${de==="stopped"?"bg-red-500/[0.08] text-red-500":de==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:de}),S&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const re=R.sessionId;if(re){u(`/dashboard?activeTab=${encodeURIComponent(re)}`,{state:{openRemoteForTabKey:re}});return}u("/dashboard",{state:{openRemoteForTabKey:R.id}})},className:"machine-btn flex items-center gap-1",title:"Open remote control",children:e.jsx(Be,{size:13})}),e.jsx("button",{onClick:()=>g(R),className:"machine-btn",style:{color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"},title:"Restart",children:e.jsx(Ns,{size:14})})]}),C&&e.jsx("button",{onClick:()=>{const re=R.sessionId;re&&v(re)},className:"machine-btn",title:"View chat",disabled:!R.sessionId,children:e.jsx(rt,{size:14})}),ne&&de!=="stopped"&&e.jsxs(e.Fragment,{children:[ne.mode&&e.jsx(Ms,{mode:ne.mode,onChange:re=>void pe(ne,re,!1),compact:!0}),e.jsx("button",{onClick:()=>{const re=R.sessionId;re&&v(re)},className:"machine-btn flex items-center gap-1",title:"Open current view in dashboard",disabled:!R.sessionId,children:ne.mode==="chat"?e.jsx(rt,{size:14}):e.jsx(Be,{size:13})})]}),de==="stopped"?e.jsx("button",{onClick:()=>{(async()=>{if(S){await x(R.type,R.workspace?{workspace:R.workspace}:void 0)&&K(R.type);return}const re=await m(R.type,R.workspace);re.success&&(K(R.type),re.sessionId&&v(re.sessionId))})()},disabled:V.includes(R.type),className:"machine-btn text-green-500 border-green-500/30",title:"Restart",children:V.includes(R.type)?"⏳":e.jsx(wa,{size:14})}):e.jsx("button",{onClick:()=>he(R),className:"machine-btn text-red-500 border-red-500/30",title:"Stop",children:e.jsx(Rn,{size:14})})]})]}),O&&O.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:O.aiAgents.map(re=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Pn(re.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[re.name," · ",_e(re.status)]},re.id))}),O&&(M[O.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:(M[O.type]||[]).map(re=>e.jsxs("button",{disabled:X===`${O.type}.${re.type}`,onClick:async()=>{const we=`${O.type}.${re.type}`;Q(we);try{await d(n,"set_ide_extension",{ideType:O.type,extensionType:re.type,enabled:!re.enabled}),Y(Ke=>({...Ke,[O.type]:(Ke[O.type]||[]).map(Me=>Me.type===re.type?{...Me,enabled:!Me.enabled}:Me)}))}catch(Ke){console.error("Extension toggle failed:",Ke)}finally{Q(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 ${re.enabled?"bg-violet-500/[0.08] border-violet-500/20 text-violet-400":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${re.enabled?"bg-violet-400 shadow-[0_0_4px_rgba(139,92,246,0.4)]":"bg-zinc-600"}`}),re.name,e.jsx("span",{className:"text-[9px] font-normal",children:re.enabled?"ON":"OFF"})]},re.type))})]})]},R.id)})]})]})}const mn=[{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 kc({machine:t,machineId:s,providers:n,ideSessions:r,cliSessions:i,acpSessions:o,actions:c,getIcon:d,initialCategory:l="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:x}){var b;const[m,h]=a.useState(l);a.useEffect(()=>{h(l)},[l]);const g=a.useMemo(()=>({ide:r.length,cli:i.length,acp:o.length}),[r.length,i.length,o.length]);return e.jsxs("div",{className:"machine-workspace-tab",children:[e.jsxs("div",{className:"machine-workspace-tab-header",children:[e.jsx("div",{className:"machine-workspace-tab-title",children:"Workspace launcher"}),e.jsx("div",{className:"machine-workspace-tab-subtitle",children:"Choose a workspace context first, then pick how you want to open it."})]}),e.jsx("div",{className:"machine-workspace-section-tabs",children:mn.map(w=>e.jsxs("button",{type:"button",className:`machine-workspace-section-tab${m===w.id?" active":""}`,onClick:()=>h(w.id),children:[e.jsx("span",{children:w.label}),e.jsx("span",{className:"machine-workspace-section-count",children:g[w.id]})]},w.id))}),e.jsx("div",{className:"machine-workspace-section-helper",children:(b=mn.find(w=>w.id===m))==null?void 0:b.helper}),m==="ide"&&e.jsx(ms,{category:"ide",machine:t,machineId:s,providers:n,managedEntries:r,getIcon:d,actions:c,sendDaemonCommand:x,initialWorkspaceId:p,initialWorkspacePath:u}),m==="cli"&&e.jsx(ms,{category:"cli",machine:t,machineId:s,providers:n,managedEntries:i,getIcon:d,actions:c,initialWorkspaceId:p,initialWorkspacePath:u}),m==="acp"&&e.jsx(ms,{category:"acp",machine:t,machineId:s,providers:n,managedEntries:o,getIcon:d,actions:c,initialWorkspaceId:p,initialWorkspacePath:u})]})}function Nc({onNicknameSynced:t}={}){var $,D,V,ae,G,W,ee,F,K;const{id:s}=sa(),n=dt(),r=js(),{sendCommand:i}=Qe(),o=Is(),c=o.ides||[],d=o.initialLoaded??!0,l=c.find(M=>M.id===s&&M.daemonMode),[p,u]=a.useState("workspace"),[x,m]=a.useState("ide"),h=a.useRef(null),g=hc({machineId:s,registeredMachineId:(l==null?void 0:l.machineId)||null,sendDaemonCommand:i,onNicknameSynced:t,logsEndRef:h});a.useEffect(()=>Je.onToast(Y=>{o.setToasts(Q=>{if(Q.some(me=>me.message===Y.message&&Y.timestamp-me.timestamp<3e3))return Q;const oe={id:Y.id,message:Y.message,type:Y.type,timestamp:Y.timestamp,targetKey:Y.targetKey,actions:Y.actions};return[...Q.slice(-4),oe]});const X=Y.duration||5e3;setTimeout(()=>o.setToasts(Q=>Q.filter(J=>J.id!==Y.id)),X)}),[o]);const b=(l==null?void 0:l.availableProviders)||[],w={};for(const M of b)w[M.type]=M.icon;const f=M=>w[M]||"",y=l?{id:l.id,hostname:Bn(l,{fallbackId:l.id}),platform:(($=l.machine)==null?void 0:$.platform)||"unknown",arch:((D=l.machine)==null?void 0:D.arch)||"",cpus:((V=l.machine)==null?void 0:V.cpus)||0,totalMem:((ae=l.machine)==null?void 0:ae.totalMem)||0,freeMem:((G=l.machine)==null?void 0:G.freeMem)||0,availableMem:(W=l.machine)==null?void 0:W.availableMem,loadavg:((ee=l.machine)==null?void 0:ee.loadavg)||[],uptime:((F=l.machine)==null?void 0:F.uptime)||0,release:((K=l.machine)==null?void 0:K.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,k=c.filter(M=>M.daemonId===s&&!M.daemonMode).filter(M=>!Ot(M)&&!xt(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,version:M.version||"",instanceId:M.instanceId||"",status:M.status,workspace:M.workspace||null,terminals:M.terminals||0,aiAgents:ei(M.aiAgents||M.agents||[]),activeChat:M.activeChat||null,chats:M.chats||[],childSessions:M.childSessions||[],cdpConnected:M.cdpConnected||!1,daemonId:s})),j=c.filter(M=>M.daemonId===s&&Ot(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,cliName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,mode:M.mode,daemonId:s})),v=c.filter(M=>M.daemonId===s&&xt(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,acpName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,currentModel:M.currentModel,currentPlan:M.currentPlan,daemonId:s}));if(!y)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:()=>n("/machines"),className:"machine-btn-back",children:"← Back to Burrows"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const T=qe(l,{fallbackId:y.id}),S="workspace",C=r.state,_=C==null?void 0:C.initialMachineTab,B=C==null?void 0:C.initialWorkspaceCategory,H=C==null?void 0:C.initialWorkspaceId,E=C==null?void 0:C.initialWorkspacePath,N=_==="ides"||_==="clis"||_==="acps"?"workspace":_||S,A=_==="ides"?"ide":_==="clis"?"cli":_==="acps"?"acp":B,P=[...k.map(M=>{var Y,X,Q,J,oe;return{id:`ide:${M.type}:${M.workspace||""}`,label:((Y=M.activeChat)==null?void 0:Y.title)||M.type,kind:"ide",providerType:M.type,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,timestamp:((oe=(J=(Q=(X=M.activeChat)==null?void 0:X.messages)==null?void 0:Q.at)==null?void 0:J.call(Q,-1))==null?void 0:oe.timestamp)||0}}),...j.map(M=>{var Y,X,Q,J,oe;return{id:`cli:${M.type}:${M.workspace||""}`,label:((Y=M.activeChat)==null?void 0:Y.title)||M.cliName,kind:"cli",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,timestamp:((oe=(J=(Q=(X=M.activeChat)==null?void 0:X.messages)==null?void 0:Q.at)==null?void 0:J.call(Q,-1))==null?void 0:oe.timestamp)||0}}),...v.map(M=>{var Y,X,Q,J,oe;return{id:`acp:${M.type}:${M.workspace||""}`,label:((Y=M.activeChat)==null?void 0:Y.title)||M.acpName,kind:"acp",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.currentModel||M.workspace||void 0,workspace:M.workspace||void 0,currentModel:M.currentModel,timestamp:((oe=(J=(Q=(X=M.activeChat)==null?void 0:X.messages)==null?void 0:Q.at)==null?void 0:J.call(Q,-1))==null?void 0:oe.timestamp)||0}})].sort((M,Y)=>Y.timestamp-M.timestamp).map(({timestamp:M,...Y})=>Y),I=(l.recentLaunches||[]).length>0?l.recentLaunches.map(M=>({id:M.id,label:M.title||M.providerName||M.providerType,kind:M.kind,providerType:M.providerType,providerSessionId:M.providerSessionId,subtitle:M.currentModel||M.workspace||void 0,workspace:M.workspace,currentModel:M.currentModel})):P,q=async M=>{if(M.kind==="ide"&&M.providerType){await g.handleLaunchIde(M.providerType,M.workspace?{workspace:M.workspace}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await g.runLaunchCliCore({cliType:M.providerType,dir:M.workspace||"",model:M.kind==="acp"?M.currentModel:void 0,resumeSessionId:M.providerSessionId});return}m(M.kind),u("workspace")};a.useEffect(()=>{u(N)},[S,N,y.id]),a.useEffect(()=>{A&&m(A)},[A,y.id]);const L=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{size:14})," Workspace"]}),count:k.length+j.length+v.length},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gt,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ja,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ga,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"dashboard-header machine-detail-header !flex-col !items-stretch",children:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"machine-detail-header-row flex items-center gap-2 md:gap-3.5 w-full min-w-0",children:[e.jsx("button",{onClick:()=>n("/machines"),className:"machine-btn-back flex shrink-0",children:"←"}),e.jsxs("div",{className:"machine-detail-title-wrap min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[g.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:g.nicknameInput,onChange:M=>g.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&g.handleSaveNickname(),M.key==="Escape"&&g.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:g.handleSaveNickname,className:"machine-btn text-green-500 border-green-500/30 shrink-0",children:"✓"}),e.jsx("button",{onClick:()=>g.setEditingNickname(!1),className:"machine-btn shrink-0",children:"✕"})]}):e.jsx("h1",{className:"header-title cursor-pointer truncate",onClick:()=>{g.setEditingNickname(!0),g.setNicknameInput(y.machineNickname||"")},title:"Click to set nickname",children:T}),e.jsx("span",{className:"status-dot-md online shrink-0"})]}),e.jsxs("div",{className:"header-subtitle machine-detail-subtitle mt-1 flex-wrap gap-1 md:gap-2 items-center display-none-mobile",children:[e.jsxs("span",{children:[y.platform," · ",y.arch]}),e.jsxs("span",{children:[y.cpus," cores"]}),(l==null?void 0:l.version)&&e.jsxs("span",{children:["v",l.version]}),y.p2p.available&&e.jsxs("span",{children:["P2P ",y.p2p.state==="connected"?"connected":y.p2p.state]}),y.cdpConnected&&e.jsx("span",{children:"CDP ready"}),y.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-80 shrink-0",children:y.hostname})]})]})]})}),e.jsx("div",{className:"machine-tabs w-full overflow-x-auto overflow-y-hidden pb-1 -mb-1 mt-2",children:L.map(M=>e.jsxs("button",{onClick:()=>u(M.id),className:`machine-tab shrink-0${p===M.id?" active":""}`,children:[M.label,M.count!==void 0&&e.jsx("span",{className:"tab-count",children:M.count})]},M.id))})]}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:"machine-page-shell",children:e.jsxs("div",{className:"machine-tab-panel",children:[p==="workspace"&&e.jsxs("div",{className:"machine-workspace-panel",children:[e.jsx(vc,{machineEntry:l,providers:b,recentLaunches:I,onUpgradeDaemon:async()=>{try{await i(s,"daemon_upgrade",{})}catch{}},onOpenLogs:()=>u("logs"),onOpenRecent:q,onOpenWorkspace:M=>{m(M),u("workspace")},onGoTab:u}),e.jsx(kc,{machine:y,machineId:s,providers:b,ideSessions:k,cliSessions:j,acpSessions:v,actions:g,getIcon:f,initialCategory:x,initialWorkspaceId:H,initialWorkspacePath:E,sendDaemonCommand:i})]}),p==="providers"&&e.jsx(bc,{machineId:s,providers:b,sendDaemonCommand:i}),p==="overview"&&e.jsx(mc,{machine:y,ideSessions:k,cliSessions:j,acpSessions:v,actions:g}),p==="logs"&&e.jsx(gc,{machineId:s,sendDaemonCommand:i})]})})}),g.launchPick&&y&&e.jsx(yc,{machine:y,launchPick:g.launchPick,actions:g}),e.jsx(Hn,{toasts:o.toasts||[],onDismiss:M=>o.setToasts(Y=>Y.filter(X=>X.id!==M)),onClickToast:M=>{M.targetKey}}),e.jsx("style",{children:`
64
- @keyframes toast-in {
65
- from { opacity: 0; transform: translateX(40px); }
66
- to { opacity: 1; transform: translateX(0); }
67
- }
68
- `})]})}function Sc(){const[t,s]=a.useState({ide:[],cli:[],ext:[],acp:[]}),[n,r]=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=[],p=[],u=[];Object.values(c.providers||{}).forEach(m=>{const h={name:m.name||"Unknown",status:m.status||"Stable",details:m.details||"Community Provider"};m.category==="ide"?d.push(h):m.category==="cli"?l.push(h):m.category==="extension"?p.push(h):m.category==="acp"&&u.push(h)});const x=(m,h)=>{const g={Stable:1,Beta:2,WIP:3},b=g[m.status]||99,w=g[h.status]||99;return b!==w?b-w:m.name.localeCompare(h.name)};s({ide:d.sort(x),cli:l.sort(x),ext:p.sort(x),acp:u.sort(x)})}).catch(c=>console.error("Failed to load capabilities:",c)).finally(()=>r(!1))},[]);const i=c=>c==="Stable"?e.jsxs("div",{className:"flex items-center gap-1.5 text-success",children:[e.jsx(Mn,{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(Ss,{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(An,{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 n?e.jsx(Ft,{title:"Capabilities",subtitle:"Provider registry coverage for IDEs, CLI agents, extensions, and ACPs",icon:e.jsx(Wt,{}),widthClassName:"max-w-5xl",children:e.jsx(Ts,{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(Ft,{title:"Capabilities",subtitle:"Provider registry coverage for IDEs, CLI agents, extensions, and ACPs",icon:e.jsx(Wt,{}),widthClassName:"max-w-5xl",contentClassName:"animate-fade-in",children:[e.jsx(Re,{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(Re,{title:"IDE support",icon:e.jsx(Be,{className:"w-4 h-4"}),description:"Desktop editors and IDE surfaces with registry-backed providers.",children:o(t.ide)}),e.jsx(Re,{title:"Standalone CLI agents",icon:e.jsx(Cs,{className:"w-4 h-4"}),description:"CLI-first agents that can participate in the standalone dashboard.",children:o(t.cli)}),e.jsx(Re,{title:"AI extensions",icon:e.jsx(ct,{className:"w-4 h-4"}),description:"IDE extensions and companion integrations available in the registry.",children:o(t.ext)}),e.jsx(Re,{title:`ACP agents (${t.acp.length} loaded)`,icon:e.jsx(ct,{className:"w-4 h-4"}),description:"ACP-backed providers discovered through the same shared registry.",children:o(t.acp)})]})}class Cc{constructor(){Ie(this,"adapters",new Map);Ie(this,"states",new Map);Ie(this,"runtimeListeners",new Map);Ie(this,"screenshotCallbacks",new Map);Ie(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(s,n){this.adapters.set(s,n),this.states.set(s,n.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,n){this.states.set(s,n)}retryConnection(s){}get(s){const n=this.resolveDaemonId(s);return n?this.adapters.get(n):void 0}getState(s){const n=this.resolveDaemonId(s);return n&&this.states.get(n)||"disconnected"}sendData(s,n){return!1}sendPtyInput(s,n,r){return!1}sendPtyResize(s,n,r,i){return!1}onScreenshot(s,n){return this.screenshotCallbacks.set(s,n),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,n){this.screenshotCallbacks.forEach(r=>r(s,n))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,n){this.statusCallbacks.forEach(r=>r(s,n))}emitRuntimeSnapshot(s,n,r=0,i=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:r,text:n,truncated:i})}emitSessionOutput(s,n,r){!s||typeof n!="string"||!n||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(s,n){const r=this.runtimeListeners.get(s)||new Set;return r.add(n),this.runtimeListeners.set(s,r),()=>{const i=this.runtimeListeners.get(s);i&&(i.delete(n),i.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,n){if(!n)return;const r=await fetch(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`);if(!r.ok)return;const i=await r.json();this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,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,n){var r;(r=this.runtimeListeners.get(s))==null||r.forEach(i=>i(n))}}const He=new Cc;function Ic(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=new URLSearchParams(window.location.search).get("token");return r?`${s}?token=${encodeURIComponent(r)}`:s}const pn=Ic(),xn=3e3,Mc=3e4;let Ve=null,Tc=0;const Yt=new Map;let tt=null,vt=null;function fn(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Ac(t){return t==="connected"?"connected":t}async function Kt(t,s,n){const r=Ni(t,n||{}),i=Ve;if(i&&i.readyState===WebSocket.OPEN){const o=`req_${++Tc}_${Date.now()}`;return new Promise((c,d)=>{const l=setTimeout(()=>{Yt.delete(o),d(new Error(`WS command timeout: ${s}`))},3e4);Yt.set(o,{resolve:p=>{clearTimeout(l),c(p)},reject:p=>{clearTimeout(l),d(p)}}),i.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}class Rc{constructor(s){Ie(this,"daemonId");Ie(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ve==null?void 0:Ve.readyState)===WebSocket.OPEN}get connectionState(){return(Ve==null?void 0:Ve.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,n){return Kt(this.daemonId,s,n)}async sendInput(s,n){return Kt(this.daemonId,"cdp_remote_action",{action:s,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,tt&&(clearInterval(tt),tt=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await Kt(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const i=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());He.emitScreenshot(this.daemonId,i)}}catch{}};n(),tt=setInterval(n,2e3)}stopScreenshots(s){tt&&(clearInterval(tt),tt=null)}}let $e=null;function Lc(t){return(!$e||$e.daemonId!==t)&&($e=new Rc(t)),$e}function Dc({children:t}){const s=a.useRef(Ws()),n=Ws();s.current=n;const{setUserName:r}=jt(),i=a.useRef(r);i.current=r;const[,o]=a.useState("disconnected"),c=a.useCallback((m,h)=>{o(m),vt==null||vt(m,h)},[]),d=a.useRef(null),l=a.useRef(),p=a.useRef(xn),u=a.useRef(!0),x=a.useRef(!1);return a.useEffect(()=>{u.current=!0,x.current=!1;function m(){var b,w;if(!u.current||((b=d.current)==null?void 0:b.readyState)===WebSocket.OPEN||((w=d.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${pn}...`);let g;try{g=new WebSocket(pn)}catch(f){console.error("[Standalone WS] Failed to create WebSocket:",f),h();return}d.current=g,g.onopen=()=>{if(!u.current){g.close();return}c("connected"),p.current=xn,console.log("[Standalone WS] Connected")},Ve=g,g.onmessage=f=>{var y;try{const k=JSON.parse(f.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const j=Yt.get(k.requestId);j&&(Yt.delete(k.requestId),k.type==="error"?j.reject(new Error(((y=k.data)==null?void 0:y.message)||"Command failed")):j.resolve(k.data));return}if(k.type==="session_output"){const j=k.sessionId||k.cliId||k.cliType;j&&He.emitSessionOutput(j,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){He.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="status"||k.type==="initial_state"){const j=k.data;if(!j)return;const{injectEntries:v,markLoaded:T}=s.current,S=j.id||"standalone",C=Lc(S);He.register(S,C),He.setState(S,"connected"),c("connected",S),He.emitStatus(S,j);const _=wi(j,{daemonId:S});fn("ws_status",{type:k.type,daemonId:S,sessions:(j.sessions||[]).map(B=>({id:B.id,parentId:B.parentId,providerType:B.providerType,kind:B.kind,transport:B.transport,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,title:B.title})),recentLaunches:(j.recentLaunches||[]).map(B=>({id:B.id,providerType:B.providerType,kind:B.kind,workspace:B.workspace,lastLaunchedAt:B.lastLaunchedAt}))}),fn("entries",{daemonId:S,entries:_.filter(B=>B.type!=="adhdev-daemon").map(B=>({id:B.id,type:B.type,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,sessionId:B.sessionId}))}),_.length>0&&v(_,{authoritativeDaemonIds:[S]}),T(),j.userName&&i.current&&i.current(j.userName)}}catch(k){console.error("[Standalone WS] Parse error:",k)}},g.onclose=()=>{u.current&&($e==null||$e.stopScreenshots(),$e&&He.setState($e.daemonId,"disconnected"),c("disconnected"),d.current=null,h())},g.onerror=f=>{x.current||!u.current||console.warn("[Standalone WS] Error, will reconnect:",f)}}function h(){if(!u.current)return;clearTimeout(l.current);const g=p.current;console.log(`[Standalone WS] Reconnecting in ${g}ms...`),l.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,Mc),m()},g)}return m(),()=>{u.current=!1,x.current=!0,clearTimeout(l.current),d.current&&(d.current.onerror=null,d.current.onclose=null,d.current.close(),d.current=null,Ve=null),$e&&($e.stopScreenshots(),He.unregister($e.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function _c({children:t}){const[s,n]=a.useState("disconnected"),[r,i]=a.useState(null);a.useEffect(()=>(vt=(c,d)=>{n(c),d&&i(d)},()=>{vt=null}),[]);const o=a.useMemo(()=>{const c=s==="connected",d=Ac(s),l={};return r&&(l[r]=d),l.standalone=d,{wsStatus:s,isConnected:c,connectionStates:l}},[s,r]);return e.jsx(la,{connectionOverrides:o,children:e.jsx(Dc,{children:t})})}const Ec=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Sn,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(ws,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(Gt,{}),label:"Settings"}];function Pc({children:t}){const s=dt(),n=js(),[r,i]=a.useState(!1),[o,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=u=>{s(u),i(!1)},l=()=>{c(u=>{const x=!u;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},p=u=>`nav-item${n.pathname.startsWith(u)?" active":""} cursor-pointer ${o?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${r?" 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"})]}),r&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>i(!1),onKeyDown:u=>u.key==="Escape"&&i(!1)}),e.jsxs("aside",{className:`sidebar ${r?"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:Ec.map(u=>e.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>d(u.path),title:o?u.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:u.icon}),!o&&u.label]},u.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:o?"Docs":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(Wt,{})}),!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${n.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(In,{})}),!o&&"About"]}),!o&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.7.46"]}),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 $c=[{icon:e.jsx(ws,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(rt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(Tn,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(Be,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(ct,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Wt,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Bc=[{icon:e.jsx(Ln,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Sn,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(Xt,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(ba,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(xa,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Mn,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Kc=[{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 Wc(){return e.jsxs(Ft,{icon:e.jsx(In,{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.7.46"]}),children:[e.jsx(Re,{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(Re,{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:$c.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-accent/10 text-accent-light",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Re,{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:Gn.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Jn.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Xn.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(Re,{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:Bc.map(t=>e.jsxs("div",{className:"rounded-xl border border-violet-500/20 bg-violet-500/[0.04] 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-violet-500/10 text-violet-400",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Re,{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-violet-400 text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),e.jsx("tbody",{children:Kc.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(Ts,{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(Ta,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Oc(){const{ides:t}=jt(),s=t.find(x=>x.type==="adhdev-daemon"),n=(s==null?void 0:s.detectedIdes)||[],{sendCommand:r}=Qe(),{userName:i}=jt(),[o,c]=a.useState(i||"");a.useEffect(()=>{i!==void 0&&c(i)},[i]);const d=x=>{const m=x.target.value.trim();s!=null&&s.id&&m!==i&&r(s.id,"set_user_name",{userName:m}).catch(console.error)},[l,p]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=x=>{p(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return e.jsxs(Ft,{icon:e.jsx(Gt,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(Ki,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(Re,{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.7.46"]}),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(Re,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:n.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:n.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(Re,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Vi,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(Re,{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(Xi,{})]}),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(so,{})]}),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(ro,{})]})]})}),e.jsx(Re,{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(Hi,{}),e.jsx(Ze,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ma,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:l,onChange:u})]})}),e.jsx(Re,{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(fa,{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()}})]})})})]})}Fi();eo();const Uc=kn({baseUrl:""});function bn(){const{ides:t,initialLoaded:s}=jt();if(!s)return e.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const n=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return n?e.jsx(ps,{to:`/machines/${n.id}`,replace:!0}):e.jsx(ps,{to:"/dashboard",replace:!0})}function zc(){return e.jsx(na,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(ha,{client:Uc,children:e.jsx(_c,{children:e.jsx(pa,{value:{sendCommand:Kt,sendData:()=>!1},children:e.jsx(Pc,{children:e.jsxs(ra,{children:[e.jsx(Xe,{path:"/dashboard",element:e.jsx(uc,{})}),e.jsx(Xe,{path:"/machine",element:e.jsx(bn,{})}),e.jsx(Xe,{path:"/machines/:id",element:e.jsx(Nc,{})}),e.jsx(Xe,{path:"/machines",element:e.jsx(bn,{})}),e.jsx(Xe,{path:"/capabilities",element:e.jsx(Sc,{})}),e.jsx(Xe,{path:"/about",element:e.jsx(Wc,{})}),e.jsx(Xe,{path:"/settings",element:e.jsx(Oc,{})}),e.jsx(Xe,{path:"*",element:e.jsx(ps,{to:"/dashboard",replace:!0})})]})})})})})})}li({connectionManager:He});aa(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(zc,{})}));