@adhdev/daemon-standalone 0.8.51 → 0.8.53
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.
- package/dist/index.js +938 -301
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-BrT7pA0n.js +71 -0
- package/public/assets/index-OHw5X7HM.css +1 -0
- package/public/index.html +2 -2
- package/vendor/session-host-daemon/index.d.mts +3 -0
- package/vendor/session-host-daemon/index.d.ts +3 -0
- package/vendor/session-host-daemon/index.js +33 -2
- package/vendor/session-host-daemon/index.js.map +1 -1
- package/vendor/session-host-daemon/index.mjs +34 -2
- package/vendor/session-host-daemon/index.mjs.map +1 -1
- package/public/assets/index-BNnOxdJy.css +0 -1
- package/public/assets/index-DW3wxPx9.js +0 -71
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Ri=Object.defineProperty;var Di=(t,s,r)=>s in t?Ri(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var nt=(t,s,r)=>Di(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as qa,a as Ya,b as Ei,c as $i,u as bs,R as et,d as Ls,t as Bi,e as Ki,D as Wi,f as en,g as tn,h as fn,i as Oi,k as Hi,B as Ui,l as zi,m as Ft,N as sn,n as Fi}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();function Vi(t={}){const s=Math.max(1,Math.floor(t.capacity||200)),r=[];return{record(n){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(o),r.length>s&&r.splice(0,r.length-s),o},list(n={}){const o=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-o).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Qt=Vi();function Vn(t){const s={};for(const r of t)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:t.length,ids:t.map(r=>r.id),statuses:t.map(r=>String(r.status||"unknown")),transports:s}}const Xa=a.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),Ja=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Gn(t){var r,n;let s=0;return"activeChat"in t&&(s+=4),(r=t.childSessions)!=null&&r.length&&(s+=2),t.workspace&&(s+=1),t.machine&&(s+=1),(n=t.agents)!=null&&n.length&&(s+=1),s}function Pr(t,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},o=s.version??r.version??t.version,i=s.serverVersion??t.serverVersion??r.serverVersion,c=s.versionMismatch===!0||t.versionMismatch===!0,d=s.versionUpdateRequired===!0||t.versionUpdateRequired===!0,p=s.versionUpdateReason??t.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),p&&(n.versionUpdateReason=p),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),d&&(n.versionUpdateRequired=!0),n)}function ur(t){return Array.isArray(t)?t.map(ur):!t||typeof t!="object"?t:Object.fromEntries(Object.entries(t).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,ur(r)]))}function Gi(t,s){try{return JSON.stringify(ur(t))===JSON.stringify(ur(s))}catch{return!1}}function zs(t,s,r){return Gi(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function qi(t,s,r){var p,f,m,h,w,S,I;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(u=>({...u,_lastUpdate:n}));const i=new Map;for(const u of s)i.set(u.id,u);for(const u of t){const b=i.get(u.id);if(!b){i.set(u.id,{...u,_lastUpdate:n});continue}const v=Gn(u),l=Gn(b);if(v>l){const N=(p=u.chats)!=null&&p.length?u.chats:b.chats,A=Pr(b,u,{...b,...u,chats:N,_lastUpdate:n});i.set(u.id,zs(b,A,n))}else if(v<l){const N={};if(u.status&&u.status!==b.status&&(N.status=u.status),u.cdpConnected!==void 0&&(N.cdpConnected=u.cdpConnected),(f=u.chats)!=null&&f.length&&!((m=b.chats)!=null&&m.length)&&(N.chats=u.chats),u.machineNickname!==void 0&&u.machineNickname!==b.machineNickname&&(N.machineNickname=u.machineNickname),u.version!==void 0&&(N.version=u.version),u.serverVersion!==void 0&&(N.serverVersion=u.serverVersion),u.versionMismatch===!0&&(N.versionMismatch=!0),Object.keys(N).length>0){const A=Pr(b,u,{...b,...N,_lastUpdate:b._lastUpdate});i.set(u.id,zs(b,A,n))}else zs(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const N=u.timestamp||n,A=b._lastUpdate||b.timestamp||0;if(N>=A){const k=(h=u.chats)!=null&&h.length?u.chats:b.chats,x=Pr(b,u,{...b,...u,chats:k,_lastUpdate:n});i.set(u.id,zs(b,x,n))}else(w=u.chats)!=null&&w.length&&!((S=b.chats)!=null&&S.length)&&i.set(u.id,{...b,chats:u.chats})}}const c=new Set(t.map(u=>u.id)),d=new Set;for(const u of t){const b=u.daemonId||((I=u.id)==null?void 0:I.split(":")[0]);b&&d.add(b)}for(const[u,b]of i){const v=b.daemonId||u.split(":")[0];if(!d.has(v))continue;if(o.has(v)&&!c.has(u)){i.delete(u);continue}const l=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(u)&&l>1e4||b.transport==="acp"&&!c.has(u)&&l>1e4||b.transport==="cdp-page"&&!c.has(u)&&l>3e4)&&i.delete(u)}for(const[u,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(u);return Array.from(i.values())}function Yi(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function Xi({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,d]=a.useState([]),[p,f]=a.useState(void 0),m=a.useRef(r);a.useEffect(()=>{m.current=r},[r]);const h=a.useCallback((v,l)=>{n(N=>{let A=!1;const k=N.map(x=>x.id!==v||x.chats===l?x:(A=!0,{...x,chats:l}));return A?k:N})},[]),w=a.useCallback((v,l)=>{n(N=>{const A=N.length===0?v:qi(v,N,l),k=!Yi(N,A);return k&&Qt.record({kind:"dashboard.entries_applied",payload:{incoming:Vn(v),next:Vn(A)}}),k?A:N})},[]),S=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:w,markLoaded:S,getIdes:()=>m.current}),[w,S]),u=s,b=a.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:o,toasts:c,setToasts:d,wsStatus:(u==null?void 0:u.wsStatus)??"connected",isConnected:(u==null?void 0:u.isConnected)??!0,connectionStates:(u==null?void 0:u.connectionStates)??{},connectionTransports:(u==null?void 0:u.connectionTransports)??{},showReconnected:(u==null?void 0:u.showReconnected)??!1,retryConnection:u==null?void 0:u.retryConnection,isP2PActive:(u==null?void 0:u.isP2PActive)??!1,p2pStates:(u==null?void 0:u.p2pStates)??{},userRole:u==null?void 0:u.userRole,userName:p,setUserName:f}),[r,h,o,c,u==null?void 0:u.wsStatus,u==null?void 0:u.isConnected,u==null?void 0:u.connectionStates,u==null?void 0:u.connectionTransports,u==null?void 0:u.showReconnected,u==null?void 0:u.retryConnection,u==null?void 0:u.isP2PActive,u==null?void 0:u.p2pStates,u==null?void 0:u.userRole,p]);return e.jsx(Ja.Provider,{value:I,children:e.jsx(Xa.Provider,{value:b,children:t})})}function es(){return a.useContext(Xa)}function pr(){return a.useContext(Ja)}function Za(t){const{baseUrl:s,getToken:r,onUnauthorized:n}=t;function o(d){return d.startsWith("http")?d:`${s}${d.startsWith("/")?"":"/"}${d}`}function i(d){const p=r==null?void 0:r(),f=o(d),m=d.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return p&&m.searchParams.set("token",p),!d.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(d,p={}){const f={"Content-Type":"application/json",...p.headers||{}},m=r==null?void 0:r();m&&(f.Authorization=`Bearer ${m}`);const h=o(d),w=new AbortController,S=setTimeout(()=>w.abort(),15e3);try{const I=await fetch(h,{...p,headers:f,signal:w.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const u=await I.json().catch(()=>({error:I.statusText}));throw new Error(u.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,p,f={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:p,payload:f})}),execTerminal:(d,p,f)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:p,name:f})}),sendAgentMessage:(d,p,f)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:p,message:f})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,p,f)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:p,action:f?"approve":"reject"})}),getMuxState:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/state`),getMuxSocketInfo:d=>c(`/api/v1/mux/${encodeURIComponent(d)}/socket-info`),controlMux:(d,p,f={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:p,payload:f})}),getMuxEventsUrl:d=>i(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>i(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const Ji=Za({baseUrl:"http://localhost:3847"}),Zi=a.createContext(Ji);function Qi({client:t,children:s}){return e.jsx(Zi.Provider,{value:t,children:s})}const ec={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Qa=a.createContext(ec);function tc({value:t,children:s}){return e.jsx(Qa.Provider,{value:t,children:s})}function St(){return a.useContext(Qa)}const Ee={size:18};function eo({size:t=Ee.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 xn({size:t=Ee.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 Ut({size:t=Ee.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 hn({size:t=Ee.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 sc({size:t=Ee.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 rc({size:t=Ee.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 to({size:t=Ee.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 nc({size:t=Ee.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 vr({size:t=Ee.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 so({size:t=Ee.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 ac({size:t=Ee.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 Kt({size:t=Ee.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 Nt({size:t=Ee.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 bn({size:t=Ee.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 oc({size:t=Ee.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=Ee.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 gs({size:t=Ee.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 ts({size:t=Ee.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 Rs({size:t=Ee.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 ro({size:t=Ee.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 no({size:t=Ee.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 ao({size:t=Ee.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 ic({size:t=Ee.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 wr({size:t=Ee.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 cc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function gn({size:t=Ee.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 lc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:t=Ee.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 oo({size:t=Ee.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 dc({size:t=Ee.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 uc({size:t=Ee.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 pc({size:t=Ee.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 jr({size:t=Ee.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 mc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"5"}),e.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),e.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),e.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),e.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),e.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),e.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),e.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),e.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function fc({size:t=Ee.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function xc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function hc({size:t=Ee.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 bc({size:t=Ee.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 gc({size:t=Ee.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 yc({size:t=Ee.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 vc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),e.jsx("path",{d:"M13 2h9v9"}),e.jsx("path",{d:"M22 2L13 11"})]})}function wc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function jc({size:t=Ee.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),e.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),e.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),e.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),e.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),e.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),e.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),e.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),e.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),e.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function kc({size:t=Ee.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:"6",width:"13",height:"13",rx:"2"}),e.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function qn({size:t=Ee.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:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),e.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Yn(t){return!!t&&typeof t=="object"&&"text"in t}function yn(t,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let o="";return typeof t=="string"?o=t:Array.isArray(t)?o=t.map(i=>typeof i=="string"?i:Yn(i)?String(i.text||""):"").join(r):Yn(t)?o=String(t.text||""):o=String(t||""),n?o.replace(/\s+/g," ").trim():o}function ss(t){return yn(t,{normalizeWhitespace:!0})}const Lr=new Map;function io(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Nc(t,s,r){return Number(t.receivedAt||r[ps(t,s)]||0)||0}function Sc(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ps(t,s){const r=t,n=yn(t.content,{joiner:`
|
|
3
|
-
`});return[t.id?`id:${t.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof t.index=="number"?`msgIndex:${t.index}`:"",t.role?`role:${t.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const Xn=5e3,Cc=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(qa,{remarkPlugins:[Ya],children:s.text}),e.jsx("span",{className:"action-time",children:io(s.timestamp)})]})},(t,s)=>t.log===s.log),Ic=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:d}){var A,k,x;const p=(s.role||"").toLowerCase(),f=p==="user"||p==="human",m=s.kind||(p==="tool"?"tool":"standard"),h=yn(s.content,{joiner:`
|
|
4
|
-
`});if(m==="thought"){const g=typeof((A=s.meta)==null?void 0:A.label)=="string"?s.meta.label:"Thought";return e.jsxs("div",{className:"self-start chat-msg-thought",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx(uc,{size:13}),e.jsx("span",{children:g})]}),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(`
|
|
5
|
-
`)[0].slice(0,80)})]});if(m==="terminal"){const g=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",y=typeof((x=s.meta)==null?void 0:x.label)=="string"?s.meta.label:"Ran command";return e.jsxs("div",{className:"self-start chat-msg-terminal",children:[e.jsxs("div",{className:"chat-msg-header",children:[e.jsx("span",{children:g}),e.jsx("span",{children:y})]}),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 w=s.meta,I=(typeof(w==null?void 0:w.renderMode)=="string"?w.renderMode.trim():"")==="preformatted",u=h,b=i&&!f&&!I&&u.length>Xn,v=b&&!c?u.slice(0,Xn):u,l=I,N=!l&&Sc(v);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(u||f)&&e.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${u?"mb-1.5":"mb-0"}`,children:[e.jsx("span",{className:"chat-sender",children:f?o||"You":s.senderName||n}),r!=null&&e.jsx("span",{className:"chat-time",children:io(r)})]}),u&&e.jsx("div",{className:"chat-markdown",children:l?e.jsx("pre",{className:"chat-preformatted",children:v}):N?e.jsx(qa,{remarkPlugins:[Ya,Ei,$i],children:v}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:v})}),b&&e.jsx("button",{onClick:d,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(u.length/100)*100} chars) ↓`})]})})},(t,s)=>t.message===s.message&&t.receivedAt===s.receivedAt&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isTextExpanded===s.isTextExpanded),Ac=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:p={},emptyState:f,onLoadMore:m,isLoadingMore:h,hasMoreHistory:w,hiddenLiveCount:S=0,loadError:I,scrollToBottomRequestNonce:u},b){var oe;const v=a.useRef(null),l=a.useRef(null),N=a.useRef(null),A=a.useRef(0),k=a.useRef(""),x=a.useRef(!1),g=a.useRef(null),y=a.useRef(!1),j=a.useRef(null),E=a.useRef(!1),[R,K]=a.useState(new Set),D=a.useRef(!1),V=a.useRef(!1),_=()=>{const W=v.current;return W?W.scrollHeight-W.scrollTop-W.clientHeight<200:!0},C=a.useCallback((W="auto")=>{const be=v.current;be&&be.scrollTo({top:be.scrollHeight,behavior:W})},[]),T=a.useCallback(()=>{const W=v.current;!W||!d||Lr.set(d,{top:W.scrollTop,fromBottom:Math.max(0,W.scrollHeight-W.scrollTop-W.clientHeight)})},[d]),z=a.useCallback(()=>{var te;const W=v.current,be=(te=window.getSelection)==null?void 0:te.call(window);if(!W||!be||be.rangeCount===0||be.isCollapsed){E.current=!1;return}const X=be.anchorNode,ue=be.focusNode;E.current=!!(X&&ue&&W.contains(X)&&W.contains(ue))},[]),L=a.useCallback((W="auto")=>{g.current!=null&&cancelAnimationFrame(g.current),g.current=requestAnimationFrame(()=>{g.current=null,C(W)})},[C]),$=s.length>0?`${s.length}:${(((oe=s[s.length-1])==null?void 0:oe.content)||"").length}`:"0:0";a.useEffect(()=>{const W=!x.current,be=k.current!==d;if(k.current=d,W||be){if(x.current=!0,D.current=!1,y.current=!0,!E.current){const ue=d?Lr.get(d):null;ue?requestAnimationFrame(()=>{const te=v.current;if(!te)return;const ae=Math.max(0,te.scrollHeight-te.clientHeight-ue.fromBottom);te.scrollTop=Number.isFinite(ae)?ae:ue.top,V.current=!0}):L("auto")}A.current=s.length;return}s.length>A.current?!D.current&&!E.current&&L("auto"):_()&&!D.current&&!E.current&&L("auto"),A.current=s.length},[$,d,c,s.length,L]),a.useEffect(()=>{u&&(D.current=!1,y.current=!0,V.current=!0,j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{y.current=!1,j.current=null},180),E.current||L("auto"))},[L,u]),a.useEffect(()=>()=>{T(),g.current!=null&&cancelAnimationFrame(g.current),j.current!=null&&window.clearTimeout(j.current)},[T]),a.useEffect(()=>{const W=l.current;if(!W)return;const be=()=>{j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{y.current=!1,j.current=null},180)},X=new ResizeObserver(()=>{y.current&&(E.current||(L("auto"),be()))});return X.observe(W),()=>{X.disconnect(),j.current!=null&&(window.clearTimeout(j.current),j.current=null)}},[L,d]),a.useImperativeHandle(b,()=>({scrollToBottom:(W="smooth")=>{C(W)}}),[C]),a.useEffect(()=>{const W=v.current;if(!W)return;let be;const X=()=>{clearTimeout(be),be=setTimeout(()=>{D.current=!_(),T()},50)};return W.addEventListener("scroll",X,{passive:!0}),()=>{W.removeEventListener("scroll",X),clearTimeout(be)}},[T]),a.useEffect(()=>(document.addEventListener("selectionchange",z),()=>document.removeEventListener("selectionchange",z)),[z]);const H=a.useRef(0),se=a.useRef(!1);a.useEffect(()=>{const W=v.current;if(!W||!se.current||H.current===0)return;const be=W.scrollHeight-H.current;be>0&&(W.scrollTop=be),T(),H.current=0,se.current=!1},[s.length,T]),a.useEffect(()=>{if(V.current||!d)return;const W=Lr.get(d),be=v.current;if(!W||!be)return;const X=Math.max(0,be.scrollHeight-be.clientHeight-W.fromBottom);be.scrollTop=Number.isFinite(X)?X:W.top,V.current=!0},[d,s.length]);const Y=()=>{const W=v.current;W&&(H.current=W.scrollHeight),se.current=!0,m==null||m()},ie=a.useMemo(()=>{const W=s.map((te,ae)=>({type:"message",data:te,index:ae,ts:Nc(te,ae,p)}));if(!r||r.length===0)return W;const be=[...r].sort((te,ae)=>te.timestamp-ae.timestamp).map((te,ae)=>({type:"action",data:te,index:ae,ts:te.timestamp})),X=[];let ue=0;for(const te of W){for(;ue<be.length&&te.ts>0&&be[ue].ts<te.ts;)X.push(be[ue++]);X.push(te)}for(;ue<be.length;)X.push(be[ue++]);return X},[s,r,p]),je=S>0||!!w,G=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return e.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:l,className:"chat-container-content",children:[h&&e.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),je&&!h&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:Y,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${I&&S===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:G})}),ie.length===0&&!je&&(f||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ie.map(W=>{if(W.type==="action"){const le=W.data;return e.jsx(Cc,{log:le},`action-${W.index}`)}const be=W.data,X=W.index,ue=ps(be,X),te=be.receivedAt||p[ue],ae=`${d}-${ue}`,fe=R.has(ae);return e.jsx(Ic,{message:be,receivedAt:te,agentName:n,userName:o,isCliMode:i,isTextExpanded:fe,onToggleTextExpanded:()=>K(le=>{const he=new Set(le);return fe?he.delete(ae):he.add(ae),he})},`msg-${ue}`)}),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:N})]})})}),Mc=a.memo(Ac,(t,s)=>t.messages===s.messages&&t.actionLogs===s.actionLogs&&t.agentName===s.agentName&&t.userName===s.userName&&t.isCliMode===s.isCliMode&&t.isWorking===s.isWorking&&t.contextKey===s.contextKey&&t.receivedAtMap===s.receivedAtMap&&t.emptyState===s.emptyState&&t.onLoadMore===s.onLoadMore&&t.isLoadingMore===s.isLoadingMore&&t.hasMoreHistory===s.hasMoreHistory&&t.hiddenLiveCount===s.hiddenLiveCount&&t.loadError===s.loadError&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),Tc="modulepreload",_c=function(t){return"/"+t},Jn={},Pc=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(p=>{if(p=_c(p),p in Jn)return;Jn[p]=!0;const f=p.endsWith(".css"),m=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":Tc,f||(h.as="script"),h.crossOrigin="",h.href=p,d&&h.setAttribute("nonce",d),document.head.appendChild(h),f)return new Promise((w,S)=>{h.addEventListener("load",w),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&i(d.reason);return s().catch(i)})};let Zn=!1;const co=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,d]=a.useState(null),p=a.useRef([]),f=a.useRef(!1),m=a.useRef(!1),h=a.useRef(!1),w=()=>{const S=i.current;if(S){f.current&&(S.clear(),f.current=!1);for(const I of p.current)S.write(I);p.current=[],m.current&&(S.fit(),m.current=!1),h.current&&(S.bumpResize(),h.current=!1)}};return a.useImperativeHandle(o,()=>({write:S=>{i.current?i.current.write(S):p.current.push(S)},clear:()=>{i.current?i.current.clear():(p.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(p.current=[],f.current=!0)},resize:(S,I)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(S,I)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():h.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const S=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(S)},[c]),a.useEffect(()=>{let S=!1;return Pc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(I=>{Zn||(Zn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||d(()=>I.GhosttyTerminalView)}).catch(I=>{console.error("[CliTerminal] failed to load terminal renderer",I)}),()=>{S=!0}},[]),c?e.jsx(c,{ref:i,onInput:t,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):e.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});co.displayName="CliTerminal";function Fs({label:t,value:s,sub:r,icon:n}){return e.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:"text-base flex items-center",children:n}),e.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:t})]}),e.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Qn({value:t,max:s,label:r,color:n="#8b5cf6",detail:o,compact:i=!1}){const c=s>0?Math.min(Math.round(t/s*100),100):0,d=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex justify-between mb-0.5",children:[e.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),e.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),e.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:d}})})]}):e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex justify-between mb-1.5",children:[e.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),e.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),e.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${d}, ${d}cc)`}})}),o&&e.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function Lc({cursorPos:t,viewportRef:s,imgRef:r}){var l;if(!t||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(l=s.current)==null?void 0:l.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,d=n.naturalHeight||o.height,p=c/d,f=o.width/o.height;let m,h,w,S;p>f?(m=o.width,h=o.width/p,w=0,S=(o.height-h)/2):(h=o.height,m=o.height*p,w=(o.width-m)/2,S=0);const I=o.left-i.left+w+m*t.nx,u=o.top-i.top+S+h*t.ny,b=Math.max(8,Math.min(i.width-8,I)),v=Math.max(8,Math.min(i.height-8,u));return e.jsxs("div",{style:{position:"absolute",left:b-8,top:v-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 Rc({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:d,handleImeSubmit:p,isConnActive:f,zoom:m,isMobile:h,mobileFillZoom:w,onZoomOut:S,onZoomReset:I,onZoomIn:u,transportType:b,screenshotUsage:v,lastActionStatus:l}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[e.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${t==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[e.jsx("span",{className:"text-sm",children:t==="mouse"?"🖱️":"👆"}),e.jsx("span",{className:`text-[10px] font-bold ${t==="mouse"?"text-blue-400":"text-slate-400"}`,children:t==="mouse"?"Mouse":"Touch"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:e.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&e.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:e.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>d(N.target.value),onKeyDown:N=>{p(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),e.jsx("div",{className:"relative",children:e.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:e.jsx("span",{className:"text-sm",children:"⚙️"})})}),e.jsx("div",{className:"w-px h-[18px] bg-white/10"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[e.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),e.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),m>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),b==="relay"&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),v&&v.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),l&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:l})]})]}),o&&e.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(h?w:1)+.01?h?"FILL":"FIT":`${Math.round(m*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:N=>{N.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),I()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),e.jsx("button",{onClick:N=>{N.stopPropagation(),u()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Dc({waitingLabel:t,waitingHint:s,transportType:r}){return e.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),e.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:t}),e.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&e.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Ec(){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 ea(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 Ks(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!Ec())return;n.current+=1;const o=r.current;if(!o){console.debug(`[render-trace] ${t}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,d])=>[c,ea(d)]))}),r.current=s;return}const i=Object.keys({...o,...s}).filter(c=>!Object.is(o[c],s[c]));i.length>0&&console.debug(`[render-trace] ${t}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,ea(s[c])]))}),r.current=s})}function $c({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:d,panYRef:p,setPanX:f,setPanY:m,setZoom:h,lastWheelTimeRef:w,onAction:S,setLastActionStatus:I,spawnRippleFromNormalized:u,clampPan:b,isMobile:v,mobileFillZoom:l}){const[N,A]=a.useState(null),k=a.useRef(null),x=a.useRef(null),g=a.useRef(null),y=a.useRef(!1),j=a.useRef(null),E=a.useRef(0),R=a.useRef(null),K=a.useRef(1),D=a.useRef({x:0,y:0}),V=a.useRef(!1),_=a.useRef(n),C=a.useRef(S),T=30,z=550,L=18,$=60,H=400,se=12,Y=()=>{if(k.current)return;const G={nx:.5,ny:.5};k.current=G,A(G)};return a.useEffect(()=>{_.current=n,n==="mouse"&&Y()},[n]),a.useEffect(()=>{C.current=S},[S]),a.useEffect(()=>{const G=t.current;if(!G)return;const oe=ae=>{if(!r.current)return null;const fe=r.current.getBoundingClientRect();return!fe.width||!fe.height?null:{nx:Math.max(0,Math.min(1,(ae.clientX-fe.left)/fe.width)),ny:Math.max(0,Math.min(1,(ae.clientY-fe.top)/fe.height))}},W=(ae,fe)=>{if(!r.current)return{dnx:0,dny:0};const le=r.current,he=le.getBoundingClientRect(),J=le.naturalWidth||he.width,pe=le.naturalHeight||he.height,ne=J/pe,we=he.width/he.height;let ge,P;return ne>we?(ge=he.width,P=he.width/ne):(P=he.height,ge=he.height*ne),{dnx:ae/ge,dny:fe/P}},be=(ae,fe,le)=>{if(le<=1.05)return;const he=-(ae-.5)*100,J=-(fe-.5)*100,pe=b(he,J,le);(Math.abs(pe.x-d.current)>.1||Math.abs(pe.y-p.current)>.1)&&(f(pe.x),m(pe.y),d.current=pe.x,p.current=pe.y)},X=ae=>{const fe=s.current;if(fe&&ae.target instanceof Node&&fe.contains(ae.target))ae.preventDefault();else return;if(ae.touches.length===1){const le=ae.touches[0];x.current={x:le.clientX,y:le.clientY,time:Date.now()},g.current={x:le.clientX,y:le.clientY},V.current||(y.current=!1),j.current=setTimeout(()=>{if(!y.current&&!V.current)if(y.current=!0,_.current==="mouse"){const he=k.current||{nx:.5,ny:.5};I("Right Click"),u(he.nx,he.ny,"right"),C.current("input_click",{...he,button:"right"}).catch(()=>{})}else{const he=oe(le);he&&(I("Right Click"),u(he.nx,he.ny,"right"),C.current("input_click",{...he,button:"right"}).catch(()=>{}))}},500);return}if(ae.touches.length===2){j.current&&clearTimeout(j.current),y.current=!0,V.current=!0;const le=ae.touches[1].clientX-ae.touches[0].clientX,he=ae.touches[1].clientY-ae.touches[0].clientY;R.current=Math.sqrt(le*le+he*he),K.current=c.current,D.current={x:(ae.touches[0].clientX+ae.touches[1].clientX)/2,y:(ae.touches[0].clientY+ae.touches[1].clientY)/2}}},ue=ae=>{const fe=s.current;if(fe&&ae.target instanceof Node&&fe.contains(ae.target)&&ae.preventDefault(),ae.touches.length===1&&g.current){const le=ae.touches[0],he=le.clientX-g.current.x,J=le.clientY-g.current.y;if(!y.current&&x.current){const pe=le.clientX-x.current.x,ne=le.clientY-x.current.y;Math.sqrt(pe*pe+ne*ne)>8&&(y.current=!0,j.current&&clearTimeout(j.current))}if(y.current)if(_.current==="mouse"){const pe=W(he,J),ne=k.current||{nx:.5,ny:.5},we=Math.max(0,Math.min(1,ne.nx+pe.dnx)),ge=Math.max(0,Math.min(1,ne.ny+pe.dny));k.current={nx:we,ny:ge},A({nx:we,ny:ge}),I(`Cursor: ${Math.round(we*100)}%, ${Math.round(ge*100)}%`),be(we,ge,c.current);const P=Date.now();P-w.current>=30&&(w.current=P,C.current("input_mouseMoved",{nx:we,ny:ge}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const ne=pe.clientWidth,we=pe.clientHeight,ge=d.current+he/ne*100,P=p.current+J/we*100,ye=b(ge,P,c.current);f(ye.x),m(ye.y),d.current=ye.x,p.current=ye.y}}else{const pe=oe(le);if(pe){const ne=Date.now();ne-w.current>=40&&(w.current=ne,I("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-he*2.5),deltaY:Math.round(-J*2.5)}).catch(()=>{}))}}g.current={x:le.clientX,y:le.clientY};return}if(ae.touches.length===2&&R.current!==null){const le=ae.touches[1].clientX-ae.touches[0].clientX,he=ae.touches[1].clientY-ae.touches[0].clientY,pe=Math.sqrt(le*le+he*he)/R.current,ne=(ae.touches[0].clientX+ae.touches[1].clientX)/2,we=(ae.touches[0].clientY+ae.touches[1].clientY)/2,ge=ne-D.current.x,P=we-D.current.y,ye=Math.abs(pe-1)>.03;if(_.current==="mouse"){if(ye){const F=Math.max(i,Math.min(5,K.current*pe));h(F),c.current=F}else if(Math.abs(ge)>2||Math.abs(P)>2){const F=k.current||{nx:.5,ny:.5},me=Date.now();me-w.current>=30&&(w.current=me,I("Scroll"),C.current("input_wheel",{nx:F.nx,ny:F.ny,deltaX:Math.round(-ge*3),deltaY:Math.round(-P*3)}).catch(()=>{}))}}else{const F=Math.max(i,Math.min(5,K.current*pe));h(F),c.current=F;const me=s.current;if(me&&F>1){const Ce=me.clientWidth,xe=me.clientHeight,Le=d.current+ge/Ce*100,Be=p.current+P/xe*100,Fe=b(Le,Be,F);f(Fe.x),m(Fe.y),d.current=Fe.x,p.current=Fe.y}}D.current={x:ne,y:we}}},te=ae=>{var fe;if(j.current&&clearTimeout(j.current),R.current=null,ae.touches.length===1&&V.current){const le=ae.touches[0];x.current={x:le.clientX,y:le.clientY,time:Date.now()},g.current={x:le.clientX,y:le.clientY},y.current=!0;return}if(ae.touches.length===0){if(V.current){V.current=!1,y.current=!1;return}if(ae.changedTouches.length===1){const le=ae.changedTouches[0],he=Date.now(),J=he-(((fe=x.current)==null?void 0:fe.time)||0),pe=x.current?le.clientX-x.current.x:0,ne=x.current?le.clientY-x.current.y:0,we=Math.sqrt(pe*pe+ne*ne);if(_.current==="mouse"){if(J<T||J>z||we>L){y.current=!1;return}const ge=k.current||oe(le);ge&&(I(`Click: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),u(ge.nx,ge.ny,"left"),C.current("input_click",{...ge}).catch(()=>{}))}else{if(y.current){y.current=!1;return}if(J<$||J>H||we>se){y.current=!1;return}const ge=oe(le);if(!ge)return;he-E.current<300?(I("Double tap"),u(ge.nx,ge.ny,"double"),C.current("input_click",{...ge,clickCount:2}).catch(()=>{}),E.current=0):(I(`Tap: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),u(ge.nx,ge.ny,"left"),C.current("input_click",{...ge}).catch(()=>{}),E.current=he)}}y.current=!1}};return G.addEventListener("touchstart",X,{passive:!1}),G.addEventListener("touchmove",ue,{passive:!1}),G.addEventListener("touchend",te,{passive:!1}),()=>{G.removeEventListener("touchstart",X),G.removeEventListener("touchmove",ue),G.removeEventListener("touchend",te),j.current&&clearTimeout(j.current)}},[t,s,r,i,c,d,p,f,m,h,w,I,u,b]),{cursorPos:N,cursorPosRef:k,handleToggleInputMode:()=>{o(G=>{const oe=G==="touch"?"mouse":"touch";return oe==="mouse"&&Y(),oe})},handleZoomReset:()=>{const G=v?l:1;h(G),c.current=G,f(0),m(0),d.current=0,p.current=0}}}function lo({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),d=a.useRef(null),p=a.useRef(null),[f,m]=a.useState(null),[h,w]=a.useState(""),[,S]=a.useState(!1),[I,u]=a.useState([]),b=a.useRef(0),[v,l]=a.useState(!1),[N,A]=a.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,g]=a.useState(k?"mouse":"touch"),[y,j]=a.useState(1),E=a.useRef(!1),[R,K]=a.useState(1),[D,V]=a.useState(0),[_,C]=a.useState(0);Ks("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:R,panX:D,panY:_,isMenuOpen:v,isImeOpen:N});const T=a.useRef(0),z=a.useRef(R),L=a.useRef(D),$=a.useRef(_);a.useEffect(()=>{z.current=R},[R]),a.useEffect(()=>{L.current=D},[D]),a.useEffect(()=>{$.current=_},[_]),a.useEffect(()=>{var J;(J=c.current)==null||J.focus()},[]);const H=r==="connected",se=n,Y=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!k||E.current||!se)return;const J=p.current,pe=d.current;if(!J||!pe)return;const ne=()=>{const we=pe.clientWidth,ge=pe.clientHeight,P=J.naturalWidth,ye=J.naturalHeight;if(!P||!ye||!we||!ge)return;const F=Math.min(we/P,ge/ye),Ce=Math.max(we/P,ge/ye)/F;Ce>1.01&&(j(Ce),K(Ce),z.current=Ce),E.current=!0};J.complete&&J.naturalWidth?ne():J.addEventListener("load",ne,{once:!0})},[se,k]);const je=.5;a.useEffect(()=>{R<=je&&(V(0),C(0))},[R,je]);const G=(J,pe,ne)=>{if(ne<=je)return{x:0,y:0};const we=(ne-1)/(2*ne)*100,ge=(ne-1)/(2*ne)*100;return{x:Math.max(-we,Math.min(we,J)),y:Math.max(-ge,Math.min(ge,pe))}},oe=(J,pe)=>{if(!p.current)return null;const ne=p.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(J-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(pe-ne.top)/ne.height))}},W=(J,pe,ne)=>{const we=d.current;if(!we)return;const ge=we.getBoundingClientRect(),P=++b.current;u(ye=>[...ye,{id:P,x:J-ge.left,y:pe-ge.top,type:ne}]),setTimeout(()=>u(ye=>ye.filter(F=>F.id!==P)),600)},be=(J,pe,ne)=>{const we=p.current,ge=d.current;if(!we||!ge)return;const P=we.getBoundingClientRect(),ye=ge.getBoundingClientRect(),F=we.naturalWidth||P.width,me=we.naturalHeight||P.height,Ce=F/me,xe=P.width/P.height;let Le,Be,Fe,st;Ce>xe?(Le=P.width,Be=P.width/Ce,Fe=0,st=(P.height-Be)/2):(Be=P.height,Le=P.height*Ce,Fe=(P.width-Le)/2,st=0);const ze=P.left-ye.left+Fe+Le*J,dt=P.top-ye.top+st+Be*pe,gt=++b.current;u(Ge=>[...Ge,{id:gt,x:ze,y:dt,type:ne}]),setTimeout(()=>u(Ge=>Ge.filter(at=>at.id!==gt)),600)},X=async J=>{var ne;const pe=oe(J.clientX,J.clientY);if(pe){m(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),W(J.clientX,J.clientY,"left"),(ne=c.current)==null||ne.focus();try{const we=await t("input_click",{nx:pe.nx,ny:pe.ny});we!=null&&we.success||s(`❌ Click failed: ${we==null?void 0:we.error}`)}catch(we){s(`❌ Click error: ${we.message||we}`)}}},ue=async(J,pe,ne,we=0)=>{try{await t("input_key",{type:ne?"char":"keyDown",key:J,code:pe,text:ne?J:void 0,unmodifiedText:ne?J:void 0,modifiers:we})}catch(ge){s(`❌ Key error: ${ge.message||ge}`)}},te=async J=>{if(J.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(J.key)&&J.preventDefault();let ne=0;J.altKey&&(ne|=1),J.ctrlKey&&(ne|=2),J.metaKey&&(ne|=4),J.shiftKey&&(ne|=8),m(`Key: ${J.key}`),await ue(J.key,J.code,J.key.length===1,ne)},ae=async J=>{if(J.key==="Enter"){if(J.nativeEvent.isComposing)return;if(h){const pe=h;w(""),m(`IME Sent: ${pe}`);try{const ne=await t("input_type",{text:pe});ne!=null&&ne.success||s(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ IME error: ${ne.message}`)}}else m("Key: Enter"),await ue("Enter","Enter",!1)}};a.useEffect(()=>{const J=c.current;if(!J)return;const pe=ne=>{var we;if((we=p.current)!=null&&we.contains(ne.target)){ne.preventDefault();const ge=Date.now();if(ge-T.current<40)return;T.current=ge;const P=oe(ne.clientX,ne.clientY);if(!P)return;m(`Scroll: ${Math.round(ne.deltaY)}`),t("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return J.addEventListener("wheel",pe,{passive:!1}),()=>J.removeEventListener("wheel",pe)},[t]);const{cursorPos:fe,handleToggleInputMode:le,handleZoomReset:he}=$c({containerRef:c,viewportRef:d,imgRef:p,inputMode:x,setInputMode:g,minZoom:je,zoomRef:z,panXRef:L,panYRef:$,setPanX:V,setPanY:C,setZoom:K,lastWheelTimeRef:T,onAction:t,setLastActionStatus:m,spawnRippleFromNormalized:be,clampPan:G,isMobile:k,mobileFillZoom:y});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:te,onContextMenu:J=>J.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[se?e.jsx("img",{ref:p,src:se,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${D}%, ${_}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:X,onContextMenu:J=>J.preventDefault(),onDragStart:J=>J.preventDefault()}):e.jsx(Dc,{waitingLabel:Y,waitingHint:ie,transportType:i}),x==="mouse"&&se&&e.jsx(Lc,{cursorPos:fe,viewportRef:d,imgRef:p}),I.map(J=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[J.type];return e.jsxs("div",{style:{position:"absolute",left:J.x,top:J.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 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(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},J.id)})]}),e.jsx(Rc,{inputMode:x,onToggleInputMode:le,isImeOpen:N,setIsImeOpen:A,isMenuOpen:v,setIsMenuOpen:l,imeText:h,setImeText:w,handleImeSubmit:ae,isConnActive:H,zoom:R,isMobile:k,mobileFillZoom:y,onZoomOut:()=>K(J=>Math.max(.5,J-.25)),onZoomReset:he,onZoomIn:()=>K(J=>Math.min(5,J+.25)),transportType:i,screenshotUsage:o,lastActionStatus:f}),e.jsx("style",{children:`
|
|
6
|
-
@keyframes slideUp {
|
|
7
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
8
|
-
to { opacity: 1; transform: translateY(0); }
|
|
9
|
-
}
|
|
10
|
-
@keyframes slideUpSidebar {
|
|
11
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
12
|
-
to { opacity: 1; transform: translateY(0); }
|
|
13
|
-
}
|
|
14
|
-
@keyframes click-ripple-ring {
|
|
15
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
16
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
17
|
-
}
|
|
18
|
-
@keyframes click-ripple-dot {
|
|
19
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
20
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
21
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
22
|
-
}
|
|
23
|
-
@keyframes remote-float {
|
|
24
|
-
0% { transform: translateY(0px); }
|
|
25
|
-
50% { transform: translateY(-7px); }
|
|
26
|
-
100% { transform: translateY(0px); }
|
|
27
|
-
}
|
|
28
|
-
`})]})}function vn(t,s={}){if(!t)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-t,c=Math.floor(i/1e3);if(c<o)return n;const d=Math.floor(c/60);if(d<60)return`${d}m${r}`;const p=Math.floor(d/60);if(p<24)return`${p}h${r}`;const f=Math.floor(p/24);return f<7?`${f}d${r}`:new Date(t).toLocaleDateString()}const uo=t=>vn(t);function Bc(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ys(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",o=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Ws(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...Bc(o)})};for(const n of t)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Ds(t,s){if(t.sessionId){const r=s.get(t.sessionId);if(r)return r}return{sessionId:t.sessionId||t.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Es(t,s,r){const n=Ds(t,s),o=ys(t),i=o.isReconnecting,c=o.isConnecting,d=o.isGenerating,p=o.isWaiting,f=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||p,m=n.inboxBucket==="working"||d,h=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:h,requiresAction:f,isWorking:m,isReconnecting:i,isConnecting:c,isGenerating:d,isWaiting:p,inboxBucket:f?"needs_attention":m?"working":h?"task_complete":"idle"}}function Kc(t,s,r){return Es(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Wc(t,s,r){return Ds(t,r||new Map).surfaceHidden}function po({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ys(t).isWaiting||!t.modalButtons)return null;const i=d=>{r||(n(d),s(d))},c=d=>d.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return e.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[t.modalMessage&&e.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:t.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[e.jsx(ts,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((d,p)=>{const f=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),w=r===d,S=r!==null;return e.jsx("button",{onClick:()=>i(d),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!w?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(d)},p)})})]})]})}const It=new Map;function ta({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:d,acpModes:p}){var je;const{sendCommand:f}=St(),m=!!(d||p),h=`${t}:${s||n}`,w=It.get(h),[S,I]=a.useState(!1),[u,b]=a.useState(!1),[v,l]=a.useState((w==null?void 0:w.models)||[]),[N,A]=a.useState((w==null?void 0:w.modes)||[]),k=G=>G?typeof G=="string"?G:typeof G=="object"?G.name||G.id||JSON.stringify(G):String(G):"",[x,g]=a.useState(k(i)),[y,j]=a.useState(k(c)),[E,R]=a.useState(!1),[K,D]=a.useState(!1),V=a.useRef(0),_=G=>G.map(oe=>typeof oe=="string"?oe:(oe==null?void 0:oe.name)||(oe==null?void 0:oe.id)||String(oe));a.useEffect(()=>{if(d){const G=d.find(oe=>oe.category==="model");if(G){const oe=_(G.options.map(be=>be.value));l(oe),G.currentValue&&g(k(G.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,models:oe})}}if(p&&p.length>0){const G=_(p.map(W=>W.id));A(G);const oe=It.get(h)||{models:[],modes:[]};It.set(h,{...oe,modes:G})}else if(d){const G=d.find(oe=>oe.category!=="model");if(G){const oe=_(G.options.map(be=>be.value));A(oe),G.currentValue&&j(k(G.currentValue));const W=It.get(h)||{models:[],modes:[]};It.set(h,{...W,modes:oe})}}},[d,p,h]),a.useEffect(()=>{I(!1),b(!1),g(k(i)),j(k(c));const G=It.get(h);G?(l(G.models),A(G.modes)):(l([]),A([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>V.current&&g(k(i))},[i]),a.useEffect(()=>{c&&Date.now()>V.current&&j(k(c))},[c]);const C=a.useCallback(async(G,oe={})=>{const W={...oe,...s&&{targetSessionId:s}};return await f(t,G,W)},[t,s,f]),T=async()=>{var G,oe;if(v.length>0){I(!S);return}if(m){I(!0);return}R(!0);try{const W=await C("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.models)||((G=W==null?void 0:W.result)==null?void 0:G.models)||[],X=_(be);l(X),W!=null&&W.current&&g(k(W.current)),(oe=W==null?void 0:W.result)!=null&&oe.current&&g(k(W.result.current));const ue=It.get(h)||{models:[],modes:[]};It.set(h,{...ue,models:X}),I(!0)}catch{}finally{R(!1)}},z=async()=>{var G,oe;if(N.length>0){b(!u);return}if(m){b(!0);return}D(!0);try{const W=await C("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),be=(W==null?void 0:W.modes)||((G=W==null?void 0:W.result)==null?void 0:G.modes)||[],X=_(be);A(X),W!=null&&W.current&&j(k(W.current)),(oe=W==null?void 0:W.result)!=null&&oe.current&&j(k(W.result.current));const ue=It.get(h)||{models:[],modes:[]};It.set(h,{...ue,modes:X}),b(!0)}catch{}finally{D(!1)}},L=async G=>{I(!1);const oe=x;g(G),V.current=Date.now()+5e3;try{const W=m?await C("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:G}):await C("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:G});if((W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change model")}catch(W){console.warn("Model change failed",W),g(oe),V.current=0}},$=m&&!(p&&p.length>0)&&(d==null?void 0:d.some(G=>G.category!=="model")),H=$?(je=d==null?void 0:d.find(G=>G.category!=="model"))==null?void 0:je.configId:void 0,se=async G=>{b(!1);const oe=y;j(G),V.current=Date.now()+5e3;try{let W;if(m&&$&&H?W=await C("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:H,value:G}):m?W=await C("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:G}):W=await C("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:G}),(W==null?void 0:W.success)===!1)throw new Error((W==null?void 0:W.error)||"Could not change mode")}catch(W){console.warn("Mode change failed",W),j(oe),V.current=0}},ie={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"}[n]||"#94a3b8";return e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-[var(--surface-primary)]",children:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:ie},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),e.jsxs("div",{className:"relative",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:S?`${ie}55`:"transparent",border:"1px solid",color:x?"var(--text-primary)":"var(--text-muted)"},onClick:T,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),E?"...":x||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),S&&v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(!1)}),e.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:"SELECT MODEL"}),v.map(G=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:G===x?`${ie}18`:"transparent",color:G===x?ie:"var(--text-secondary)",fontWeight:G===x?600:400,borderLeft:G===x?`2px solid ${ie}`:"2px solid transparent"},onMouseEnter:oe=>{oe.currentTarget.style.background=`${ie}12`},onMouseLeave:oe=>{oe.currentTarget.style.background=G===x?`${ie}18`:"transparent"},onClick:()=>L(G),children:G},G))]})]})]}),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:u?`${ie}55`:"transparent",border:"1px solid",color:y?"var(--text-primary)":"var(--text-muted)"},onClick:z,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:$?"🧠":"⚡"}),K?"...":y||($?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),u&&N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>b(!1)}),e.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[e.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:$?"SELECT THINKING LEVEL":"SELECT MODE"}),N.map(G=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:G===y?`${ie}18`:"transparent",color:G===y?ie:"var(--text-secondary)",fontWeight:G===y?600:400,borderLeft:G===y?`2px solid ${ie}`:"2px solid transparent"},onMouseEnter:oe=>{oe.currentTarget.style.background=`${ie}12`},onMouseLeave:oe=>{oe.currentTarget.style.background=G===y?`${ie}18`:"transparent"},onClick:()=>se(G),children:G},G))]})]})]})]})}const sa=new Map,Oc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Hc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m}){const{sendCommand:h}=St(),w=`${t}:${s||n}`,S=Oc[n]||"#94a3b8",[I,u]=a.useState({}),b=a.useRef(0),v={};for(const T of i||[])T.defaultValue!==void 0&&(v[T.id]=T.defaultValue);const l={...v,...d?{model:d}:{},...p?{mode:p}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&u({})},[c]);const[N,A]=a.useState(sa.get(w)||{}),[k,x]=a.useState(null),[g,y]=a.useState(null),j=a.useCallback(async(T,z={})=>{const L={...z,...s&&{targetSessionId:s}};return await h(t,T,L)},[t,s,h]),E=a.useCallback(async(T,z={},L)=>{const $=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const H=await j("invoke_provider_script",{...$,scriptName:T,...z});return(H==null?void 0:H.success)===!1&&L?await j(L,{...$,...z}):H}catch(H){if(!L)throw H;return await j(L,{...$,...z})}},[j,n,r]);if(!i||i.length===0)return e.jsx(ta,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m});const R=i.filter(T=>T.placement==="bar").sort((T,z)=>(T.order??50)-(z.order??50));if(R.length===0)return e.jsx(ta,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:p,acpConfigOptions:f,acpModes:m});const K=async T=>{var L,$,H;if(k===T.id){x(null);return}if((((L=T.options)==null?void 0:L.map(se=>se.value))||N[T.id]||[]).length>0){x(T.id);return}if(T.dynamic&&T.listScript){y(T.id);try{const se=Vs(T.listScript),Y=await E(T.listScript,{},se),je=((Y==null?void 0:Y.models)||(Y==null?void 0:Y.modes)||(($=Y==null?void 0:Y.result)==null?void 0:$.models)||((H=Y==null?void 0:Y.result)==null?void 0:H.modes)||(Y==null?void 0:Y.options)||[]).map(G=>typeof G=="string"?G:(G==null?void 0:G.name)||(G==null?void 0:G.id)||(G==null?void 0:G.value)||String(G));A(G=>{const oe={...G,[T.id]:je};return sa.set(w,oe),oe}),x(T.id)}catch{}finally{y(null)}}},D=async(T,z)=>{x(null),u(L=>({...L,[T.id]:z})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{model:T.id==="model"?z:void 0,mode:T.id==="mode"?z:void 0,value:z},Vs(T.setScript))}catch{}},V=async T=>{var Y;const z=((Y=T.options)==null?void 0:Y.map(ie=>ie.value))||N[T.id]||[];if(z.length===0)return;const L=String(l[T.id]||""),H=(z.indexOf(L)+1)%z.length,se=z[H];if(typeof se=="string"){u(ie=>({...ie,[T.id]:se})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{value:se},Vs(T.setScript))}catch{}}},_=async T=>{const L=!l[T.id];u($=>({...$,[T.id]:L})),b.current=Date.now()+5e3;try{if(!T.setScript)return;await E(T.setScript,{value:L},Vs(T.setScript))}catch{}},C=async T=>{if(T.invokeScript){if(T.confirmMessage){const z=[T.confirmTitle,T.confirmMessage,T.confirmLabel].filter($=>typeof $=="string"&&$.trim().length>0);if(!window.confirm(z.join(`
|
|
29
|
-
|
|
30
|
-
`)))return}try{await E(T.invokeScript)}catch{}}};return e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[e.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:S},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),R.map(T=>{var se;const z=String(l[T.id]||""),L=k===T.id,$=g===T.id,H=((se=T.options)==null?void 0:se.map(Y=>Y.value))||N[T.id]||[];switch(T.type){case"select":return e.jsxs("div",{className:"relative",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:L?`${S}55`:"transparent",border:"1px solid",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),$?"...":z||T.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),L&&H.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>x(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:T.label.toUpperCase()}),H.map(Y=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:Y===z?`${S}18`:"transparent",color:Y===z?S:"var(--text-secondary)",fontWeight:Y===z?600:400,borderLeft:Y===z?`2px solid ${S}`:"2px solid transparent"},onMouseEnter:ie=>{ie.currentTarget.style.background=`${S}12`},onMouseLeave:ie=>{ie.currentTarget.style.background=Y===z?`${S}18`:"transparent"},onClick:()=>D(T,Y),children:Y},Y))]})]})]},T.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:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>V(T),title:`Click to cycle: ${H.join(" → ")}`,children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),z||T.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},T.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:z?`${S}44`:"transparent",background:z?`${S}14`:"var(--surface-tertiary)",color:z?S:"var(--text-muted)"},onClick:()=>_(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),T.label]},T.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:()=>C(T),children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),T.resultDisplay==="inline"&&z?`${T.label}: ${z}`:T.label]},T.id);case"display":return e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:T.icon}),z?`${T.label}: ${z}`:T.label]},T.id);default:return null}})]})}function Vs(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const Uc=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,p]=a.useState("");a.useEffect(()=>{p("")},[s]),a.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const f=()=>{const m=d.trim();!m||n||(p(""),o(m))};return e.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:e.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:d,onChange:m=>p(m.target.value),onPaste:m=>{const h=m.clipboardData.getData("text");h&&p(w=>w+h),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),f()}},onBlur:m=>{if(window.innerWidth<768){const h=m.relatedTarget;if((h==null?void 0:h.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),e.jsx("button",{onClick:f,disabled:!d.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var zc=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Fc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function xt(t,s){if(Fc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":zc.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function mo(t){return xt(t)==="generating"}function Ze(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function Vc(t){if(t<60)return`${Math.round(t)}s`;const s=Math.floor(t/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const o=Math.floor(r/24),i=r%24;return`${o}d ${i}h`}function Rr(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function kr(t,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof t=="string"?t.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function Gc(t){if(t.length>16&&/^[a-f0-9]+$/i.test(t))return`Machine-${t.substring(0,8)}`;if(t.includes("_")){const s=t.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return t}function qc(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Yc(t){return Gc(t.trim().replace(/\.local$/i,""))}function Xc(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function fo(t,s={}){var o,i;const r=[t.hostname,(o=t.machine)==null?void 0:o.hostname,(i=t.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!qc(c));if(r&&r!=="Unknown")return Yc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function kt(t,s={}){return Xc(t)||fo(t,s)}function $s(t){return t.transport==="pty"}function ms(t){return t.transport==="acp"}function ra(t,s){return Ze(t)}function na(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Ze(r||"").trim().toLowerCase();return n===o||n===i||n===c}function Jc(t){return xt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Zc(t){if(!Array.isArray(t)||t.length<=1)return t;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of t){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=xt(n.status);if(!i){s.set(o,{...n,status:c});continue}const d=r.indexOf(i.status||"idle"),p=r.indexOf(c||"idle");p>=0&&(d<0||p<d)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Qc(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 el(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Qc(s.receivedAt)||0}function tl(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function rn(t){return Math.max(tl(t),el(t.activeChat))}function sl(t,s,r,n,o,i){const c=s-t;if(c!==0)return c;const d=r.localeCompare(n);return d!==0?d:o.localeCompare(i)}function wn(t,s){return sl(rn(t),rn(s),kt(t,{fallbackId:t.id}),kt(s,{fallbackId:s.id}),t.id,s.id)}const Xe=t=>t.transport==="pty",hs=(t,s)=>Xe(t)?t.mode||"terminal":"chat",xo=(t,s)=>Xe(t)&&hs(t)==="terminal",Ve=t=>t.transport==="acp";function Bt(t){return t.streamSource!=="agent-stream"}function zt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function ho(t){return t.machineName||""}function mr(t){return zt(t)}function jt(t){return t.agentType||""}function jn(t){return t.hostIdeType||""}function Nr(t){return t.displayPrimary||t.agentName||"Agent"}function kn(t){return[t.displaySecondary,ho(t)].filter(Boolean)}function Os(t){return t.agentName||Ze(jt(t))}function rl(t){var s,r;if(!Bt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Ze(jn(t)||jt(t))}function Nn(t){return Bt(t)?t.sessionId:t.nativeSessionId}function aa(t){return Bt(t)?"native":t.tabKey}function nl(t){return t.sessionId}function al(t,s){if(s)return Bt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function ol(t,s){const r=jt(t),n=Bt(t)?s!=null&&s.type?Ze(s.type):Ze(jn(t)||r):Os(t);return{isNativeConversation:Bt(t),isCli:Xe(t),isAcp:Ve(t),isCliTerminal:xo(t),providerType:r,displayLabel:n,targetEntry:al(t,s)}}function bo({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=bs(),c=zt(t),d=ho(t),p=t.transport==="cdp-page"||t.transport==="cdp-webview",f=t.streamSource==="agent-stream"&&!!t.agentName,m=!f&&(t.transport==="pty"||t.transport==="acp"),h=Os(t),w=rl(t),S=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const u=Nn(t);u&&i(`/dashboard?activeTab=${encodeURIComponent(u)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[p&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:w,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:w})]}):e.jsxs("span",{className:"conversation-meta-chip",title:w,children:[e.jsx(Nt,{size:12}),e.jsx("span",{children:w})]})),f&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Rs,{size:12}),e.jsx("span",{children:h})]}),m&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Rs,{size:12}),e.jsx("span",{children:h})]}),d&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:d,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:d})]}):e.jsxs("span",{className:"conversation-meta-chip",title:d,children:[e.jsx(Ut,{size:12}),e.jsx("span",{children:d})]}))]})}function oa(t,s){return`${t}:${s}`}function il(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Gs(t,s){il()&&console.debug(`[subscription-manager] ${t}`,s)}class cl{constructor(){nt(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=oa(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const m={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,m),Gs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const p=()=>{var w;const m=this.active.get(i);if(!m||(m.handlers.delete(o),m.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};Gs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,h)};return p.initialSendAccepted=d,p}publish(s){const r=oa(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Qt.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),Qt.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;Gs("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var o;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);Gs("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(o=r.sendData)==null||o.call(r,i.daemonId,i.request)}}const Ot=new cl;function ll(t,s){const r=new Map;for(const n of t||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,currentModel:n.currentModel,currentPlan:n.currentPlan,currentAutoApprove:n.currentAutoApprove,controlValues:n.controlValues,providerControls:n.providerControls,acpConfigOptions:n.acpConfigOptions,acpModes:n.acpModes,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function qs(t,s){return{...t,parentId:t.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:t.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??t.providerType,workspace:t.workspace??(s==null?void 0:s.workspace)??null,capabilities:t.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:t.cdpConnected??(s==null?void 0:s.cdpConnected),currentModel:t.currentModel??(s==null?void 0:s.currentModel),currentPlan:t.currentPlan??(s==null?void 0:s.currentPlan),currentAutoApprove:t.currentAutoApprove??(s==null?void 0:s.currentAutoApprove),controlValues:t.controlValues??(s==null?void 0:s.controlValues),providerControls:t.providerControls??(s==null?void 0:s.providerControls),acpConfigOptions:t.acpConfigOptions??(s==null?void 0:s.acpConfigOptions),acpModes:t.acpModes??(s==null?void 0:s.acpModes),runtimeWriteOwner:t.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:t.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:t.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:t.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:t.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:t.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function dl(t){const s=[],r=new Map;for(const n of t)if(n.parentId){const o=r.get(n.parentId)||[];o.push(n),r.set(n.parentId,o)}else s.push(n);return{topLevel:s,childrenByParent:r}}function fr(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||t.timestamp||Date.now(),p=t.sessions||[],{topLevel:f,childrenByParent:m}=dl(p),h=ll(i,n),w=t.machine?{...(o==null?void 0:o.machine)||{},...t.machine}:o==null?void 0:o.machine,S=f.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),I=f.filter(b=>b.kind==="agent"&&b.transport==="pty"),u=f.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:d,...t.version&&{version:t.version},...w&&{machine:w,platform:w.platform},...t.instanceId&&{instanceId:t.instanceId},...t.machineNickname!==void 0&&{machineNickname:t.machineNickname},...t.p2p&&{p2p:t.p2p},...t.workspaces&&{workspaces:t.workspaces},...t.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:t.defaultWorkspaceId},...t.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:t.defaultWorkspacePath},...t.terminalSizingMode!==void 0&&{terminalSizingMode:t.terminalSizingMode},...t.recentLaunches&&{recentLaunches:t.recentLaunches},...t.terminalBackend&&{terminalBackend:t.terminalBackend},...t.detectedIdes&&{detectedIdes:t.detectedIdes},...t.availableProviders&&{availableProviders:t.availableProviders},cdpConnected:S.some(b=>!!b.cdpConnected)});for(const b of S){const v=h.get(b.id),l=qs(b,v),N=(m.get(b.id)||[]).map(A=>qs(A,h.get(A.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,status:l.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:l.workspace,terminals:0,childSessions:N,agents:N.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:l.activeChat,chats:[],cdpConnected:l.cdpConnected,...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.currentAutoApprove!==void 0&&{currentAutoApprove:l.currentAutoApprove},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d})}for(const b of I){const v=h.get(b.id),l=qs(b,v);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:b.id,cliName:l.providerName||l.providerType,mode:l.mode||(v==null?void 0:v.mode)||"terminal",workspace:l.workspace||"",activeChat:l.activeChat,...l.resume!==void 0&&{resume:l.resume},...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isCli:!0})}for(const b of u){const v=h.get(b.id),l=qs(b,v);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:l.parentId,sessionKind:l.kind,transport:l.transport,sessionCapabilities:l.capabilities,type:l.providerType,agentType:l.providerType,status:l.status||"running",daemonId:n,instanceId:b.id,cliName:l.providerName||l.providerType,mode:"chat",workspace:l.workspace||"",activeChat:l.activeChat,...l.runtimeKey!==void 0&&{runtimeKey:l.runtimeKey},...l.runtimeDisplayName!==void 0&&{runtimeDisplayName:l.runtimeDisplayName},...l.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:l.runtimeWorkspaceLabel},...l.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:l.runtimeWriteOwner},...l.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:l.runtimeAttachedClients},...l.currentModel!==void 0&&{currentModel:l.currentModel},...l.currentPlan!==void 0&&{currentPlan:l.currentPlan},...l.lastMessagePreview!==void 0&&{lastMessagePreview:l.lastMessagePreview},...l.lastMessageRole!==void 0&&{lastMessageRole:l.lastMessageRole},...l.lastMessageAt!==void 0&&{lastMessageAt:l.lastMessageAt},...l.lastMessageHash!==void 0&&{lastMessageHash:l.lastMessageHash},lastUpdated:l.lastUpdated,unread:l.unread,lastSeenAt:l.lastSeenAt,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden,...l.acpConfigOptions!==void 0&&{acpConfigOptions:l.acpConfigOptions},...l.acpModes!==void 0&&{acpModes:l.acpModes},...l.controlValues!==void 0&&{controlValues:l.controlValues},...l.providerControls!==void 0&&{providerControls:l.providerControls},timestamp:d,_isAcp:!0})}return r}const Dr=new Map,Er=new Map,$r=new Set,Is=new Map,ul=1200;function pl(t){if(!t||typeof t!="object")return null;const s=t,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const o=n.status;if(o&&typeof o=="object")return o}return s}function ia(t,s){const r=Is.get(t);!r||r.size===0||(Is.delete(t),r.forEach(n=>n(s)))}function ml(t,s){return new Promise(r=>{const n=Is.get(t)||new Set;Is.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Is.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function Hs(){const{sendCommand:t,sendData:s}=St(),{injectEntries:r,getIdes:n}=pr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=Er.get(o)||0;if(!(i!=null&&i.force)&&$r.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const p=Dr.get(o);if(p)return p;const f=(async()=>{if(s&&!$r.has(o)&&($r.add(o),Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},u=>{const b=n(),v=b.find(N=>N.id===o),l=fr(u.status,{daemonId:o,existingDaemon:v,existingEntries:b,timestamp:u.timestamp});l.length>0&&r(l),Er.set(o,Date.now()),ia(o,!0)}),!(i!=null&&i.force)&&await ml(o,ul)))return;const m=await t(o,"get_status_metadata"),h=pl(m);if(!h)return;const w=n(),S=w.find(u=>u.id===o),I=fr(h,{daemonId:o,existingDaemon:S,existingEntries:w,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),Er.set(o,Date.now()),ia(o,!0)})().finally(()=>{Dr.delete(o)});return Dr.set(o,f),f},[n,r,t,s])}function rs(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function go(t,s){if(!t||!s)return!1;if(t===s||t.id&&s.id&&String(t.id)===String(s.id)||t._localId&&s._localId&&String(t._localId)===String(s._localId))return!0;const r=String(t.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=ss(t.content),i=ss(s.content);if(!o||o!==i)return!1;const c=rs(t),d=rs(s);return c&&d?Math.abs(c-d)<=15e3:!!t._localId!=!!s._localId}function ca(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),rs(t)&&(s+=1),s}function fl(t,s){const r=ca(t),n=ca(s);return n!==r?n>r?s:t:ss(s.content).length>=ss(t.content).length?s:t}function As(t){const s=[];for(const r of t){const n=s.findIndex(o=>go(o,r));if(n>=0){s.splice(n,1,fl(s[n],r));continue}s.push(r)}return s}function la(t){return[...t].sort((s,r)=>{const n=rs(s),o=rs(r);return n&&o&&n!==o?n-o:0})}function da(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${ss(t==null?void 0:t.content).slice(0,100)}`}function ua(t,s){const r=t.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>go(i,n));return o>=0?(r.splice(o,1),!1):!0})}function xl(t,s){const r=new Set(s.map(n=>da(n)));return t.filter(n=>!r.has(da(n)))}const hl=60,bl=200;function gl(t={}){return t.isCliLike?bl:hl}function yl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function vl(t){let s=2166136261;for(const r of t){const n=String(r||"");for(let o=0;o<n.length;o+=1)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function pa(t,s){const r=t[t.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",t.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function yo(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return vl([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function wl(t){return{knownMessageCount:t.length,lastMessageSignature:yo(t[t.length-1])}}function jl(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return As([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return As([...t.slice(0,n),...r])}case"full":default:return r}}const ma=60;function nn({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:p=!1,scrollToBottomRequestNonce:f,isInputActive:m=!0}){var W,be,X,ue;const h=a.useRef(new Map),w=a.useRef(new Map),S=a.useRef(new Map),{sendCommand:I,sendData:u}=St(),b=Hs();Ks("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const v=et.useMemo(()=>ys(t),[t.status,t.connectionState]),l=a.useMemo(()=>ol(t,s),[t,s]),N=gl({isCliLike:l.isCli||l.isAcp}),A=a.useRef(new Map),k=a.useCallback(te=>(A.current.has(te)||A.current.set(te,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:N}),A.current.get(te)),[N]),x=a.useCallback((te,ae)=>{const fe=k(te);A.current.set(te,{...fe,...ae}),g(le=>le+1)},[k]),[,g]=a.useState(0),y=t.tabKey,j=k(y),E=j.messages,R=j.hasMore,K=j.error,D=w.current.get(y),V=t.messages.filter(te=>!!(te!=null&&te._localId)),_=D?As([...D,...V]):t.messages;a.useEffect(()=>{j.visibleLiveCount>=N||x(y,{visibleLiveCount:N})},[N,j.visibleLiveCount,y,x]);const C=Math.max(0,_.length-j.visibleLiveCount),T=Nr(t),z=mr(t),L=t.sessionId||"",$=t.providerSessionId||L,[H,se]=a.useState(!1);a.useEffect(()=>{const te=l.targetEntry;z&&(!te||te.providerControls===void 0||te.controlValues===void 0||l.isAcp&&(te.acpConfigOptions===void 0||te.acpModes===void 0))&&b(z,{minFreshMs:3e4}).catch(()=>{})},[z,l.isAcp,(W=l.targetEntry)==null?void 0:W.providerControls,(be=l.targetEntry)==null?void 0:be.controlValues,(X=l.targetEntry)==null?void 0:X.acpConfigOptions,(ue=l.targetEntry)==null?void 0:ue.acpModes,b]),a.useEffect(()=>{if(!z||!L||!u)return;const te=w.current.get(y)||[],ae=S.current.get(y),fe=ae&&ae.knownMessageCount?ae:wl(te),le=`daemon:${z}:session:${L}`;return Ot.subscribe({sendData:u},z,{type:"subscribe",topic:"session.chat_tail",key:le,params:{targetSessionId:L,historySessionId:$,knownMessageCount:fe.knownMessageCount,lastMessageSignature:fe.lastMessageSignature,...fe.knownMessageCount?{}:{tailLimit:ma}}},J=>{const pe=w.current.get(y)||[],ne=jl(pe,J),we=Math.max(ne.length,Number(J.totalMessages||0));S.current.set(y,{knownMessageCount:we,lastMessageSignature:typeof J.lastMessageSignature=="string"?J.lastMessageSignature:yo(ne[ne.length-1])}),pa(pe)!==pa(ne)&&(w.current.set(y,ne),Qt.record({interactionId:J.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:L,syncMode:J.syncMode,previousCount:pe.length,nextCount:ne.length}}),g(P=>P+1))})},[z,$,u,L,y]);const Y=a.useCallback(async()=>{if(H)return;const te=t.tabKey,ae=k(te);if(_.length>ae.visibleLiveCount){x(te,{visibleLiveCount:Math.min(_.length,ae.visibleLiveCount+ma),error:null});return}se(!0),x(te,{error:null});try{const fe=mr(t);if(!fe){x(te,{hasMore:!1});return}const le=jt(t),he=await I(fe,"chat_history",{agentType:le,offset:ae.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),J=yl(he),pe=J.messages||[];if(pe.length>0){const ne=k(te);x(te,{messages:[...pe,...ne.messages],offset:ne.offset+pe.length,hasMore:!!J.hasMore})}else x(te,{hasMore:!!J.hasMore})}catch(fe){const le=(fe==null?void 0:fe.message)||"";le.includes("P2P not available")||le.includes("channel not open")||le.includes("P2P not connected")||le.includes("timeout")?x(te,{error:"Connection not ready — tap to retry"}):x(te,{hasMore:!1,error:"Failed to load history"})}finally{se(!1)}},[H,t,_.length,I,k,x]),{allMessages:ie,receivedAtMap:je}=a.useMemo(()=>{const te=C>0?_.slice(-j.visibleLiveCount):_;if(E.length===0){const he=la(As(te)),J={};return he.forEach((pe,ne)=>{const we=`${t.tabKey}:${ps(pe,ne)}`;let ge=rs(pe)||h.current.get(we)||0;ge||(ge=Date.now(),h.current.set(we,ge)),J[ps(pe,ne)]=ge}),{allMessages:he,receivedAtMap:J}}const ae=xl(E,te),fe=la(As([...ae,...te])),le={};return fe.forEach((he,J)=>{const pe=`${t.tabKey}:${ps(he,J)}`;let ne=rs(he)||h.current.get(pe)||0;ne||(ne=Date.now(),h.current.set(pe,ne)),le[ps(he,J)]=ne}),{allMessages:fe,receivedAtMap:le}},[t.tabKey,C,E,_,j.visibleLiveCount]),G=a.useMemo(()=>c.filter(te=>te.routeId===t.tabKey).sort((te,ae)=>te.timestamp-ae.timestamp),[c,t.tabKey]),oe=a.useMemo(()=>{if(_.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((v.isGenerating||t.status==="streaming")&&se(!1),t.status==="not_monitored")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(Rs,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xs,{size:14})," Open ",T," 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(ro,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xs,{size:14})," Open ",T," 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"&&!H)return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),e.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[t.connectionState,t.status,o,i,H,_.length,T,v.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&e.jsx(bo,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(Mc,{messages:ie,actionLogs:G,agentName:Os(t)||T||"Agent",userName:d,isCliMode:l.isCli||l.isAcp,isWorking:v.isGenerating,contextKey:t.tabKey,receivedAtMap:je,onLoadMore:Y,isLoadingMore:H,hasMoreHistory:R,hiddenLiveCount:C,loadError:K??void 0,emptyState:oe,scrollToBottomRequestNonce:f}),m&&!l.isCliTerminal&&(()=>{var te,ae,fe,le,he,J;return e.jsx(Hc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:l.providerType,displayLabel:l.displayLabel,controls:(te=l.targetEntry)==null?void 0:te.providerControls,controlValues:(ae=l.targetEntry)==null?void 0:ae.controlValues,serverModel:((fe=l.targetEntry)==null?void 0:fe.currentModel)||void 0,serverMode:((le=l.targetEntry)==null?void 0:le.currentPlan)||void 0,acpConfigOptions:l.isAcp?(he=l.targetEntry)==null?void 0:he.acpConfigOptions:void 0,acpModes:l.isAcp?(J=l.targetEntry)==null?void 0:J.acpModes:void 0})})(),!l.isCliTerminal&&e.jsx(Uc,{contextKey:t.tabKey,panelLabel:T,isSending:n,onSend:r,isActive:m})]})}let vo=es;function wo(){return vo()}class kl{constructor(){nt(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let jo=new kl;class Nl{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let tt=new Nl;function Sl(t){t.dashboardWS&&(jo=t.dashboardWS),t.connectionManager&&(tt=t.connectionManager),t.useDaemonsHook&&(vo=t.useDaemonsHook)}function Qe(t){return Nr(t)}function ns(t){return kn(t).join(" · ")}function ko(t){if(t.lastMessagePreview)return t.lastMessagePreview;const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=ss(s==null?void 0:s.content);return r||(t.title?t.title:ns(t)||"No messages yet")}function No(t,s){const{isReconnecting:r,isConnecting:n}=ys(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Cl(t,s){const r=["Chat",...kn(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function Yt(t){return No(t)||ns(t)}function Il(t){return`${Qe(t)} · ${ko(t)}`}function Al(t){const s=jn(t)||jt(t);return`${Qe(t)} — ${Ze(s)}`}function Ml(t){return Os(t)||"CLI"}function So(t){return t.title||Os(t)||t.routeId}function Co(t){return t?`Remote · ${Qe(t)||t.workspaceName||"Session"}`:"Remote"}function Tl({activeConv:t,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var $;const{ides:c}=es(),d=a.useRef(null),{sendCommand:p,sendData:f}=St(),[m,h]=a.useState(""),[w,S]=a.useState(!1),[I,u]=a.useState(1),b=a.useRef(!1),v=a.useRef(0),l=a.useRef(!1),N=a.useRef(""),A=a.useRef(null),k=a.useRef(!1),x=a.useRef(null),g=t.tabKey,y=t.sessionId||"",j=t.daemonId||(($=t.routeId)==null?void 0:$.split(":")[0])||t.routeId||"",E=c.find(H=>H.id===j&&H.type==="adhdev-daemon"),R=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",K=.6,D=1.15,V=()=>{if(typeof window>"u")return 1;const H=window.innerWidth||0;return H<=360?.68:H<=390?.74:H<=430?.82:H<=480?.9:1},_=()=>{var H,se;v.current=0,l.current=!1,N.current="",A.current=null,k.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),S(!1),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},C=()=>{var H,se;v.current=0,l.current=!1,N.current="",A.current=null,k.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),S(!0),(se=(H=r.current)==null?void 0:H.reset)==null||se.call(H)},T=()=>{var se;if(x.current=null,!i)return;const H=N.current;H&&(N.current="",(se=r.current)==null||se.write(H))},z=H=>{H&&(N.current+=H,i&&x.current===null&&(x.current=requestAnimationFrame(T)))},L=(H,se=0,Y,ie)=>{var je,G,oe,W,be;se>0&&v.current>=se||se===0&&l.current||(v.current=se,S(!0),typeof Y=="number"&&typeof ie=="number"&&Y>0&&ie>0&&((G=(je=r.current)==null?void 0:je.resize)==null||G.call(je,Y,ie)),(W=(oe=r.current)==null?void 0:oe.reset)==null||W.call(oe),H&&((be=r.current)==null||be.write(H)))};return a.useEffect(()=>{_()},[y]),a.useEffect(()=>{var se;if(!y)return;const H=((se=tt.onRuntimeEvent)==null?void 0:se.call(tt,y,Y=>{if(!(!Y||Y.sessionId!==y)){if(Y.type==="runtime_snapshot"){if(!i){A.current={text:Y.text||"",seq:Y.seq||0,cols:Y.cols,rows:Y.rows};return}L(Y.text||"",Y.seq||0,Y.cols,Y.rows);return}if(Y.type==="session_output"){l.current=!0,typeof Y.seq=="number"&&(v.current=Math.max(v.current,Y.seq)),w||S(!0),typeof Y.data=="string"&&z(Y.data);return}if(Y.type==="session_cleared"){if(!i){k.current=!0,N.current="",A.current=null;return}C()}}}))||(()=>{});return()=>{H()}},[j,y,r,i,w]),a.useEffect(()=>{var se,Y,ie;if(!y)return;j&&((se=tt.getState)==null?void 0:se.call(tt,j))==="connected"&&(S(!0),(Y=tt.requestRuntimeSnapshot)==null||Y.call(tt,j,y).catch(()=>{}));const H=(ie=tt.onStateChange)==null?void 0:ie.call(tt,(je,G)=>{var oe;je!==j||G!=="connected"||(S(!0),(oe=tt.requestRuntimeSnapshot)==null||oe.call(tt,j,y).catch(()=>{}))});return()=>{H==null||H()}},[j,y,r]),a.useEffect(()=>{s&&_()},[s,g,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const H=()=>{b.current||u(V())};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[]),a.useEffect(()=>{var se;if(!i){(se=d.current)==null||se.blur();return}k.current&&(k.current=!1,C());const H=A.current;H&&(A.current=null,L(H.text,H.seq,H.cols,H.rows)),N.current&&x.current===null&&(x.current=requestAnimationFrame(T)),requestAnimationFrame(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})},[i]),a.useEffect(()=>()=>{x.current!==null&&(cancelAnimationFrame(x.current),x.current=null)},[]),a.useEffect(()=>{const H=se=>{var ie;const Y=se.detail;Y!=null&&Y.sessionId&&Y.sessionId!==y||w&&((ie=r.current)==null||ie.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",H),()=>{window.removeEventListener("adhdev:fit-cli-terminal",H)}},[w,y,r]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[e.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[e.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,u(H=>Math.max(K,Number((H-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),e.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,u(H=>Math.min(D,Number((H+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),e.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:e.jsx("div",{style:{width:`${100/I}%`,height:`${100/I}%`,transform:`scale(${I})`,transformOrigin:"top left"},children:e.jsx(co,{ref:r,readOnly:!w||!i,sizingMode:R,onInput:H=>{w&&(f!=null&&f(j,{type:"pty_input",targetSessionId:y,data:H})||p(j,"pty_input",{targetSessionId:y,data:H}).catch(console.error))}})})}),!w&&e.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),e.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:e.jsxs("div",{className:"flex gap-2.5 items-center",children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${Qe(t)}...`,value:m,disabled:!w||!i||o,onChange:H=>h(H.target.value),onPaste:H=>{const se=H.clipboardData.getData("text");se&&h(Y=>Y+se),H.preventDefault()},onKeyDown:H=>{if(H.key!=="Enter")return;if(H.nativeEvent.isComposing){H.preventDefault();return}H.preventDefault();const se=m.trim();!w||!se||o||(h(""),n(se))},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 H=m.trim();!w||!H||o||(h(""),n(H))},disabled:!w||!i||!m.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function _l({wsStatus:t,showReconnected:s,loginUrl:r}){const n=t==="disconnected"||t==="reconnecting"||t==="offline"||t==="auth_failed",o=t==="auth_failed"?"red":t==="offline"?"orange":"accent",i={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},d={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return e.jsxs(e.Fragment,{children:[n&&e.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[o],borderBottom:c[o],color:d[o]},children:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:t==="auth_failed"?.6:1,animation:t==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:t==="auth_failed"?"grayscale(1)":void 0}}),t==="offline"&&"Network offline — waiting for connection...",t==="disconnected"&&"Reconnecting to server...",t==="reconnecting"&&"Reconnecting to server...",t==="auth_failed"&&(r?e.jsxs(e.Fragment,{children:["Session expired."," ",e.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&t==="connected"&&e.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[e.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function Pl({terminalBackend:t,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!t?null:`adhdev:terminal-backend-banner:dismissed:${n}:${t.backend}`,[n,t]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!t||t.backend!=="xterm"||i)return null;const d=(r==null?void 0:r.trim())||"This machine",p=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return e.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[e.jsxs("span",{children:[d," is using `xterm` fallback."]}),e.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),e.jsx("button",{type:"button",onClick:p,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Sn({mode:t,onChange:s,compact:r=!1}){const n=r?14:15;return e.jsx("button",{type:"button",onClick:()=>s(t==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:t==="chat"?"Switch to Terminal view":"Switch to Chat view",children:t==="chat"?e.jsx(wr,{size:n}):e.jsx(Kt,{size:n})})}function Ll(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Ht(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return t.lastMessageAt||Ll(s==null?void 0:s.receivedAt)||0}function an(t,s=0){return Ht(t)||t.lastUpdated||s||0}function Io(t){return Ht(t)||t.lastUpdated||0}function xr(t,s,r=Io){const n=r(s)-r(t);if(n!==0)return n;const o=(t.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=t.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=t.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:t.tabKey.localeCompare(s.tabKey)}function on(t){var r;const s=xt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Rl(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!on(t)&&!t.title.trim()}function Dl(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(on(r))-Number(on(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:xr(s,r)})[0]||null}function Dt(t,s){const r=t.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,o=r.filter(c=>c.streamSource==="agent-stream"),i=Dl(o);return n?i&&Rl(n)?i:n:i||r[0]||null}function fa({value:t}){return t?e.jsx("span",{className:"dashboard-header-shortcut-pill",children:t}):null}function xa({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=kn(t),i=vn(Ht(t)),c=[...o,i].filter(Boolean);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Nr(t)}),(r||c.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function El({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:p,onSetCliViewMode:f,onOpenConversation:m,onHideConversation:h,hiddenConversations:w=[],onShowConversation:S,onShowAllHidden:I,onResetPanelsToMain:u,inboxOpen:b,onInboxOpenChange:v,hiddenOpen:l,onHiddenOpenChange:N,onOpenNewSession:A,actionShortcuts:k}){const{ides:x,p2pStates:g={}}=es(),y=!!t&&Xe(t)&&!Ve(t),j=!!t&&Ve(t),E=p||(t?xo(t)?"terminal":"chat":null),[R,K]=a.useState(!1),D=a.useRef(null),V=a.useRef(null),_=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",C=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",T=x.filter(X=>X.type==="adhdev-daemon"),z=a.useMemo(()=>Ws(x),[x]),L=Object.values(g),$=L.filter(X=>X==="connected").length,H=L.filter(X=>X==="connecting"||X==="new"||X==="checking").length,Y=r!=="connected"||T.length===0?null:H>0&&$===0?"P2P connecting...":$>0&&s===0?"Waiting for IDE...":null,ie=a.useMemo(()=>o.filter(X=>!Wc(X,o,z)),[o,z]),je=a.useMemo(()=>ie.filter(X=>Es(X,z).requiresAction).sort(xr),[ie,z]),G=a.useMemo(()=>ie.filter(X=>{const ue=(t==null?void 0:t.tabKey)===X.tabKey;return Es(X,z,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ue}).unread}).sort(xr),[t,ie,z]),oe=a.useMemo(()=>[...je,...G].slice(0,9),[je,G]),W=je.length+G.length;a.useEffect(()=>{if(!b)return;const X=ue=>{var te;(te=D.current)!=null&&te.contains(ue.target)||v(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[b,v]),a.useEffect(()=>{if(!l)return;const X=ue=>{var te;(te=V.current)!=null&&te.contains(ue.target)||N(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[l,N]),a.useEffect(()=>{if(!l&&!b)return;const X=ue=>{if(!ue.altKey)return;const te=ue.code.match(/^Digit([1-9])$/);if(!te)return;const ae=Number(te[1])-1,fe=l?w[ae]:void 0,le=b?oe[ae]:void 0,he=fe||le;if(he){if(ue.preventDefault(),ue.stopPropagation(),fe){S==null||S(fe),N(!1);return}m==null||m(he),v(!1)}};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[w,l,b,oe,N,v,m,S]);const be=X=>{if(!X)return;const ue=o.find(te=>te.tabKey===X);ue&&(h==null||h(ue))};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(Kt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Qe(t):"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:_,boxShadow:C}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:_,boxShadow:C}}),Y&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Y]}),A&&e.jsx("button",{type:"button",onClick:A,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(lc,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(y||j||!Ve(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:ns(t)||Qe(t),children:Qe(t)}),(y||j)&&d&&e.jsxs(e.Fragment,{children:[y&&f&&E&&e.jsx(Sn,{mode:E,onChange:f,compact:!0}),e.jsx("button",{onClick:()=>d(t),className:"btn btn-secondary btn-sm",title:j?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:e.jsx(vt,{size:14})})]}),!Ve(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(bn,{size:14})}),!y&&!Ve(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(Nt,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[e.jsxs("div",{className:`dashboard-header-hidden${R?" is-drop-target":""}`,ref:V,onDragEnter:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),K(!0))},onDragOver:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),X.dataTransfer.dropEffect="move",K(!0))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||K(!1)},onDrop:X=>{const ue=X.dataTransfer.getData("text/tab-key");X.preventDefault(),K(!1),be(ue)},children:[e.jsxs("button",{type:"button",onClick:()=>N(!l),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[e.jsx(no,{size:16}),w.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:w.length})]}),l&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),e.jsx(fa,{value:k==null?void 0:k.toggleHiddenTabs})]}),e.jsxs("div",{className:"dashboard-header-hidden-actions",children:[u&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u,children:"Reset panels"}),w.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),N(!1)},children:"Restore all"})]})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx(fa,{value:k==null?void 0:k.hideCurrentTab})]}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Qe(t)})]}),w.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:w.map(X=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{S==null||S(X),N(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Qe(X)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[w.indexOf(X)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",w.indexOf(X)+1]}):null,ns(X)]})]},X.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>v(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(jr,{size:16}),W>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:W})]}),b&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),je.map(X=>e.jsx(xa,{conversation:X,isAttention:!0,shortcutIndex:oe.indexOf(X)>=0?oe.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.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(X=>e.jsx(xa,{conversation:X,shortcutIndex:oe.indexOf(X)>=0?oe.indexOf(X)+1:void 0,onClick:()=>{m==null||m(X),v(!1)}},X.tabKey))]}),W===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function $l(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 Cn({activeConv:t,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,onClose:d,onNewChat:p,onSwitchSession:f,onRefreshHistory:m,onResumeSavedSession:h}){var v;const w=s.find(l=>l.id===t.routeId),S=(w==null?void 0:w.chats)||[],I=(v=w==null?void 0:w.activeChat)==null?void 0:v.id,u=Xe(t)&&!Ve(t),b=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"card fade-in relative w-[90%] max-w-[500px] max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[20px]",children:[e.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"m-0 text-lg font-extrabold",children:u?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Al(t)})]}),e.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!u&&e.jsx("button",{onClick:p,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),u?e.jsx(e.Fragment,{children:o.map(l=>{const N=t.providerSessionId===l.providerSessionId,A=N||!l.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{A||!h||h(l)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${N?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"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 ${N?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:l.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:$l(l.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:l.preview||"No saved preview yet"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[e.jsxs("div",{className:"truncate",children:[l.workspace||"Workspace unknown",l.currentModel?` · ${l.currentModel}`:"",l.messageCount>0?` · ${l.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:N?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):S.map(l=>e.jsxs("div",{onClick:()=>{f(t.routeId,l.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${I===l.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[e.jsx("div",{className:`font-bold text-sm mb-1 ${I===l.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:l.title||"Untitled Session"}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[l.id.substring(0,12),"..."]}),I===l.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},l.id)),(u&&!i&&o.length===0||!u&&S.length===0)&&e.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[e.jsx("div",{className:"text-3xl mb-3 opacity-60",children:e.jsx(pc,{size:32})}),e.jsx("div",{className:"text-[13px]",children:u?"No saved sessions found yet.":"No recent chat sessions found."})]}),u&&i&&e.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:e.jsx("div",{className:"text-[13px]",children:"Refreshing saved sessions…"})})]}),e.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:e.jsx("button",{onClick:m,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gs,{size:13})," ",u?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Ls.createPortal(b,document.body)}const ha={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Ao({toasts:t,onDismiss:s,onClickToast:r}){return e.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:t.map(n=>{const o=ha[n.type]||ha.info;return e.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[e.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),e.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:e.jsx(vt,{size:14})}),e.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[e.jsx("div",{className:"flex items-center gap-2 pr-8",children:e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:o.label})}),e.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&e.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>e.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Bl=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function Kl(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Wl(t){return t.sessionId||t.instanceId||t.agentType}function Br(t,s){return t||s}function ba(t,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of t[o]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((o,i)=>o.timestamp-i.timestamp)}function Mo(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=kt(r,{fallbackId:r.id}));return s}function To(t,s={}){var n,o;const r=t.daemonId||((n=t.id)==null?void 0:n.split(":")[0])||t.id;return{machineName:t.daemonId&&((o=s.machineNames)==null?void 0:o[t.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function In(t,s,r={}){return Ol(t,s,To(t,r))}function Ol(t,s,r={}){var w,S,I,u,b,v;const n=[],o=r.machineName,i=r.connectionState,c=Kl(t),d=Ze(t.type),p=Array.isArray(t.childSessions)?t.childSessions.map(l=>{var N,A;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||Ze(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((N=l.activeChat)==null?void 0:N.messages)||[],activeModal:((A=l.activeChat)==null?void 0:A.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=Bl(t),m=t.activeChat||{title:""},h=m.title&&String(m.title).trim()?String(m.title).trim():"";if(f){const l=t.sessionId||t.instanceId,N=ra(t.type),A=(w=t.activeChat)==null?void 0:w.activeModal,k=A&&Array.isArray(A.buttons)&&A.buttons.length>0,x=xt((S=t.activeChat)==null?void 0:S.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||xt((b=(u=t.agents)==null?void 0:u[0])==null?void 0:b.status)||"idle",g=t.activeChat||{title:"",messages:[]};let y=g.title&&String(g.title).trim()?String(g.title).trim():"";const j=(v=t.activeChat)==null?void 0:v.id,E=t.chats;if(j&&Array.isArray(E)&&E.length>0){const C=E.find(T=>T.id===j||T.id&&String(T.id)===String(j));C!=null&&C.title&&String(C.title).trim()&&(y=String(C.title).trim())}const R=(Xe(t)||Ve(t),t.type),K=(Xe(t)||Ve(t))&&na(y,N,R)?"":y,D=g.messages||[],V=ba(s,[t.id,l]),_=ua(D,V);n.push({routeId:t.id,sessionId:l,providerSessionId:t.providerSessionId,nativeSessionId:l,transport:t.transport,daemonId:t.daemonId||void 0,mode:Xe(t)?t.mode||"terminal":"chat",agentName:N,agentType:R,status:x,title:K,messages:[...D,..._],resume:t.resume,hostIdeType:!Xe(t)&&!Ve(t)?t.type:void 0,workspaceName:c,displayPrimary:c||K||(Xe(t)?t.mode==="chat"?N:"Terminal":N),displaySecondary:d,cdpConnected:t.cdpConnected,lastMessagePreview:t.lastMessagePreview,lastMessageRole:t.lastMessageRole,lastMessageAt:t.lastMessageAt,lastMessageHash:t.lastMessageHash,lastUpdated:t.lastUpdated,modalButtons:k?A.buttons:void 0,modalMessage:k?A.message:void 0,streamSource:"native",tabKey:Br(l,t.id),machineName:o,connectionState:i})}if(f&&(Xe(t)||Ve(t)))return n;for(const l of p){const N=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,A=Jc(l),k=Wl(l),x=`${t.id}:${k}`,g=l.title&&String(l.title).trim()||"",y=na(g,l.agentName,l.agentType)?"":g,j=l.messages||[],E=ba(s,[x,l.sessionId,l.instanceId]),R=ua(j,E);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||j.length>0||R.length>0||N||y||!["idle","panel_hidden","disconnected","not_monitored"].includes(A))&&n.push({routeId:t.id,sessionId:l.sessionId||l.instanceId,providerSessionId:l.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:l.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:l.agentName,agentType:l.agentType,status:A,title:y,messages:[...j,...R],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||y||d,displaySecondary:`${d} · ${l.agentName}`,cdpConnected:t.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||t.lastUpdated,modalButtons:N?l.activeModal.buttons:void 0,modalMessage:N?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Br(l.sessionId||l.instanceId,x),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:t.id,sessionId:t.sessionId||t.instanceId,providerSessionId:t.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:t.transport,daemonId:t.daemonId||void 0,mode:"chat",agentName:ra(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:t.type,workspaceName:c,displayPrimary:c||d,displaySecondary:d,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,streamSource:"native",tabKey:Br(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function Hl(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 Ul(t,s){const r=Hl(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const _o=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Po=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Lo=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],zl=_o,Fl=Po,Vl=Lo,Ro="adhdev_notification_prefs",ga={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Gl(){try{const t=localStorage.getItem(Ro);if(t){const s=JSON.parse(t);return{...ga,...s}}}catch{}return{...ga}}function ql(t){try{localStorage.setItem(Ro,JSON.stringify(t))}catch{}}let $t=Gl(),or=[];function Yl(){or.forEach(t=>t())}function Xl(t){$t={...$t,...t},ql($t),Yl()}function Jl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return or.push(r),()=>{or=or.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{Xl(r)},[]);return[{...$t},s]}function Ms(t){if(!$t.globalEnabled)return!1;switch(t){case"disconnect":return $t.disconnectAlert;case"completion":return $t.completionAlert;case"approval":return $t.approvalAlert;case"browser":return $t.browserNotifications;default:return!0}}const Zl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ql(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Do(){return"Notification"in window&&Notification.permission==="granted"}let Vt=null;async function ed(){if(Vt!==null)return Vt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Vt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(Vt=!!await t.pushManager.getSubscription(),Vt):(Vt=!1,!1)}catch{return Vt=!1,!1}}function cn(t,s,r){if(Do())try{const n=new Notification(t,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function td(t,s={}){const r={...Zl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{ed().then(d=>{i.current=d})},[]);const c=a.useCallback((d,p,f)=>{const m=Date.now();m-o.current<r.throttleMs||(o.current=m,cn(d,p,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!Do())&&Ms("browser")&&i.current!==!0){if(document.hasFocus()){for(const p of t)n.current.set(p.id,xt(p.status,{activeModal:p.activeModal}));return}for(const p of t){const f=n.current.get(p.id),m=xt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(r.onApproval&&Ms("approval")&&m==="waiting_approval"&&f!=="waiting_approval"){const w=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,w.slice(0,120),`approval-${p.id}`)}r.onComplete&&Ms("completion")&&mo(f)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&m==="error"&&f!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,m)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const sd=/^(run|approve|accept|yes|allow|always)/,rd=/^(run|approve|accept|yes|allow|always|proceed|save)/,nd=/^(reject|deny|delete|remove|abort|cancel|no)/;function An(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function ad(t){const s=An(t).toLowerCase();return sd.test(s)?"primary":nd.test(s)?"danger":"default"}function od(t){return rd.test(An(t).toLowerCase())?"approve":"reject"}function id(t){return t.map((s,r)=>({label:An(s),variant:ad(s),action:od(s),button:s,buttonIndex:r}))}function cd(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
31
|
-
${n}`}function ld(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function dd(t,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(t,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(t,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class ud{constructor(){nt(this,"dedupMap",new Map);nt(this,"DEDUP_WINDOW_MS",5e3);nt(this,"DEDUP_MAX_SIZE",50);nt(this,"DEDUP_CLEANUP_AGE_MS",1e4);nt(this,"toastCallbacks",[]);nt(this,"systemMessageCallbacks",[]);nt(this,"clearSystemMessageCallbacks",[]);nt(this,"resolveActionFn",null);nt(this,"viewRequestRespondFn",null);nt(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const o=(n==null?void 0:n.id)||Date.now();this.emitToast({id:o,message:s,type:r,timestamp:o,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(s){if(s.daemonId){const o=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(o)return o}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const o=r.daemonId;if(o){const i=this.ides.find(c=>c.id===o&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(o=>o.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(o=>(o==null?void 0:o.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var I,u;const n=this.resolveConversationKey(s),o=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(o),d=`${i}:${s.event}:${c}`;if(this.isDuplicate(d))return;const p=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(p==null?void 0:p.type)||"";let m=Ze(f);const h=this.resolveOwningDaemon(s);if(h){const b=kt(h,{fallbackId:h.id});b&&(m=!f||f==="adhdev-daemon"?b:`${b}/${m}`)}let w="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(w=`⚡ ${m} approval needed`,S="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:cd(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(u=s.modalButtons)!=null&&u.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const v=this.resolveActionFn,l=id(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{v(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=ld(m,s.modalMessage,w),A=Date.now();this.emitToast({id:A,message:N,type:S,timestamp:A,targetKey:n||b,actions:l,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,S="warning",Ms("browser")&&!document.hasFocus()&&cn(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",v=s.requestId,l=s.orgId;if(w=`👁️ ${b} wants to view your session`,S="warning",v&&l&&this.viewRequestRespondFn){const N=Date.now(),A=dd(l,v,this.viewRequestRespondFn,(k,x)=>console.error(`[EventManager] ${k} view request failed:`,x));this.emitToast({id:N,message:w,type:S,timestamp:N,actions:A,duration:3e4}),w=""}Ms("browser")&&!document.hasFocus()&&cn("👁️ View Request",`${b} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ht=new ud;function as(...t){return Bi(Ki(t))}function pd({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:as("dashboard-header",i),children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"header-title flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center text-lg",children:t})," ",s,n&&e.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&e.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&e.jsx("div",{className:"flex gap-2",children:o})]})}function Eo({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:d}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(pd,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:as("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function Pt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:as("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",o),style:n?{borderLeftColor:n}:void 0,children:[(t||r)&&e.jsxs("div",{className:"mb-4",children:[t&&e.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&e.jsx("span",{className:"mr-1.5",children:s}),t]}),r&&e.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function $o({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:as("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[e.jsx("div",{className:"text-5xl mb-4 opacity-50",children:t}),e.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),e.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const md={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"},fd={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function xd({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:as("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",md[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:fd[t]}),e.jsx("span",{children:s})]}),r&&e.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const hd={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"},bd={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function gd({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:as("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",hd[t],r),children:[e.jsx("span",{className:as("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",bd[t])}),n]})}const ln="adhdev:themechange";function yd(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ds(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function us(t){return t==="system"?yd():t}function Bo(t){typeof document>"u"||(document.documentElement.setAttribute("data-theme",t),document.documentElement.style.colorScheme=t)}function ir(t,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ln,{detail:{preference:t,theme:s}}))}function vd(){const t=ds(),s=us(t);Bo(s),ir(t,s)}function Mn(){const[t,s]=a.useState(ds),[r,n]=a.useState(()=>us(ds()));a.useEffect(()=>{Bo(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=p=>{if(t==="system"){const f=p.matches?"light":"dark";n(f),ir("system",f)}};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]),a.useEffect(()=>{const c=p=>{const f=p.detail||{},m=f.preference,h=f.theme;s(m==="dark"||m==="light"||m==="system"?m:ds()),n(h==="dark"||h==="light"?h:us(ds()))},d=p=>{if(p.key!=="theme")return;const f=ds(),m=us(f);s(f),n(m)};return window.addEventListener(ln,c),window.addEventListener("storage",d),()=>{window.removeEventListener(ln,c),window.removeEventListener("storage",d)}},[]);const o=a.useCallback(c=>{const d=us(c);s(c),n(d);try{localStorage.setItem("theme",c)}catch{}ir(c,d)},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark",p=us(d);n(p);try{localStorage.setItem("theme",d)}catch{}return ir(d,p),d})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const ya={dark:"Dark",light:"Light",system:"System"};function wd({collapsed:t}){const{preference:s,cycleTheme:r}=Mn(),n=s==="dark"?e.jsx(fc,{size:16}):s==="light"?e.jsx(mc,{size:16}):e.jsx(xc,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ya[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:ya[s]})]})}function qt({label:t,description:s,checked:r,disabled:n,onChange:o,extra:i}){return e.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[e.jsxs("div",{className:"pr-4",children:[e.jsx("div",{className:"font-medium text-sm",children:t}),e.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,e.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>o(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[e.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),e.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function jd({onPrefChange:t}){const[s,r]=Jl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&e.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&e.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(hc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(bc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&e.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function hr(t){const s=t.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function kd(t,s){const r=hr(t),n=hr(s);if(!r||!n)return t.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function Ko(t,s){const r=t.version||null;return t.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Ts(t,s){if(t.versionUpdateRequired===!0)return!0;const r=t.version||null;if(!r||!s||r===s||kd(r,s)>=0)return!1;const n=hr(r),o=hr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function Nd(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Kr(t,s){return t instanceof Error?t.message:s}function Sd({ides:t,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=t.filter(c=>c.type==="adhdev-daemon");return i.length===0?e.jsx($o,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Run 'adhdev-standalone' to connect a local daemon instance."}):e.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>e.jsx(Id,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function va({title:t,message:s,confirmLabel:r,confirmColor:n,onConfirm:o,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Ls.createPortal(e.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick: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:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),e.jsx("button",{onClick:o,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Cd(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...zl,...Fl,...Vl].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:t}}function Id({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var V,_;const[i,c]=a.useState("idle"),[d,p]=a.useState(""),[f,m]=a.useState(null),[h,w]=a.useState("idle"),[S,I]=a.useState(""),u=t.version||null,b=((V=t.machine)==null?void 0:V.platform)||((_=t.system)==null?void 0:_.platform)||"",v=kt(t,{fallbackId:t.id}),l=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(C=>C.daemonId===t.id&&C.transport==="cdp-page"),A=s.filter(C=>C.daemonId===t.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===t.id&&C.transport==="acp"),x=t.p2p,g=async()=>{if(r){c("upgrading"),p("Starting upgrade...");try{const C=Nd(await r(t.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),p(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),p(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(C.error||"Upgrade failed"))}catch(C){c("error"),p(Kr(C,"Connection lost during upgrade"))}}},y=async()=>{if(m(null),!!n){w("loading");try{await n(t.id),w("done"),I("Machine disconnected.")}catch(C){w("error"),I(Kr(C,"Failed to disconnect"))}}},j=async()=>{if(m(null),!!o){w("loading");try{await o(t.id),w("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(C){w("error"),I(Kr(C,"Failed to revoke token"))}}},E="0.8.51",R=Ko(t,E),K=Ts(t,E),D=N.length+A.length+k.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:l}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),u&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",u,!R&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&e.jsx("button",{onClick:g,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${K?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&e.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&e.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),e.jsx(gd,{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:[x&&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 ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),e.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&e.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&D>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(C=>{const T=Cd(C.type),z=C.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:T.icon}),e.jsx("span",{children:T.name}),z!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},C.id)}),A.map(C=>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:C.cliName||"CLI"})]},C.id)),k.map(C=>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:C.cliName||"ACP"})]},C.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||S)&&e.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:S||d})]}),f==="disconnect"&&e.jsx(va,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
32
|
-
|
|
33
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
34
|
-
|
|
35
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:y,onCancel:()=>m(null)}),f==="revoke"&&e.jsx(va,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
|
|
36
|
-
|
|
37
|
-
This will:
|
|
38
|
-
• Immediately disconnect the machine
|
|
39
|
-
• Delete the machine registration
|
|
40
|
-
• Require restarting "adhdev-standalone" on that machine
|
|
41
|
-
|
|
42
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>m(null)})]})}const Ad=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Md(){const{preference:t,setPreference:s}=Mn();return e.jsx("div",{className:"flex gap-2",children:Ad.map(r=>e.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function Td(t){const s=t.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function _d(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Wr(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function wa(t){const{r:s,g:r,b:n}=_d(t);return .2126*Wr(s)+.7152*Wr(r)+.0722*Wr(n)}function ja(t,s){const r=wa(t),n=wa(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function Wo(t){const s=Td(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return ja(s,r)>=ja(s,n)?r:n}const dn={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},un={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},Pd=[{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"}}}],Oo="adhdev-chat-theme",Ho="adhdev-chat-theme-custom";function cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Oo)||"ember"}catch{return"ember"}}function Lt(t){try{const s=localStorage.getItem(Ho);if(s){const r=JSON.parse(s);return{...t==="dark"?dn:un,...r[t]}}}catch{}return t==="dark"?dn:un}function Ys(t,s){try{localStorage.setItem(Ho,JSON.stringify({dark:t,light:s}))}catch{}}function At(t,s){const r=parseInt(t.slice(1,3),16),n=parseInt(t.slice(3,5),16),o=parseInt(t.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function br(t,s){const r=Math.min(255,parseInt(t.slice(1,3),16)+s),n=Math.min(255,parseInt(t.slice(3,5),16)+s),o=Math.min(255,parseInt(t.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const Ld={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function _s(t,s){var o;const r=(o=Ld[t])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",br(r,24)),n.style.setProperty("--accent-on-primary",Wo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${br(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function Xt(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",At(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",At(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",At(t.borderSubtle,.25)),s.style.setProperty("--text-primary",t.textPrimary),s.style.setProperty("--text-secondary",t.textSecondary),s.style.setProperty("--text-muted",t.textMuted),s.style.setProperty("--border-subtle",At(t.borderSubtle,.5)),s.style.setProperty("--border-default",At(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",br(t.accentColor,30)),s.style.setProperty("--accent-on-primary",Wo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${br(t.accentColor,40)})`),s.style.setProperty("--border-accent",At(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",At(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${At(t.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",t.userBubble),s.style.setProperty("--chat-user-color",t.userText),s.style.setProperty("--chat-user-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px 4px ${t.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",t.assistantBubble),s.style.setProperty("--chat-assistant-color",t.assistantText),s.style.setProperty("--chat-assistant-radius",`${t.bubbleRadius}px ${t.bubbleRadius}px ${t.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${At(t.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",t.containerBg),s.style.setProperty("--dashboard-pane-bg",t.containerBg),s.style.setProperty("--chat-thought-accent",t.accentColor),s.style.setProperty("--chat-tool-accent",t.accentColor),s.style.setProperty("--chat-action-color",t.accentColor),s.style.setProperty("--chat-send-bg",t.sendButton),s.style.setProperty("--chat-input-border",t.inputBorder)}function Tn(){const t=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>t.style.removeProperty(r))}function Rd(t){try{localStorage.setItem(Oo,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Dd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=cr();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Jt()?"dark":"light";Xt(Lt(s))}else Tn(),_s(t,Jt()?"dark":"light")}function Jt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function ft({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),e.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function js({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 Ed({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>Lt(r));a.useEffect(()=>{o(Lt(r))},[r]);const i=a.useCallback((c,d)=>{o(p=>{const f={...p,[c]:d},h=Lt(r==="dark"?"light":"dark");return r==="dark"?Ys(f,h):Ys(h,f),Xt(f),s(f),f})},[r,s]);return e.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[e.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",e.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[t?"🌙 Dark":"☀️ Light"," mode"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(js,{title:"App Background",children:[e.jsx(ft,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(ft,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(ft,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(js,{title:"App Text",children:[e.jsx(ft,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(ft,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(ft,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(js,{title:"Borders & Accent",children:[e.jsx(ft,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(ft,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(ft,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(js,{title:"Chat Bubbles",children:[e.jsx(ft,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(ft,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(ft,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(ft,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(js,{title:"Chat Layout",children:[e.jsx(ft,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(ft,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(ft,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[e.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),e.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),e.jsx("button",{onClick:()=>{const c=t?dn:un,p=Lt(t?"light":"dark");t?Ys(c,p):Ys(p,c),o(c),Xt(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 $d(){const[t,s]=a.useState(cr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Lt("dark"));a.useEffect(()=>{n(Jt());const p=new MutationObserver(()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=Jt();n(h);const w=cr();w==="custom"?Xt(Lt(h?"dark":"light")):_s(w,h?"dark":"light")};return f.addEventListener("change",m),()=>{p.disconnect(),f.removeEventListener("change",m)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xt(Lt(r?"dark":"light")):(Tn(),_s(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(Lt(r?"dark":"light"))},[r]);const c=p=>{s(p),Rd(p)},d=[...Pd,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const f=t===p.id,m=r?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[e.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),e.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:"Fix the bug please"}),e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?"🎨 Custom":p.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&e.jsx(Ed,{dark:r,onColorsChange:p=>i(p)})]})}const Uo="adhdev_mobileDashboardMode_v1";function zo(){try{return localStorage.getItem(Uo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Bd(t){try{localStorage.setItem(Uo,t)}catch{}}function Kd(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(zo()==="chat")},[]),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Kt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:t?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:t,onChange:r=>{s(r),Bd(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function Wd(t,s,r){return{...t||{},id:s,type:(t==null?void 0:t.type)||"adhdev-daemon",status:(t==null?void 0:t.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(t==null?void 0:t.machine)||{},...r.machine}}}function Od(t,s){const{sendData:r}=St(),{injectEntries:n,getIdes:o}=pr(),i=Array.from(new Set(t.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const d=c.map(p=>Ot.subscribe({sendData:r},p,{type:"subscribe",topic:"machine.runtime",key:`machine:${p}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const m=o().find(w=>w.id===p),h=Wd(m,p,f);n([h])}));return()=>{d.forEach(p=>p())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Hd=4e3;function Fo(t,s){const{sendData:r}=St(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!t){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let d=null;const p=Ot.subscribe({sendData:r},t,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${t}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{d&&(clearTimeout(d),d=null),o(f.diagnostics),c(!1)});return p.initialSendAccepted?d=setTimeout(()=>{c(!1)},Hd):c(!1),()=>{d&&clearTimeout(d),p()}},[t,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:o}}function Ud(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function Vo(t){const{sendData:s}=St(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Ud(t);if(!o||!t.sessionId||!s){n({});return}const i=Ot.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${t.sessionId}`,params:{targetSessionId:t.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Qt.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:t.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const Go="adhdev_hiddenTabs";function zd(){try{const t=localStorage.getItem(Go);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function cs(t){try{localStorage.setItem(Go,JSON.stringify([...t]))}catch{}}function Fd(){const[t,s]=a.useState(zd),r=a.useCallback(f=>{s(m=>{const h=new Set(m);return h.has(f)?h.delete(f):h.add(f),cs(h),h})},[]),n=a.useCallback(f=>{s(m=>{if(m.has(f))return m;const h=new Set(m);return h.add(f),cs(h),h})},[]),o=a.useCallback(f=>{s(m=>{if(!m.has(f))return m;const h=new Set(m);return h.delete(f),cs(h),h})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const m=new Set;return cs(m),m})},[]),c=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.add(S);return cs(w),w})},[]),d=a.useCallback((f,m)=>{s(h=>{const w=new Set(h);for(const S of m)w.delete(S);return cs(w),w})},[]),p=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:p}}function Vd({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Ql()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:So(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return td(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const p=Date.now(),f={};for(const[m,h]of Object.entries(d))p-h<5e3&&(f[m]=h);return Object.keys(f).length===Object.keys(d).length?d:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const p=d.filter(f=>f.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[n]),null}function Gd(t){const s=t.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const o=r.get(n.id);if(!o){r.set(n.id,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Xs(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r]!==s[r])return!1;return!0}function qd(t,s){const r=Date.now();return t.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Yd(t,s){const r=[],n=t.sessionId||t.instanceId;r.push({key:t.id,ref:s[t.id]}),n&&r.push({key:n,ref:s[n]});for(const o of t.childSessions||[]){const i=o.id||o.providerType,c=`${t.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Xd(t,s){if(t.length!==s.length)return!1;for(let r=0;r<t.length;r+=1)if(t[r].key!==s[r].key||t[r].ref!==s[r].ref)return!1;return!0}function Jd(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function Zd(t){const s=Jd(t);if(!s)return`empty:${t.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=ss(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function Qd({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),p=a.useRef([]),f=a.useMemo(()=>{const x=Gd(t);return Xs(i.current,x)?i.current:(i.current=x,x)},[t]),m=a.useMemo(()=>Mo(t),[t]),h=a.useRef(new Map),w=a.useRef(new Map),S=a.useMemo(()=>{const x=new Map,g=[];for(const R of f){const{connectionState:K="new",machineName:D}=To(R,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),V=Yd(R,r),_=h.current.get(R.id);if(_&&_.ide===R&&_.connectionState===K&&_.machineName===D&&Xd(_.localRefs,V)){x.set(R.id,_),g.push(..._.conversations);continue}const C=In(R,r,{machineNames:m,connectionStates:s,defaultConnectionState:"new"}),T={ide:R,connectionState:K,machineName:D,localRefs:V,conversations:C};x.set(R.id,T),g.push(...C)}h.current=x;const y=new Map,j=R=>{const K=Zd(R),D=w.current.get(R.tabKey);if(D&&D.signature===K)return y.set(R.tabKey,D),D.timestamp;const V={signature:K,timestamp:Io(R)||(D==null?void 0:D.timestamp)||0};return y.set(R.tabKey,V),V.timestamp},E=[...g].sort((R,K)=>xr(R,K,j));return w.current=y,E},[f,r,s,m]),I=a.useMemo(()=>{const x=qd(S,n);return Xs(c.current,x)?c.current:(c.current=x,x)},[S,n]),u=a.useMemo(()=>{const x=new Map,g=Array.from(new Set(I.map(y=>y.routeId)));for(const y of g){const j=Dt(I,y);j&&x.set(y,j)}return x},[I]),b=a.useMemo(()=>{const x=new Map;for(const g of I)if(g.sessionId&&x.set(g.sessionId,g),g.streamSource==="native"&&g.sessionId){const y=u.get(g.routeId);y&&x.set(g.sessionId,y)}return x},[I,u]),v=a.useMemo(()=>{const x=new Map;for(const g of I)g.sessionId&&x.set(g.sessionId,g),x.set(g.routeId,u.get(g.routeId)||g),x.set(g.tabKey,g);return x},[I,u]),l=a.useCallback(x=>{if(x)return b.get(x)},[b]),N=a.useCallback(x=>{if(x)return v.get(x)},[v]),A=a.useMemo(()=>{const x=I.filter(g=>!o.has(g.tabKey));return Xs(d.current,x)?d.current:(d.current=x,x)},[I,o]),k=a.useMemo(()=>{const x=A.map(g=>g.tabKey);return Xs(p.current,x)?p.current:(p.current=x,x)},[A]);return{chatIdes:f,conversations:I,visibleConversations:A,visibleTabKeys:k,resolveConversationBySessionId:l,resolveConversationByTarget:N}}function eu({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var d;return t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var d;return!t||!s?null:((d=r(s))==null?void 0:d.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(d=>{const p=new URLSearchParams(d);return p.delete("activeTab"),p},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function tu({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{ht.setIdes(t)},[t]),a.useEffect(()=>{ht.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=ht.onToast(p=>{r(m=>m.some(w=>w.message===p.message&&p.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:p.id,message:p.message,type:p.type,timestamp:p.timestamp,targetKey:p.targetKey,actions:p.actions}]);const f=p.duration||5e3;setTimeout(()=>r(m=>m.filter(h=>h.id!==p.id)),f)}),c=ht.onSystemMessage((p,f)=>{var S,I;const m=o(p),h=(S=f._localId)==null?void 0:S.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(I=m.modalButtons)!=null&&I.length||m.modalMessage));h&&w||n(u=>({...u,[p]:[...u[p]||[],f]}))}),d=ht.onClearSystemMessage((p,f)=>{n(m=>{var h;return(h=m[p])!=null&&h.length?{...m,[p]:m[p].filter(w=>{var S;return!(w.role==="system"&&((S=w._localId)!=null&&S.startsWith(f)))})}:m})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=jo.on("status_event",c=>{ht.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var b;const p=d.data;if((p==null?void 0:p.type)!=="notification_action"||typeof p.action!="string"||!p.action.startsWith("approval_")||!(p.daemonId||p.targetSessionId||p.targetKey))return;const f=p.targetSessionId||p.targetKey||p.daemonId,m=o(f),h=(m==null?void 0:m.routeId)||p.daemonId;if(!h)return;const w=Number(p.buttonIndex),S=p.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",I=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),u=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:u?"approve":"reject",button:S,...Number.isFinite(w)&&{buttonIndex:w},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...p.targetSessionId&&{targetSessionId:p.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var d;return(d=navigator.serviceWorker)==null?void 0:d.removeEventListener("message",i)}},[o,s])}const su="adhdev_dashboardLayout_v1",ru="adhdev_dashboardDockview_v1",nu="adhdev_dashboardDockviewHiddenRestore_v1",ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function _n(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function qo(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function Yo(t){return`${su}:${t}`}function au(t){const s=Yo(t);return _n(s,null)}function ou(t,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Yo(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Xo(t){return`${ru}:${t}`}function iu(t){const s=Xo(t);return _n(s,null)}function cu(t,s){try{const r=Xo(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Jo(t){return`${nu}:${t}`}function lu(t){const s=Jo(t);return _n(s,{})}function du(t,s){try{const r=Jo(t);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function uu(){return{groupAssignments:[...ks.groupAssignments],focusedGroup:ks.focusedGroup,groupActiveTabIds:{...ks.groupActiveTabIds},groupTabOrders:{...ks.groupTabOrders},groupSizes:[...ks.groupSizes]}}function pu(){const[t]=a.useState(()=>qo(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,p]=a.useState({}),[f,m]=a.useState([]),[h,w]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,I]=a.useState(!1),u=a.useCallback(()=>{if(S)return;const b=au(t)??uu();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),p(b.groupTabOrders),m(b.groupSizes),I(!0)},[S,t]);return a.useEffect(()=>{S&&ou(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[S,t,s,n,i,d,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=l=>w(l.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:p,groupSizes:f,setGroupSizes:m,isMobile:h,hasHydratedStoredLayout:S,hydrateStoredLayout:u}}function mu(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[0],n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function fu({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:p,historyModalOpen:f,activeConv:m,isRefreshingHistory:h,ides:w,handleRefreshHistory:S}){const I=a.useRef(!1),u=a.useRef(!1),b=a.useRef(null),v=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const l=r(t);if(!l)return;const N=n.get(l.tabKey)??0;c(A=>({...A,[N]:l.tabKey})),d(N),I.current=!0,u.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),p(A=>{const k=new URLSearchParams(A);return k.delete("activeTab"),k},{replace:!0})},[t,s,r,n,o,i,c,d,p]),a.useEffect(()=>{if(!(u.current||o)&&s.length!==0){if(!t){i(),u.current=!0;return}if(I.current){u.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(u.current||o)&&(i(),u.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!f){v.current=!1;return}if(!m||v.current||h)return;const l=w.find(N=>N.id===m.routeId);l&&(!l.chats||l.chats.length===0||mu(l.chats,m))&&(v.current=!0,S())},[f,m,h,w,S]),a.useEffect(()=>{if(!m)return;let l=null,N=0,A=-1,k=0;const x=()=>{l=null;const g=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(g.length===0){N<18&&(N+=1,l=requestAnimationFrame(x));return}let y=0;for(const j of g)j.scrollTop=j.scrollHeight,y+=j.scrollHeight;y===A?k+=1:(k=0,A=y),N+=1,!(k>=2||N>=18)&&(l=requestAnimationFrame(x))};return l=requestAnimationFrame(x),()=>{l!=null&&cancelAnimationFrame(l)}},[m==null?void 0:m.tabKey])}function xu({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[p,f]=a.useState(null),[m,h]=a.useState(null),w=a.useMemo(()=>{if(t||!n)return null;const v=d(n);return v&&!Xe(v)&&!Ve(v)?v:null},[t,n,d]),S=a.useMemo(()=>{const v=p==null?void 0:p.routeId;if(!v)return null;const l=p!=null&&p.tabKey?i.find(N=>N.tabKey===p.tabKey):o?i.find(N=>N.tabKey===o):null;return(l==null?void 0:l.routeId)===v?l:Dt(i,v)},[i,p,o]),I=a.useMemo(()=>{if(S)return c.find(v=>v.id===S.routeId)},[c,S]);a.useEffect(()=>{w&&(f({routeId:w.routeId,tabKey:aa(w)}),h(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const u=a.useCallback(v=>{v&&(f({routeId:v.routeId,tabKey:aa(v)}),h(v))},[]),b=a.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:I,remoteDialogActiveConv:m,setRemoteDialogActiveConv:h,openRemoteDialog:u,closeRemoteDialog:b}}function fs(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:Xe(t)||Ve(t)?{agentType:jt(t)}:t.streamSource==="agent-stream"?{agentType:jt(t)}:s}function Bs(t){return t?mr(t):""}function Ns(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Or(t,s){if(!Array.isArray(t)||t.length!==1||!s)return!1;const r=t[0];if((r==null?void 0:r.active)===!0)return!0;const n=[s.providerSessionId,s.sessionId].filter(o=>typeof o=="string"&&o.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ka({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,p]=a.useState(!1),[f,m]=a.useState(!1),h=a.useCallback(async u=>{try{await t("standalone","launch_ide",{ideType:u,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),w=a.useCallback(async(u,b)=>{try{const v=u||(s==null?void 0:s.daemonId)||"",l=await t(v,"switch_chat",{id:b,sessionId:b,...fs(s)}),N=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ns(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ns(o,`⚠️ Switch error: ${N}`):Ns(o,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Ns(o,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,t,o]),S=a.useCallback(async()=>{if(!(!s||d)){p(!0);try{const u=Bs(s);await t(u,"new_chat",{...fs(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(u){console.error("New chat failed",u)}finally{p(!1)}}},[s,d,t,c,i]),I=a.useCallback(async()=>{var u,b;if(!(!s||f)){m(!0);try{const v=Bs(s),l=async()=>t(v,"list_chats",{forceExpand:!0,...fs(s)});let N=await l(),A=(N==null?void 0:N.chats)||((u=N==null?void 0:N.result)==null?void 0:u.chats);Or(A,s)&&(await new Promise(k=>setTimeout(k,450)),N=await l(),A=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(A)&&(n(s.routeId,A),Or(A,s)&&!Or(r,s)&&Ns(o,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,f,t,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:h,handleSwitchSession:w,handleNewChat:S,handleRefreshHistory:I}}function hu(t,s){if(t.size!==s.size)return!1;for(const[r,n]of t)if(s.get(r)!==n)return!1;return!0}function bu(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function Na(t,s){const r=Object.keys(t),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===t[Number(o)])}function Js(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of t)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const o={};n.forEach((c,d)=>{o[c]=d}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,d]of t){if(!r.has(c)||d<=0)continue;const p=o[d];typeof p=="number"&&p>0&&i.set(c,p)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Sa(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function gu(t,s,r){if(s.length===0)return 0;if(typeof r[t]=="number")return r[t];const n=[...s].reverse().find(o=>o<t)??s[0];return r[n]??0}function yu(t,s,r){if(s.length<=1)return[];const n=s.map(c=>t[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,d)=>c+d,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function Ca(t,s){const r={};for(const[n,o]of Object.entries(t)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function Ia(t){return Array(t).fill(100/t)}function vu({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:p,visibleTabKeys:f}){const m=a.useRef(null),h=a.useMemo(()=>Js(t,f),[t,f]),w=h.assignments,S=a.useMemo(()=>d?1:h.groupCount,[h.groupCount,d]),I=S>1,u=a.useCallback((k,x)=>{s(g=>{const y=new Map(Js(g,f).assignments);return x===0?y.delete(k):y.set(k,x),y}),n(g=>({...g,[x]:k})),r(x)},[s,f,n,r]),b=a.useCallback(k=>{s(x=>{const g=Js(x,f).assignments,y=new Map;for(const[j,E]of g)E!==k&&(E>k?y.set(j,E-1):y.set(j,E));return y}),c(x=>{if(x.length<=1)return[];const g=[...x];g.splice(k,1);const y=g.reduce((j,E)=>j+E,0);return y>0?g.map(j=>j/y*100):[]}),r(0)},[s,f,c,r]),v=a.useCallback((k,x)=>{x.preventDefault();const g=m.current;if(!g)return;const y=x.clientX,j=g.offsetWidth,E=i.length===S?[...i]:Ia(S),R=D=>{const _=(D.clientX-y)/j*100,C=[...E];C[k]=Math.max(15,E[k]+_),C[k+1]=Math.max(15,E[k+1]-_),c(C)},K=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",K),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",K)},[i,S,c]),l=a.useCallback((k,x,g)=>{if(S>=4)return;const y=g==="left"?x:x+1;s(j=>{const E=Js(j,f).assignments,R=new Map;for(const K of p){const D=E.get(K.tabKey)??0,V=D>=y?D+1:D;V>0&&R.set(K.tabKey,V)}return y>0&&R.set(k,y),R}),c(j=>{const E=j.length===S?[...j]:Ia(S),R=E[x]??100/S,K=Math.max(15,R/2),D=Math.max(15,R/2),V=[...E];V[x]=K,V.splice(y,0,D);const _=V.reduce((C,T)=>C+T,0);return V.map(C=>C/_*100)}),n(j=>{const E=Ca(j,y);return E[y]=k,E}),o(j=>{const E=Ca(j,y);return E[y]=[k],E}),r(y)},[S,s,f,p,c,n,o,r]);a.useEffect(()=>{hu(t,w)||s(w)},[t,w,s]),a.useEffect(()=>{const{mapping:k,usedGroups:x}=h;n(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),o(g=>{const y=Sa(g,k);return Na(g,y)?g:y}),r(g=>{const y=d?0:gu(g,x,k);return g===y?g:y}),c(g=>{const y=d?[]:yu(g,x,h.groupCount);return bu(g,y)?g:y})},[h,d,n,o,r,c]);const N=a.useMemo(()=>{const k=Array.from({length:S},()=>[]);for(const x of p){const g=w.get(x.tabKey)??0,y=Math.min(g,S-1);k[y].push(x)}return k},[p,w,S]),A=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:S,isSplitMode:I,groupedConvs:N,moveTabToGroup:u,closeGroup:b,handleResizeStart:v,splitTabRelative:l,clearAllSplits:A}}function wu({ides:t,sendDaemonCommand:s}){const r="0.8.51",n=a.useMemo(()=>t.filter(m=>m.type!=="adhdev-daemon"?!1:Ko(m,r)).sort((m,h)=>Number(Ts(h,r))-Number(Ts(m,r))),[r,t]),o=a.useMemo(()=>n.some(m=>Ts(m,r)),[r,n]),[i,c]=a.useState(!1),[d,p]=a.useState({}),f=a.useCallback(async m=>{var h,w;p(S=>({...S,[m]:"upgrading"}));try{const S=await s(m,"daemon_upgrade",{});(h=S==null?void 0:S.result)!=null&&h.upgraded||(w=S==null?void 0:S.result)!=null&&w.success?p(I=>({...I,[m]:"done"})):p(I=>({...I,[m]:"error"}))}catch{p(S=>({...S,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:f}}function Aa(t){return!t||typeof t!="object"?t:t.result&&typeof t.result=="object"?t.result:t}function Pn(t){return t instanceof Error?t.message:String(t||"")}function Ma(t){const s=Pn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ta(t,s){const r=Pn(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${t}** failed — button not found`:`⚠️ **${t}** failed — ${r}`:`⚠️ **${t}** unavailable`}function Sr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,p]=a.useState(!1),f=a.useRef(!1),m=a.useRef(null),h=a.useCallback(async u=>{if(!s)return;const b=u.trim();if(!b||f.current)return;const v=s.tabKey,l=Date.now(),N=m.current;if(N&&N.tabKey===v&&N.message===b&&l-N.timestamp<2e3)return;f.current=!0,p(!0),m.current={tabKey:v,message:b,timestamp:l};const A=`${l}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:b,timestamp:l,_localId:A},x=!(Xe(s)||Ve(s));x&&r(g=>({...g,[v]:[...g[v]||[],k]}));try{const g=Bs(s);if(!g)return;const y=await t(g,"send_chat",{message:b,...fs(s)}),j=Aa(y);if(x&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r(E=>({...E,[v]:(E[v]||[]).filter(R=>R._localId!==A)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const E=Date.now()-6e4;r(R=>{const K=R[v];if(!K)return R;const D=K.filter(V=>V.timestamp>E);return D.length===K.length?R:{...R,[v]:D}})},6e4)}catch(g){const y=Pn(g);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",g),x&&r(j=>({...j,[v]:(j[v]||[]).filter(E=>E._localId!==A)}))}finally{f.current=!1,p(!1)}},[s,t,r]),w=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(u){console.error("Relaunch failed",u)}},[s,t]),S=a.useCallback(async u=>{if(s)try{const v=(s.modalButtons||[]).indexOf(u),l=u.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),A=Bs(s);if(!A)return;const k=await t(A,"resolve_action",{button:u,action:N?"approve":"reject",...v>=0&&{buttonIndex:v},...fs(s)}),x=Aa(k);x.success||n(g=>[...g,{routeId:s.tabKey,text:Ta(u,x==null?void 0:x.error),timestamp:Date.now()}])}catch(b){Ma(b)||console.error("[ModalButton] Error:",b),n(v=>[...v,{routeId:s.tabKey,text:Ma(b)?Ta(u,b):`❌ **${u}** error`,timestamp:Date.now()}])}},[s,t,n]),I=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await t(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(u){console.error("Focus agent failed",u)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:h,handleRelaunch:w,handleModalButton:S,handleFocusAgent:I}}const Ln=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u=!0}){const b=Vo(s),v=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return e.jsxs(e.Fragment,{children:[e.jsx(po,{activeConv:v,onModalButton:c}),v.transport!=="pty"&&v.transport!=="acp"&&v.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(ts,{size:14})}),e.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),e.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:d,children:"Relaunch with CDP"})]})}):null,v.transport==="pty"?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(Tl,{activeConv:v,clearToken:r,terminalRef:i,handleSendChat:p,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})})]}):e.jsx(nn,{activeConv:v,ideEntry:o,handleSendChat:p,isSendingChat:f,handleFocusAgent:m,isFocusingAgent:h,actionLogs:w,userName:S,scrollToBottomRequestNonce:I,isInputActive:u})]})},(t,s)=>t.activeConv===s.activeConv&&t.isCliTerminal===s.isCliTerminal&&t.ideEntry===s.ideEntry&&t.terminalRef===s.terminalRef&&t.handleModalButton===s.handleModalButton&&t.handleRelaunch===s.handleRelaunch&&t.handleSendChat===s.handleSendChat&&t.isSendingChat===s.isSendingChat&&t.handleFocusAgent===s.handleFocusAgent&&t.isFocusingAgent===s.isFocusingAgent&&t.actionLogs===s.actionLogs&&t.userName===s.userName&&t.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&t.isInputActive===s.isInputActive);function ju({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:p,onOpenNativeConversation:f,onOpenMachine:m,onOpenHistory:h,onOpenRemote:w,onHideConversation:S,onStopCli:I,cliViewMode:u,onSetCliViewMode:b,handleSendChat:v,handleFocusAgent:l,handleModalButton:N,handleRelaunch:A}){const k=a.useRef(null),x=Xe(t)&&!s,g=x&&u==="terminal",y=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center justify-between gap-3 ${y} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Qe(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(bo,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>m(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[x&&u&&e.jsx(Sn,{mode:u,onChange:b,compact:!0}),x&&I&&e.jsx("button",{onClick:()=>{I(t)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:e.jsx(vt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(bn,{size:14})}),!s&&!x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(t),type:"button",children:e.jsx(Nt,{size:14})}),S&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(t),type:"button",title:"Close chat",children:e.jsx(vt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(Ln,{activeConv:t,clearToken:0,isCliTerminal:g,ideEntry:n,terminalRef:k,handleModalButton:N,handleRelaunch:A,handleSendChat:v,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Hr={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 ku(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Zo(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(ku())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Hr[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return e.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),e.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${t==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),t==="windows"&&e.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[e.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),e.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:d,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:Hr[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Hr[c].cmd}),e.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),e.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",e.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Qo({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Nt},{key:"chats",label:"Chats",icon:Kt}];return e.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:e.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:o,icon:i})=>{const c=t===n;return e.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[e.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:e.jsx(i,{size:15})}),e.jsx("span",{children:o})]},n)})})})}function Zs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function ls({children:t,className:s=""}){return e.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:t})}function Ss({icon:t,title:s,subtitle:r,children:n}){return e.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[e.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:t}),e.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Qs({item:t,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",d=s==="task_complete",{isReconnecting:p,isConnecting:f}=ys(t.conversation),m=Qe(t.conversation),h=ns(t.conversation),w=No(t.conversation,{requiresAction:s==="needs_attention"}),S=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",I=o?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",u=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return e.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(t.conversation),type:"button",children:[o||i?e.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,e.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${I}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${u}`,children:m}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:uo(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:N,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:t.preview})]}),o&&!d&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),d&&e.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&e.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},t.conversation.tabKey)}function _a({size:t=32,label:s}){return e.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[e.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:t,height:t}}),s&&e.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function Nu({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:p,onShowConversation:f,onShowAllHidden:m,onOpenNewSession:h,onOpenMachine:w,onOpenSettings:S,onSectionChange:I,wsStatus:u="connected",isStandalone:b=!1}){const v=u==="disconnected"||u==="reconnecting"||u==="offline"||u==="auth_failed",l=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,A=t==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",x=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return e.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[e.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[t==="chats"&&(s.length>0||r.length>0)&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[e.jsx(jr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:e.jsx(vr,{size:18})})]})]})}),e.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${x}`,children:[t==="machines"&&e.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?e.jsx(Ss,{icon:e.jsx(_a,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:u==="offline"?"Your device appears to be offline. Waiting for network…":u==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(Ss,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your first machine",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install the ADHDev daemon on your machine, then it will show up here.",children:!b&&e.jsx("div",{className:"w-full max-w-[360px] mt-4",children:e.jsx(Zo,{})})}):e.jsx(ls,{children:c.map((g,y)=>e.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(g.id),type:"button",children:[e.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:d(g.label)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:g.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:g.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[g.unread," new"]}):g.total>0?`${g.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:g.subtitle}),g.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[g.total," chat",g.total!==1?"s":"",g.unread>0?` · ${g.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},g.id))})}),t==="chats"&&s.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Needs attention",className:"mb-0"}),e.jsx(ls,{children:s.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"needs_attention",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&r.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(ls,{children:r.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"task_complete",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&n.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsx(Zs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(ls,{children:n.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"working",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))})]}),t==="chats"&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&e.jsx(Zs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(ls,{children:o.map((g,y)=>e.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:e.jsx(Qs,{item:g,type:"earlier",getAvatarText:d,onOpenConversation:p})},g.conversation.tabKey))}):N?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?e.jsx(Ss,{icon:e.jsx(_a,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?e.jsx(Ss,{icon:e.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:e.jsx(Kt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):e.jsx(Ss,{icon:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),t==="chats"&&i.length>0&&e.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[e.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[e.jsx("span",{children:"Hidden"}),e.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),e.jsx(ls,{className:"bg-bg-secondary/25",children:i.map((g,y)=>e.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(g),type:"button",children:[e.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:d(Qe(g))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Qe(g)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ns(g)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},g.tabKey))})]})]}),t==="chats"&&h&&e.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":"Start new session",children:e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),e.jsx(Qo,{section:t,onSectionChange:I})]})}function Su(t){const s=t.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),o=(r[2]||"").replace(/[\\/]+/g,"\\");return o?`${n}:\\${o}`:`${n}:\\`}return null}function Cr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Su(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Cu(t){const s=t.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}async function Ir(t,s,r){const n=await t(s,"file_list_browse",{path:r});if(!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"Could not browse folder");const o=typeof(n==null?void 0:n.path)=="string"?n.path:r,i=o.includes("\\")?"\\":"/",c=(p,f)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${f}`:p==="/"||p==="\\"?`${i}${f}`:`${p.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:c(o,p.name)})).sort((p,f)=>p.name.localeCompare(f.name)):[];return{path:o,directories:d}}function Ar({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:p,onConfirm:f}){const[m,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const w=Cu(r),S=m.trim();return e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:e.jsxs("div",{className:"w-full max-w-2xl max-h-[min(86vh,720px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:d,"aria-label":"Close folder browser",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!w||o||p(w)},disabled:!w||o,children:[e.jsx(xn,{size:15}),"Parent"]}),e.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:m,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!S||o||(I.preventDefault(),p(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||o||p(S)},disabled:!S||o,children:"Go"})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?e.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?e.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):e.jsx("div",{className:"p-3",children:n.map(I=>e.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>p(I.path),children:[e.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:e.jsx(xs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:I.name}),e.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:I.path})]})]},I.path))})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:d,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(S||r),disabled:!S&&!r||o,children:c})]})]})})}function Rn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:d=!1,showArgsInput:p,argsValue:f,onArgsChange:m,showModelInput:h,modelValue:w,onModelChange:S,historyProviderNode:I,onConfirm:u,onCancel:b}){const v=n==null?void 0:n.find(l=>l.key===o);return e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:t}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:b,"aria-label":"Close launch confirmation",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),e.jsx("select",{value:o||"",onChange:l=>i(l.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(l=>e.jsx("option",{value:l.key,children:l.label},l.key))}),(v==null?void 0:v.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),I,r.map(l=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:l.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:l.value})]},`${l.label}:${l.value}`)),h&&S&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),e.jsx("input",{type:"text",value:w||"",onChange:l=>S(l.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),e.jsx("input",{type:"text",value:f||"",onChange:l=>m(l.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:d,children:"Cancel"}),e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:u,disabled:d,children:[e.jsx(gn,{size:14}),d?"Launching…":c]})]})]})})}function Pa(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function Zt(t){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=t,i=[];o&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const p of s.workspaces||[])i.push({key:`saved:${p.id}`,label:`${p.id===s.defaultWorkspaceId?"⭐ ":""}${Pa(p.path,p.label)}`,description:p.path,workspaceId:p.id,workspacePath:p.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(p=>p.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:Pa(c),description:c,workspaceId:null,workspacePath:c}),n){const p=`saved:${n}`;if(i.some(f=>f.key===p))return{options:i,selectedKey:p}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Ur(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function Iu({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var ye,F,me,Ce;const c=Hs(),[d,p]=a.useState(!1),f=(((ye=t.detectedIdes)==null?void 0:ye.length)||0)>0,m=a.useMemo(()=>(t.workspaces||[]).map(xe=>({id:xe.id,path:xe.path,label:xe.label})),[t]),h=t.defaultWorkspaceId||null,[w,S]=a.useState(h||((F=m[0])==null?void 0:F.id)||""),[I,u]=a.useState(""),[b,v]=a.useState(""),[l,N]=a.useState([]),[A,k]=a.useState(!1),[x,g]=a.useState(""),[y,j]=a.useState(!1),[E,R]=a.useState(Ur(f,s.length,r.length)),K=a.useRef(null),[D,V]=a.useState(null),_=a.useRef("__home__"),[C,T]=a.useState("__home__"),[z,L]=a.useState(""),[$,H]=a.useState(""),[se,Y]=a.useState(""),[ie,je]=a.useState([]),[G,oe]=a.useState(!1),[W,be]=a.useState(!1),X=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const ue=w==="__custom__"?I.trim():((me=m.find(xe=>xe.id===w))==null?void 0:me.path)||"",te=w==="__custom__"&&!!ue&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ae=w!=="__custom__"&&((Ce=m.find(xe=>xe.id===w))==null?void 0:Ce.path)||"",fe=a.useCallback(async xe=>{k(!0),g("");try{const Le=await o(xe);v(Le.path),u(Le.path),N(Le.directories)}catch(Le){g(Le instanceof Error?Le.message:"Could not load folder")}finally{k(!1)}},[o]),le=a.useCallback(()=>{var Le,Be;S("__custom__"),j(!0);const xe=Cr(t.platform,[I.trim(),ae,(Le=m.find(Fe=>Fe.id===h))==null?void 0:Le.path,(Be=m[0])==null?void 0:Be.path]);fe(xe)},[I,h,fe,ae,t.platform,m]),he=a.useCallback(xe=>{if(xe!=null&&xe.workspaceId){S(xe.workspaceId),u("");return}if(xe!=null&&xe.workspacePath){S("__custom__"),u(xe.workspacePath);return}S(""),u("")},[]),J=a.useCallback(xe=>{if(S(xe),xe==="__custom__"){le();return}u("")},[le]),pe=a.useCallback(xe=>{S("__custom__"),u(xe)},[]),ne=a.useCallback((xe,Le)=>{K.current=Le,_.current=xe.selectedWorkspaceKey||"__home__",T(xe.selectedWorkspaceKey||"__home__"),L(xe.initialArgs||""),H(xe.initialModel||""),Y(""),je([]),V(xe),xe.providerType&&i&&(oe(!0),i(xe.providerType).then(Be=>je(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>oe(!1)))},[i]),we=a.useCallback(()=>{K.current&&(be(!0),K.current().finally(()=>{K.current=null,be(!1),V(null)}))},[]),ge=a.useCallback(()=>{K.current=null,V(null)},[]),P=a.useCallback(xe=>{_.current=xe,T(xe)},[]);return a.useEffect(()=>{var xe;X.current!==t.id&&(X.current=t.id,S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"),u(""),v(""),N([]),g(""),j(!1),R(Ur(f,s.length,r.length)))},[r.length,s.length,h,f,t.id,m]),a.useEffect(()=>{var xe;w!=="__custom__"&&(w&&m.some(Le=>Le.id===w)||S(h||((xe=m[0])==null?void 0:xe.id)||"__custom__"))},[h,w,m]),a.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||R(Ur(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:p,hasIdeOptions:f,workspaceRows:m,defaultWorkspaceId:h,workspaceChoice:w,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:l,browseBusy:A,browseError:x,browseDialogOpen:y,activeLauncherKind:E,launchConfirm:D,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:C,launchConfirmArgs:z,launchConfirmModel:$,launchConfirmResumeId:se,launchConfirmSavedSessions:ie,launchConfirmSessionsLoading:G,launchConfirmBusy:W,resolvedWorkspacePath:ue,canCreateMissingWorkspace:te,openBrowseDialog:le,loadBrowsePath:fe,handleWorkspaceChoiceChange:J,chooseCustomWorkspacePath:pe,setCustomWorkspacePath:u,setBrowseDialogOpen:j,setActiveLauncherKind:R,openLaunchConfirm:ne,handleConfirmLaunch:we,closeLaunchConfirm:ge,setWorkspaceSelectionFromOption:he,setLaunchConfirmWorkspaceKeyAndSync:P,setLaunchConfirmArgs:L,setLaunchConfirmModel:H,setLaunchConfirmResumeId:Y}}function Au({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:p,section:f,showBottomNav:m,onBack:h,onSectionChange:w,onOpenConversation:S,onOpenRecent:I,onOpenMachineDetails:u,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:l,onBrowseDirectory:N,onLaunchWorkspaceProvider:A,onListSavedSessions:k}){const x=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",g=r.slice(0,4),y=s.slice(0,3),j=Iu({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:N,onListSavedSessions:k}),E=a.useMemo(()=>g.map(C=>({key:`recent-launch:${C.id}`,primary:C.label,secondary:`${x(C.kind)}${C.subtitle?` · ${C.subtitle}`:""}`,onClick:()=>{const{options:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:C.workspace});j.openLaunchConfirm({title:`Launch ${C.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:x(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),await I({...C,workspace:(L==null?void 0:L.workspacePath)??null})})}})),[j,I,g]),R=a.useMemo(()=>y.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:Qe(C.conversation),secondary:Cl(C.conversation,{timestampLabel:C.timestamp?uo(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,y]),K=j.showAllRecent?E:E.slice(0,4),D=E.length>0,V=R.length>0,_=p?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`flex items-center justify-between gap-3 ${_} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[e.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:e.jsx(xn,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(t,{fallbackId:t.id})}),e.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[t.platform||"machine",t.version?` · v${t.version}`:""]})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[V&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(C=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),D&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:K.map(C=>e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&e.jsx("div",{className:"flex justify-center px-4 pt-2",children:e.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>j.setShowAllRecent(C=>!C),children:j.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||o.length>0)&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:e.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),e.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),e.jsx("select",{value:j.workspaceChoice,onChange:C=>j.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:j.workspaceRows.length>0?e.jsxs(e.Fragment,{children:[j.workspaceRows.map(C=>e.jsxs("option",{value:C.id,children:[C.id===j.defaultWorkspaceId?"⭐ ":"",kr(C.path,C.label)||C.path]},C.id)),e.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):e.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:e.jsx(xs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:j.openBrowseDialog,children:"Select workspace…"}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{j.resolvedWorkspacePath&&l(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&e.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&e.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&e.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[e.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(t.detectedIdes||[]).slice(0,6).map(C=>e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:T,selectedKey:z}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const L=T.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),v(C.type,{workspacePath:(L==null?void 0:L.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(j.activeLauncherKind==="cli"?n:o).map(C=>e.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const T=j.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:L}=Zt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:L,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=z.find(H=>H.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),A(T,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[e.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),d.message&&e.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${d.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[d.message,j.canCreateMissingWorkspace&&e.jsx("div",{className:"mt-2",children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>l(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[e.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),e.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:u,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&e.jsx(Ar,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:C=>{j.loadBrowsePath(C)},onConfirm:C=>{j.chooseCustomWorkspacePath(C),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(Rn,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.confirmLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),j.launchConfirmSessionsLoading&&e.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),e.jsxs("select",{value:j.launchConfirmResumeId,onChange:C=>j.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[e.jsx("option",{value:"",children:"Start a new session"}),j.launchConfirmSavedSessions.map(C=>e.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),m&&e.jsx(Qo,{section:f,onSectionChange:w})]})}function ei(t){var r;const s=((r=t.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Mu(t,s){if(!t)return[];const r=t.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:n.currentModel||n.workspace||void 0,workspace:n.workspace,currentModel:n.currentModel})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===t.id).map(n=>{var i,c,d,p,f;const o=$s(n)?"cli":ms(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||($s(n)?n.cliName||n.type:ms(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ms(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(p=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:p.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function Tu(t,s){const r=new Map;for(const n of s){const o=zt(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return t.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((h,w)=>w.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=rn(n),p=o.filter(h=>h.unread||h.requiresAction).length,f=ei(n),m=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:kt(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:p,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?Il(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,o)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=o.latestTimestamp||o.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(o.label)})}function er(t,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${t}`,s)}catch{}}function _u({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:p,onRequestedActiveTabConsumed:f,requestedMachineId:m,onRequestedMachineConsumed:h,requestedMobileSection:w,onRequestedMobileSectionConsumed:S,setSelectedTabKey:I,setScreen:u,setSelectedMachineId:b,setSection:v,setMachineBackTarget:l,resetMachineAction:N}){const A=a.useRef(null),k=a.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const g=Ds(x,c),y=Math.max(Date.now(),Ht(x),g.lastUpdated||0);er("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:Qe(x),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:Ht(x),readAt:y}),d(zt(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,seenAt:y}).then(j=>{er("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:j})}).catch(j=>{er("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,d]);return a.useEffect(()=>{var g;if(!n){u("inbox"),I(((g=t[0])==null?void 0:g.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;A.current!==x&&(A.current=x,k(n))},[t,k,i,n,u,I]),a.useEffect(()=>{if(!p)return;const x=t.find(g=>g.tabKey===p);x&&(I(x.tabKey),u("chat"),f==null||f())},[t,f,p,u,I]),a.useEffect(()=>{if(!m)return;const x=s.find(g=>g.id===m);x&&(b(x.id),N(),v("machines"),l("inbox"),u("machine"),h==null||h())},[s,h,m,N,l,u,v,b]),a.useEffect(()=>{w&&(v(w),u("inbox"),S==null||S())},[S,w,u,v]),a.useEffect(()=>{const x=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);x.length!==0&&er("inbox_state",{screen:i,selectedTabKey:o,items:x.map(g=>{const y=Ds(g.conversation,c);return{liveState:y,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:Qe(g.conversation),serverBucket:y.inboxBucket,computedBucket:g.inboxBucket,serverUnread:y.unread,computedUnread:g.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:Ht(g.conversation)}})})},[r,c,i,o]),{markConversationRead:k}}function Pu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function La(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Lu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ru({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[p,f]=a.useState(null),m=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),h=a.useCallback(async(l,N,A)=>{var k;try{i("loading"),d(`Launching ${N}…`);const x={ideType:N,enableCdp:!0};(k=A==null?void 0:A.workspacePath)!=null&&k.trim()&&(x.workspace=A.workspacePath.trim()),await t(l,"launch_ide",x),i("done"),d(`${N} launch requested`)}catch(x){i("error"),d(x instanceof Error?x.message:"Launch IDE failed"),console.error("Launch IDE failed",x)}},[t]),w=a.useCallback(async(l,N,A)=>{if(N.trim())try{i("loading"),d(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const k=await t(l,"workspace_add",{path:N.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(k!=null&&k.success){i("done"),d(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),d(k instanceof Error?k.message:"Could not save workspace")}},[t]),S=a.useCallback(async l=>{var N,A,k,x,g,y;try{i("loading"),d("Starting daemon upgrade…");const j=await t(l,"daemon_upgrade",{});if((N=j==null?void 0:j.result)!=null&&N.alreadyLatest){i("done"),d(`Already on v${((A=j==null?void 0:j.result)==null?void 0:A.version)||"latest"}.`);return}if((k=j==null?void 0:j.result)!=null&&k.upgraded||(x=j==null?void 0:j.result)!=null&&x.success){i("done"),d(`Upgrade to v${((g=j==null?void 0:j.result)==null?void 0:g.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((y=j==null?void 0:j.result)==null?void 0:y.error)||"Upgrade failed")}catch(j){i("error"),d(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(l,N,A,k)=>{var y,j,E;const x=Date.now(),g={machineId:l,kind:N,providerType:A,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:x};try{i("loading"),d(`Launching ${A}…`),f(g);const R={cliType:A};(y=k==null?void 0:k.workspacePath)!=null&&y.trim()?R.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(R.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(R.resumeSessionId=k.resumeSessionId),(j=k==null?void 0:k.args)!=null&&j.trim()&&(R.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(R.initialModel=k.model.trim());const K=await t(l,"launch_cli",R),D=(K==null?void 0:K.result)||K,V=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(K!=null&&K.success&&V){f(null),i("done"),d(`${A} launched`),s(`/dashboard?activeTab=${encodeURIComponent(V)}`);return}if(K!=null&&K.success){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d((K==null?void 0:K.error)||(D==null?void 0:D.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(R){if(Lu(R)){i("loading"),d(`${A} launch requested — waiting for session…`);return}f(null),i("error"),d(R instanceof Error?R.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,t]),u=a.useCallback(async(l,N)=>{try{const A=await t(l,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),k=(A==null?void 0:A.result)??A;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[t]),b=a.useCallback(async(l,N)=>Ir(t,l,N),[t]);a.useEffect(()=>{var k;if(!p)return;const l=La(p.workspacePath),N=r.find(x=>{var K,D,V,_;if(!x||x.type==="adhdev-daemon"||Pu(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const E=String(x.providerSessionId||"");if(p.resumeSessionId&&E)return E===p.resumeSessionId;if(l){const C=La(x.workspace||x.runtimeWorkspaceLabel);return C?C===l:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((_=(V=(D=(K=x.activeChat)==null?void 0:K.messages)==null?void 0:D.at)==null?void 0:V.call(D,-1))==null?void 0:_.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const A=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(k=n.find(x=>x.routeId===N.id))==null?void 0:k.sessionId;A&&(f(null),i("done"),d(`${p.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(A)}`))},[n,r,s,p]),a.useEffect(()=>{if(!p)return;const l=window.setTimeout(()=>{f(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[p]);const v=a.useCallback(async(l,N)=>{if(N.kind==="ide"&&N.providerType){await h(l,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await I(l,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:w,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:I,handleListSavedSessions:u,handleBrowseDirectory:b,handleOpenRecent:v}}function Du({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:p,setMachineBackTarget:f}){const m=a.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),h=a.useCallback(v=>{const l=t.find(N=>N.routeId===v.routeId&&N.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[t,n,c,i]),w=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=a.useCallback((v,l="inbox")=>{d(v),o(),p("machines"),f(l),c("machine")},[o,f,c,p,d]),I=a.useCallback(v=>{const l=zt(v);l&&S(l,"chat")},[S]),u=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(v=>{p(v),c("inbox")},[c,p]);return{openConversation:m,openNativeConversation:h,backFromConversation:w,openMachine:S,openConversationMachine:I,backFromMachine:u,changeMachineSection:b}}function Eu(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function $u(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function tr(t){return[...t].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Bu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:p,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:u,onOpenRemote:b,onStopCli:v,wsStatus:l,isConnected:N,onShowHiddenConversation:A,onShowAllHiddenConversations:k,onHideConversation:x,onOpenNewSession:g}){const[y,j]=a.useState(()=>{var F;return((F=t[0])==null?void 0:F.tabKey)||null}),[E,R]=a.useState(()=>t[0]?"chat":"inbox"),[K,D]=a.useState("chats"),[V,_]=a.useState(null),[C,T]=a.useState("inbox"),z=bs(),L="0.8.51",$=a.useMemo(()=>t.find(F=>F.tabKey===y)||t[0]||null,[t,y]),H=a.useMemo(()=>$?r.find(F=>F.id===$.routeId):void 0,[r,$]),se=a.useMemo(()=>!$||Ve($)||!Xe($)?null:hs($),[$]),Y=a.useMemo(()=>r.filter(F=>F.type==="adhdev-daemon").sort(wn),[r]),ie=a.useMemo(()=>Y.find(F=>F.id===V)||null,[Y,V]),je=a.useMemo(()=>Ws(r),[r]),G=Sr({sendDaemonCommand:o,activeConv:$||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),oe=Ru({sendDaemonCommand:o,navigate:z,ides:r,conversations:t}),W=a.useMemo(()=>t.map(F=>{const me=E==="chat"&&($==null?void 0:$.tabKey)===F.tabKey,Ce=Es(F,je,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}),xe=Ht(F),Le=ko(F);return{conversation:F,timestamp:xe,preview:Le,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[t,je,E,$]),{markConversationRead:be}=_u({conversations:t,machineEntries:Y,items:W,selectedConversation:$,selectedTabKey:y,screen:E,liveSessionInboxState:je,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:m,requestedMachineId:h,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T,resetMachineAction:oe.resetMachineAction}),X=Du({conversations:t,selectedConversation:$,machineBackTarget:C,markConversationRead:be,resetMachineAction:oe.resetMachineAction,setSelectedTabKey:j,setScreen:R,setSelectedMachineId:_,setSection:D,setMachineBackTarget:T}),ue=a.useMemo(()=>tr(W.filter(F=>F.requiresAction)),[W]),te=a.useMemo(()=>tr(W.filter(F=>F.unread&&!F.requiresAction)),[W]),ae=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&F.isWorking)),[W]),fe=a.useMemo(()=>tr(W.filter(F=>!F.unread&&!F.requiresAction&&!F.isWorking)),[W]),le=a.useMemo(()=>ie?W.filter(F=>zt(F.conversation)===ie.id):[],[W,ie]),he=a.useMemo(()=>Mu(ie,r),[r,ie]),J=(ie==null?void 0:ie.version)||null,pe=!!ie&&!!J&&!0&&J!==L,ne=a.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),we=a.useMemo(()=>ne.filter(F=>F.category==="cli"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),ge=a.useMemo(()=>ne.filter(F=>F.category==="acp"&&F.installed!==!1).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[ne]),P=a.useMemo(()=>Tu(Y,W),[W,Y]),ye=a.useCallback(async F=>{ie&&await oe.handleOpenRecent(ie.id,F)},[oe,ie]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&$?e.jsx(ju,{selectedConversation:$,isAcp:Ve($),isStandalone:d,selectedIdeEntry:H,actionLogs:n,userName:p,isSendingChat:G.isSendingChat,isFocusingAgent:G.isFocusingAgent,handleModalButton:G.handleModalButton,handleRelaunch:G.handleRelaunch,onBack:X.backFromConversation,onOpenNativeConversation:X.openNativeConversation,onOpenMachine:X.openConversationMachine,onHideConversation:x,onOpenHistory:u,onOpenRemote:b,onStopCli:v,cliViewMode:se,onSetCliViewMode:async F=>{if($&&se!==F)try{await o(zt($)||$.routeId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:jt($),mode:F})}catch(me){$u(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},handleSendChat:G.handleSendChat,handleFocusAgent:G.handleFocusAgent}):E==="machine"&&ie?e.jsx(Au,{selectedMachineEntry:ie,selectedMachineConversations:le,selectedMachineRecentLaunches:he,cliProviders:we,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:L,machineAction:oe.machineAction,isStandalone:d,section:K,showBottomNav:C==="inbox",onBack:X.backFromMachine,onSectionChange:X.changeMachineSection,onOpenConversation:X.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>z(`/machines/${ie.id}`),onMachineUpgrade:()=>oe.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(F,me)=>oe.handleLaunchDetectedIde(ie.id,F,me),onAddWorkspace:(F,me)=>oe.handleAddWorkspace(ie.id,F,me),onBrowseDirectory:F=>oe.handleBrowseDirectory(ie.id,F),onLaunchWorkspaceProvider:(F,me,Ce)=>oe.handleLaunchWorkspaceProvider(ie.id,F,me,Ce),onListSavedSessions:F=>oe.handleListSavedSessions(ie.id,F)}):e.jsx(Nu,{section:K,attentionItems:ue,unreadItems:te,workingItems:ae,completedItems:fe,hiddenConversations:s,machineCards:P,getAvatarText:Eu,onOpenConversation:X.openConversation,onShowConversation:A,onShowAllHidden:k,onOpenNewSession:g,onOpenMachine:X.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:D,wsStatus:l,isConnected:N,isStandalone:d})})}function zr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function Ku({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,p]=a.useState(!1),[f,m]=a.useState(null),h=a.useCallback(()=>{c.current=0,p(!1),m(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const w=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,p(!0))},[]),S=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!zr(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),l=b.clientX-v.left,N=v.width/3;l<N?m("split-left"):l>N*2?m("split-right"):m("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,p(!1),m(null))},[]),u=a.useCallback(b=>{c.current=0,p(!1);const v=b.dataTransfer.getData("text/tab-key"),l=v?t.some(A=>A.tabKey===v):!1,N=f;if(m(null),i(),!!v){if(b.preventDefault(),N==="split-left"&&zr(s,r)){r==null||r(v,"split-left");return}if(N==="split-right"&&zr(s,r)){r==null||r(v,"split-right");return}if(l){o(v);return}n==null||n(v)}},[t,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:h,handleDragEnter:w,handleDragOver:S,handleDragLeave:I,handleDrop:u}}function Wu(t,s){const r=new Set(s.map(i=>i.tabKey)),n=t.filter(i=>r.has(i)),o=s.filter(i=>!t.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function Ou({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,p]=a.useState(r??[]),[f,m]=a.useState(null),h=a.useRef(null),w=a.useRef(null),S=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{S.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{p(g=>{const y=Wu(g,t);return y.length===g.length&&y.every((j,E)=>j===g[E])?g:y})},[t]);const u=a.useMemo(()=>{const g=f??d;if(g.length===0)return t;const y=new Map(g.map((j,E)=>[j,E]));return[...t].sort((j,E)=>{const R=y.get(j.tabKey)??999,K=y.get(E.tabKey)??999;return R-K})},[t,f,d]);a.useEffect(()=>{var y,j;if(u.length===0){i!==null&&(c(null),(y=S.current)==null||y.call(S,null));return}if(i&&u.some(E=>E.tabKey===i))return;const g=u[0].tabKey;g!==i&&(c(g),(j=S.current)==null||j.call(S,g))},[u,i]);const b=a.useMemo(()=>u.find(g=>g.tabKey===i),[u,i]),v=a.useCallback(g=>{var y;c(g),(y=S.current)==null||y.call(S,g)},[]),l=a.useCallback((g,y,j)=>{p(E=>{var V;const R=E.filter(_=>_!==g),K=R.indexOf(y);if(K<0)return E;const D=j==="left"?K:K+1;return R.splice(D,0,g),(V=I.current)==null||V.call(I,R),R}),m(null)},[]),N=a.useCallback((g,y,j)=>{const R=(d.length>0?d:t.map(V=>V.tabKey)).filter(V=>V!==g),K=R.indexOf(y);if(K<0)return;const D=j==="left"?K:K+1;R.splice(D,0,g),h.current=R,m(R)},[d,t]),A=a.useCallback(()=>{var y;const g=h.current;g&&(p(g),(y=I.current)==null||y.call(I,g))},[]),k=a.useCallback(()=>{h.current=null,m(null)},[]),x=a.useCallback(g=>{p(y=>{var E;const j=y.filter(R=>R!==g);return j.push(g),(E=I.current)==null||E.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:u,previewOrderRef:h,draggingTabRef:w,selectTab:v,handleTabReorder:l,updatePreviewOrder:N,commitPreviewOrder:A,clearPreviewOrder:k,moveTabToEnd:x,setDraggingTabKey:g=>{w.current=g}}}function Hu({dropAction:t,canSplit:s}){return e.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:e.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),e.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:t==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:e.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),e.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:t==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:t==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:e.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Dn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,d=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",p=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install the ADHDev daemon and link your dashboard to start.";return t===0&&!s&&o&&i?e.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[e.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),e.jsxs("div",{className:"text-center max-w-lg",children:[e.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&e.jsx(Zo,{}),r&&o.length>0&&e.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Detected IDEs"}),e.jsx("div",{className:"flex flex-wrap gap-2.5 justify-center mt-1",children:o.map(f=>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(f.type),children:[e.jsx(oo,{size:14,className:"opacity-70"})," Open ",f.name]},f.type))})]}),c&&e.jsx("div",{className:"mt-8",children:e.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):e.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const ti="adhdev-tab-shortcuts";function si(){try{return JSON.parse(localStorage.getItem(ti)||"{}")}catch{return{}}}function ri({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>si()),[d,p]=a.useState(null),f=a.useCallback(h=>{const w=[];return h.metaKey&&w.push(o?"⌘":"Meta"),h.ctrlKey&&w.push("Ctrl"),h.altKey&&w.push(o?"⌥":"Alt"),h.shiftKey&&w.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(w.push(h.key.length===1?h.key.toUpperCase():h.key),w.join("+"))},[o]),m=a.useCallback(h=>{c(h);try{localStorage.setItem(ti,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const h=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){p(null);return}const S=f(w);if(!S)return;const I={...i};for(const[u,b]of Object.entries(I))b===S&&delete I[u];I[d]=S,m(I),p(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,d,i,m,f]),a.useEffect(()=>{if(!t)return;const h=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[S,I]of Object.entries(i))if(s.includes(S)&&f(w)===I){w.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:p,saveShortcuts:m}}const Uu=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:p,onSelectTab:f,onConversationActivated:m,onPreviewReorder:h,onReorderTab:w,onCommitPreviewOrder:S,onClearPreviewOrder:I,onDragStateReset:u,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:l,longPressTimer:N,isGroupActive:A}){const k=ys(s),x=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",g=k.isReconnecting,y=a.useCallback(T=>{d.current=s.tabKey,b(s.tabKey),T.dataTransfer.setData("text/tab-key",s.tabKey),T.dataTransfer.effectAllowed="move"},[s.tabKey,d,b]),j=a.useCallback(()=>{d.current=null,b(null),S(),I(),u()},[d,b,S,I,u]),E=a.useCallback(T=>{const z=d.current;if(!(!z||z===s.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";h(z,s.tabKey,$)}},[s.tabKey,d,h]),R=a.useCallback(T=>{T.preventDefault(),T.stopPropagation();const z=T.dataTransfer.getData("text/tab-key");if(z&&z!==s.tabKey){const L=T.currentTarget.getBoundingClientRect(),$=T.clientX<L.left+L.width/2?"left":"right";c.includes(z)?w(z,s.tabKey,$):v&&v(z)}I()},[s.tabKey,c,w,v,I]),K=a.useCallback(T=>{T.stopPropagation(),p(),f(s.tabKey),m(s)},[s,m,p,f]),D=a.useCallback(T=>{T.preventDefault(),l(T.clientX,T.clientY,s.tabKey)},[s.tabKey,l]),V=a.useCallback(T=>{const z=T.touches[0];N.current=setTimeout(()=>{l(z.clientX,z.clientY,s.tabKey)},600)},[s.tabKey,N,l]),_=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),C=["adhdev-dockview-tab",x,r&&"is-active",A&&"is-group-active",g&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:y,onDragEnd:j,onDragOver:E,onDrop:R,onClick:K,onContextMenu:D,onTouchStart:V,onTouchEnd:_,onTouchMove:_,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?e.jsx("div",{className:"tab-spinner"}):k.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Qe(s),children:Qe(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:g?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(s)}):k.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Yt(s),e.jsx("span",{className:"connecting-dots"})]}):Yt(s)})]}),i&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(t,s)=>t.conv===s.conv&&t.isActive===s.isActive&&t.isDraggedTab===s.isDraggedTab&&t.isTaskCompleteUnread===s.isTaskCompleteUnread&&t.shortcut===s.shortcut&&t.conversationKeys===s.conversationKeys&&t.isGroupActive===s.isGroupActive);function zu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onHideTab:u,isGroupActive:b,allowTabShortcuts:v=!0}){const[l,N]=a.useState(null),A=a.useRef(null),k=a.useRef(null),x=a.useMemo(()=>t.map(D=>D.tabKey),[t]);Ks("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:g,tabShortcuts:y,shortcutListening:j,setShortcutListening:E,saveShortcuts:R}=ri({enabled:v,sortedTabKeys:t.map(D=>D.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const D=V=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(V.target)||N(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[l]),a.useEffect(()=>{const D=k.current;if(!D)return;const V=_=>{Math.abs(_.deltaY)>Math.abs(_.deltaX)&&(_.preventDefault(),D.scrollLeft+=_.deltaY)};return D.addEventListener("wheel",V,{passive:!1}),()=>D.removeEventListener("wheel",V)},[]);const K=a.useCallback((D,V,_)=>{N({x:D,y:V,tabKey:_})},[]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:e.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(D=>e.jsx(Uu,{conv:D,isActive:s===D.tabKey,isDraggedTab:o.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:v?y[D.tabKey]:void 0,conversationKeys:x,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:m,onClearPreviewOrder:h,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:I,onOpenContextMenu:K,longPressTimer:A,isGroupActive:b},D.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),l&&e.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:l.x,top:l.y},children:[v&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:D=>{D.stopPropagation(),E(l.tabKey),N(null)},children:["⌨ ",y[l.tabKey]?`Change shortcut (${y[l.tabKey]})`:"Set shortcut"]}),y[l.tabKey]&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const D={...y};delete D[l.tabKey],R(D),N(null)},children:"✕ Remove shortcut"})]}),u&&e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{u(l.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&j&&e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",g?"⌘+1":"Ctrl+1",", ",g?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Fu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,userName:f,groupIndex:m,onFocus:h,isSplitMode:w,numGroups:S,onMoveTab:I,onReceiveTab:u,style:b,detectedIdes:v,handleLaunchIde:l,onActiveTabChange:N,initialActiveTabId:A,initialTabOrder:k,onTabOrderChange:x,onHideTab:g,isFocused:y,allowTabShortcuts:j=!0}){const{sendCommand:E}=St(),R=a.useRef(null),{activeTabId:K,activeConv:D,sortedConversations:V,draggingTabRef:_,selectTab:C,handleTabReorder:T,updatePreviewOrder:z,commitPreviewOrder:L,clearPreviewOrder:$,moveTabToEnd:H,setDraggingTabKey:se}=Ou({conversations:t,initialActiveTabId:A,initialTabOrder:k,onActiveTabChange:N,onTabOrderChange:x}),Y=Sr({sendDaemonCommand:o,activeConv:D,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:ie,dropAction:je,resetDragState:G,handleDragEnter:oe,handleDragOver:W,handleDragLeave:be,handleDrop:X}=Ku({conversations:t,numGroups:S,onMoveTab:I,onReceiveTab:u,onOwnTabDrop:H,onClearPreviewOrder:$}),ue=D&&!Ve(D)&&hs(D)==="terminal",te=a.useMemo(()=>D?s.find(J=>J.id===D.routeId):void 0,[s,D]),ae=a.useMemo(()=>D?n.filter(J=>J.routeId===D.tabKey):[],[n,D]),fe=a.useMemo(()=>Ws(s),[s]),le=a.useMemo(()=>new Set(V.filter(J=>Kc(J,fe,{isOpenConversation:J.tabKey===K})).map(J=>J.tabKey)),[K,fe,V]);Ks("PaneGroup",{groupIndex:m,conversationCount:t.length,activeTabId:K,dragOver:ie});const he=a.useCallback(J=>{J.streamSource==="agent-stream"&&J.agentType&&E(J.routeId,"focus_session",{agentType:J.agentType,...J.sessionId&&{targetSessionId:J.sessionId}}).catch(()=>{})},[E]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:ie?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(zu,{conversations:V,activeTabId:K,groupIndex:m,numGroups:S,unreadTabKeys:le,draggingTabRef:_,onFocus:h,onSelectTab:C,onConversationActivated:he,onPreviewReorder:z,onReorderTab:T,onCommitPreviewOrder:L,onClearPreviewOrder:$,onDragStateReset:G,onDragTabKeyChange:se,onMoveTab:I,onReceiveTab:u,onHideTab:g,isGroupActive:y??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:oe,onDragOver:W,onDragLeave:be,onDrop:X,children:[ie&&e.jsx(Hu,{dropAction:je,canSplit:!!(S<4&&I)}),D?e.jsx(Ln,{activeConv:D,clearToken:r[D.tabKey]||0,isCliTerminal:!!ue,ideEntry:te,terminalRef:R,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ae,userName:f,isInputActive:!w||!!y}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:t.length,isSplitMode:w,isStandalone:d,hasRegisteredMachines:p,detectedIdes:v,handleLaunchIde:l})})]})]})}function Vu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,focusedGroup:I,setFocusedGroup:u,moveTabToGroup:b,splitTabRelative:v,closeGroup:l,handleResizeStart:N,detectedIdes:A,handleLaunchIde:k,groupActiveTabIds:x,setGroupActiveTabIds:g,groupTabOrders:y,setGroupTabOrders:j,toggleHiddenTab:E,allowTabShortcuts:R=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((K,D)=>{const V=s&&n.length===r?`${n[D]}%`:void 0;return e.jsxs(et.Fragment,{children:[s&&D>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:_=>N(D-1,_),onDoubleClick:()=>l(D),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(Fu,{style:s?{flexBasis:V??`${100/r}%`,flexGrow:V?0:1,flexShrink:V?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:p,setLocalUserMessages:f,setActionLogs:m,isStandalone:h,hasRegisteredMachines:w,userName:S,groupIndex:D,isFocused:s&&I===D,onFocus:()=>u(D),isSplitMode:s,numGroups:r,onMoveTab:(_,C)=>{C==="left"&&D>0?b(_,D-1):C==="right"&&D<r-1?b(_,D+1):C==="split-left"&&r<4?v(_,D,"left"):C==="split-right"&&r<4&&v(_,D,"right")},onReceiveTab:_=>b(_,D),detectedIdes:D===0?A:void 0,handleLaunchIde:D===0?k:void 0,onActiveTabChange:_=>g(C=>(C[D]??null)===(_??null)?C:{...C,[D]:_}),initialActiveTabId:x[D],initialTabOrder:y[D],onTabOrderChange:_=>j(C=>{const T=C[D]||[];return T.length===_.length&&T.every((z,L)=>z===_[L])?C:{...C,[D]:_}}),onHideTab:E,allowTabShortcuts:R})]},D)})})}function ni({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>t?tt.onScreenshot("ide-page",(m,h)=>{if(m!==t)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var m;return t?((m=tt.onStatus)==null?void 0:m.call(tt,(h,w)=>{h===t&&w!=null&&w.screenshotUsage&&d(w.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const f=t?tt.get(t):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,t]);const p=a.useCallback(async(f,m)=>{const h=t?tt.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,m,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:p}}const ai="adhdev-dashboard-action-shortcuts",Gu=1200,qu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Yu(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(t,s){switch(t){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function oi(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",t)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",t)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",t)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:Je("dockActiveTab",t)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:Je("splitActiveTabRight",t)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:Je("splitActiveTabDown",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",t)}]}function pn(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function gr(t){const s=Object.fromEntries(oi(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ai)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(qu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function ii(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Xu({enabled:t=!0,onTrigger:s}){const r=Yu(),[n,o]=a.useState(()=>gr(r)),[i,c]=a.useState(null),[d,p]=a.useState([]),f=a.useRef({parts:[],timer:null}),m=a.useCallback(u=>{const b=[];return u.metaKey&&b.push(r?"⌘":"Meta"),u.ctrlKey&&b.push("Ctrl"),u.altKey&&b.push(r?"⌥":"Alt"),u.shiftKey&&u.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(b.push(ii(u.key)),b.join("+"))},[r]),h=a.useCallback(u=>{o(u);try{localStorage.setItem(ai,JSON.stringify(u))}catch{}},[]);a.useEffect(()=>{const u=gr(r),b=Object.entries(n),v=Object.entries(u);b.length===v.length&&b.every(([l,N])=>u[l]===N)||h(u)},[n,r,h]);const w=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),S=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Gu))},[]);a.useEffect(()=>{if(!i)return;const u=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),p([]);return}const v=m(b);if(!v)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(d.length===0&&N){p([v]);return}const k=[...d,v].slice(0,2).join(" "),x={...n};for(const[g,y]of Object.entries(x))y===k&&delete x[g];x[i]=k,h(x),c(null),p([])};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[n,m,h,i,d]),a.useEffect(()=>{if(!t||i)return;const u=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const l=b.metaKey||b.ctrlKey||b.altKey;if(pn(b.target)&&!l)return;const N=f.current.parts,A=l?[v]:[...N.slice(-1),v].slice(-2),k=A.join(" "),x=A[A.length-1],g=Object.entries(n).filter(([,K])=>!!K),y=g.find(([,K])=>K===k);if(y){b.preventDefault(),w(),s(y[0]);return}if(g.some(([,K])=>K.startsWith(`${k} `))){b.preventDefault(),f.current.parts=A,S();return}const E=g.find(([,K])=>K===x);if(E){b.preventDefault(),w(),s(E[0]);return}if(g.some(([,K])=>K.startsWith(`${x} `))){b.preventDefault(),f.current.parts=[x],S();return}w()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n,S,t,m,s,w,i]),a.useEffect(()=>()=>w(),[w]);const I=a.useMemo(()=>oi(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:p,saveShortcuts:h}}const ci=a.createContext(null);function Mr(){const t=a.useContext(ci);if(!t)throw new Error("DashboardDockviewContext missing");return t}function lr(t){return Qe(t)||t.tabKey}function Ju(t){return`remote:${t}`}function Wt(t){return t.startsWith("remote:")}function Ra(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fr(t){var r,n,o,i,c;const s=t==null?void 0:t.defaultView;if(s)try{s.focus(),(n=(r=t==null?void 0:t.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=t==null?void 0:t.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var d,p;try{s.focus(),(p=(d=t==null?void 0:t.body)==null?void 0:d.focus)==null||p.call(d)}catch{}})}catch{}}function sr(t,s){t.classList.remove(en.className,tn.className),t.classList.add(s==="light"?en.className:tn.className)}function Da(t){return t?Array.from(new Set(t.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function Zu(t){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[t.api.onDidActiveGroupChange(r),t.api.onDidTitleChange(r),t.api.onDidGroupChange(r),t.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[t.api,t.containerApi])}function Qu(t,s,r){var d;const n=[s];let o;for(const p of n){let f;for(const m of p){const h=t.addPanel({id:m.tabKey,component:"conversation",title:lr(m),params:{kind:"conversation",tabKey:m.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=h.id)}o=f??o}const i=r??((d=s[0])==null?void 0:d.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function Ea(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Wt(n.id)||r.has(n.id)||t.removePanel(n);for(const n of s){const o=t.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==lr(n)&&o.api.setTitle(lr(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:lr(n),params:{kind:"conversation",tabKey:n.tabKey},...t.activePanel?{position:{referencePanel:t.activePanel.id,direction:"within"},inactive:!0}:t.panels[0]?{position:{referencePanel:t.panels[0].id,direction:"within"},inactive:!0}:{}})}}function $a(t,s,r){var p,f;const n=r?Ju(r):null;for(const m of[...t.panels])Wt(m.id)&&(!n||m.id!==n)&&t.removePanel(m);if(!r||!n)return;const o=Dt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=Co(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((p=t.activePanel)==null?void 0:p.id)??((f=t.panels.find(m=>!Wt(m.id)))==null?void 0:f.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...d?{position:{referencePanel:d,direction:"right"},inactive:!0}:{}})}function ep({params:t,api:s}){var h;const r=Mr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=Sr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const w=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of w)S.dispose()}},[s]);const p=a.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const m=!Ve(c)&&hs(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(Ln,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:p,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function tp({params:t}){var p;const s=Mr(),r=a.useMemo(()=>Dt([...s.conversationsByTabKey.values()],t.routeId),[s.conversationsByTabKey,t.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===t.routeId),[s.ides,t.routeId]),o=(r==null?void 0:r.daemonId)||((p=r==null?void 0:r.routeId)==null?void 0:p.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=ni({doId:o,targetSessionId:r?Nn(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:e.jsx(lo,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:d})}):e.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function sp(){const t=Mr();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(Dn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function rp(t){var S,I;Zu(t);const s=Mr(),r=a.useCallback(u=>{"button"in u&&u.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const u=Dt([...s.conversationsByTabKey.values()],t.params.routeId),b=((S=t.api.group.activePanel)==null?void 0:S.id)===t.api.id,v=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(u==null?void 0:u.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||"Remote"}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u!=null&&u.machineName?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"Live remote view"}),e.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),e.jsx("span",{className:"adhdev-dockview-tab-machine",children:u.machineName})]}):e.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(t.params.tabKey);if(!n)return e.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":t.params.tabKey||"",children:e.jsx("div",{className:"adhdev-dockview-tab-copy",children:e.jsx("div",{className:"adhdev-dockview-tab-primary",children:t.api.title||t.params.tabKey})})});const o=((I=t.api.group.activePanel)==null?void 0:I.id)===t.api.id,i=t.api.isGroupActive,c=Es(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,p=c.isConnecting,f=c.isGenerating,m=c.isWaiting,h=c.unread,w=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:Qe(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:u=>{var b;u.preventDefault(),r(u),s.openTabContextMenu({x:u.clientX,y:u.clientY,tabKey:n.tabKey,sourceDocument:((b=u.target)==null?void 0:b.ownerDocument)??document})},children:[h&&e.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),e.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?e.jsx("div",{className:"tab-spinner"}):m?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):d?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):p?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:Qe(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Yt(n)}):p?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Yt(n)}):e.jsx("span",{children:Yt(n)})})]}),w&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function np({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:p,initialDataLoaded:f,userName:m,detectedIdes:h,handleLaunchIde:w,toggleHiddenTab:S,actionShortcuts:I,registerActionHandlers:u,onActiveTabChange:b,requestedActiveTabKey:v,requestedRemoteIdeId:l,onRequestedActiveTabConsumed:N,scrollToBottomRequest:A}){var wt,bt,Tt;const{theme:k}=Mn(),{sendCommand:x}=St(),g=a.useRef(null),y=a.useRef(null),j=a.useRef(!1),E=a.useRef(!1),R=a.useRef(!1),K=a.useRef(null),D=a.useRef([]),[V,_]=a.useState(null),[C,T]=a.useState(!1),[z,L]=a.useState(!1),[$,H]=a.useState(0),se=a.useRef(null),Y=a.useMemo(()=>qo(typeof window<"u"?window.innerWidth:1280),[]),ie=a.useRef(typeof window>"u"?{}:lu(Y)),je=a.useMemo(()=>new Map(t.map(B=>[B.tabKey,B])),[t]),G=a.useMemo(()=>Ws(r),[r]),oe=a.useCallback(()=>{var B;(B=g.current)==null||B.focus()},[]),W=a.useCallback(B=>{const U=document,q=B.document;for(const Z of U.querySelectorAll('link[rel="stylesheet"]')){const Ie=q.createElement("link");Ie.rel="stylesheet",Ie.href=Z.href,Z.crossOrigin&&(Ie.crossOrigin=Z.crossOrigin),q.head.appendChild(Ie)}for(const Z of U.querySelectorAll("style")){const Ie=q.createElement("style");Ie.textContent=Z.textContent,q.head.appendChild(Ie)}const O=[];for(const Z of U.styleSheets)try{for(const Ie of Z.cssRules)Ie instanceof CSSStyleRule&&(Ie.selectorText===":root"||Ie.selectorText==="html")&&O.push(Ie.cssText)}catch{}if(O.length>0){const Z=q.createElement("style");Z.textContent=O.join(`
|
|
43
|
-
`),q.head.appendChild(Z)}const de=U.documentElement.getAttribute("data-theme");de&&q.documentElement.setAttribute("data-theme",de),q.documentElement.style.colorScheme=de==="light"?"light":"dark",q.body.className=U.body.className;const Se=U.documentElement.getAttribute("style");Se&&q.documentElement.setAttribute("style",Se);const Ae=q.getElementById("dv-popout-window");Ae instanceof HTMLElement&&(Ae.classList.add("adhdev-dockview"),sr(Ae,k))},[k]),be=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const de=O.getElementById("dv-popout-window");de instanceof HTMLElement&&(de.classList.add("adhdev-dockview"),sr(de,k));const Se=document.documentElement.getAttribute("data-theme");Se&&O.documentElement.setAttribute("data-theme",Se),O.documentElement.style.colorScheme=Se==="light"?"light":"dark",O.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae?O.documentElement.setAttribute("style",Ae):O.documentElement.removeAttribute("style")}catch{}},[k]),X=a.useCallback(()=>{var U;const B=g.current;if(B)for(const q of B.groups)try{const O=(U=q.element)==null?void 0:U.ownerDocument;if(!O||O===document)continue;const de=O.getElementById("dv-popout-window");if(!(de instanceof HTMLElement))continue;de.classList.add("adhdev-dockview"),sr(de,k),de.classList.toggle("is-showing-dockview-overlay",z),de.classList.toggle("is-dragging-dockview",C)}catch{}},[C,z,k]),ue=a.useCallback(B=>{const U=g.current;if(!U)return;const q=U.getPanel(B);q&&U.addPopoutGroup(q,{popoutUrl:"/popout.html",onDidOpen:({window:O})=>{W(O),we();const de=je.get(B);O.document.title=de?`${Qe(de)} — ADHDev`:"ADHDev — Popout"}})},[je,W]),te=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(de=>{var Se;try{return((Se=de.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),ae=a.useCallback(B=>{var O;const U=g.current;if(!U)return!1;const q=U.getPanel(B);if(!q)return!1;try{return((O=q.group.element)==null?void 0:O.ownerDocument)!==document}catch{return!1}},[]),fe=a.useCallback(B=>{ae(B)&&te(B),S(B)},[ae,te,S]),le=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);!U||!q||U.addFloatingGroup(q,{width:600,height:500})},[]),he=a.useCallback(B=>{var q;const U=(q=g.current)==null?void 0:q.getPanel(B);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),J=a.useCallback(()=>{var U,q;const B=(q=(U=g.current)==null?void 0:U.activePanel)==null?void 0:q.id;return!B||Wt(B)?null:je.has(B)?B:null},[je]),pe=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.getPanel(B);if(!U||!q)return;const O=U.groups.filter(de=>{try{return de.model.location.type==="grid"}catch{return!0}});O.length>0?q.api.moveTo({group:O[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),ne=a.useCallback(()=>{var Se;const B=g.current;if(!B)return;const q=B.groups.filter(Ae=>{var Z;try{return((Z=Ae.element)==null?void 0:Z.ownerDocument)===document&&Ae.model.location.type==="grid"}catch{return!1}})[0]||null,O=[...B.panels];for(const Ae of O){const Z=(Se=Ae.group.element)==null?void 0:Se.ownerDocument,Ie=Ae.group.model.location.type;Z===document&&Ie==="grid"||(q&&q.id!==Ae.group.id?Ae.api.moveTo({group:q,position:"center"}):Ae.api.moveTo({position:"center"}))}const de=B.activePanel;de&&(de.group.model.openPanel(de),de.api.setActive()),Fr(document)},[]),we=a.useCallback(()=>{var U,q;const B=g.current;if(B)for(const O of B.groups){const de=(U=O.element)==null?void 0:U.ownerDocument;if(!de||de===document)continue;const Se=de.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Ae=null,Z=de.title||"ADHDev",Ie="Popout workspace";const De=O.activePanel;if(De)if(Ae=De.id,Wt(De.id)){const re=((q=De.params)==null?void 0:q.routeId)||De.id.slice(7),ce=Dt([...je.values()],re);Z=Co(ce),Ie=ce!=null&&ce.machineName?`Remote view · ${ce.machineName}`:"Remote view"}else{const re=je.get(De.id);Z=re?Qe(re):De.title||De.id,Ie=re?Yt(re):"Dockview panel"}de.title=`${Z} — ADHDev`;let Ue=de.getElementById("adhdev-popout-header");Ue instanceof HTMLElement||(Ue=de.createElement("div"),Ue.id="adhdev-popout-header",de.body.appendChild(Ue)),Ue.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ue.innerHTML=`
|
|
44
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
45
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
46
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ra(Z)}</div>
|
|
47
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ra(Ie)}</div>
|
|
48
|
-
</div>
|
|
49
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
50
|
-
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
51
|
-
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
52
|
-
</div>
|
|
53
|
-
`,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const M=Ue.querySelector("[data-adhdev-popout-focus]");M&&(M.onclick=()=>{window.focus()});const ee=Ue.querySelector("[data-adhdev-popout-dock]");ee&&(ee.disabled=!Ae,ee.style.opacity=Ae?"1":"0.5",ee.style.cursor=Ae?"pointer":"default",ee.onclick=()=>{var re;Ae&&te(Ae),(re=de.defaultView)==null||re.focus()})}},[je,te]),ge=a.useCallback(B=>{var O;const U=g.current,q=U==null?void 0:U.getPanel(B);if(!(!U||!q)){q.group.model.openPanel(q),q.api.setActive();try{const de=q.group.model.location;de.type==="popout"?de.getWindow().focus():Fr((O=q.group.element)==null?void 0:O.ownerDocument)}catch{}}},[]),P=a.useCallback(B=>{const U=g.current,q=U==null?void 0:U.activePanel,O=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!O)return;const de=O.panels||[];if(de.length<=1)return;const Se=de.findIndex(Ie=>Ie.id===q.id);if(Se<0)return;const Ae=(Se+B+de.length)%de.length,Z=de[Ae];Z&&(Z.group.model.openPanel(Z),Z.api.setActive())},[]),ye=a.useCallback(B=>{var ee;const U=g.current,q=(U==null?void 0:U.activeGroup)||((ee=U==null?void 0:U.activePanel)==null?void 0:ee.group);if(!U||!q)return;const O=U.groups||[],de=O.find(re=>re.id===q.id);if(!de)return;const Se=de.element.getBoundingClientRect(),Ae=Se.left+Se.width/2,Z=Se.top+Se.height/2,Ie=(re,ce,Pe,Me)=>Math.max(0,Math.min(ce,Me)-Math.max(re,Pe)),De=re=>{const ce=re.element.getBoundingClientRect(),Pe=ce.left+ce.width/2,Me=ce.top+ce.height/2;let Oe=0,rt=0,Ye=0,qe=!1;if(B==="left"?(qe=Pe<Ae,Oe=Math.max(0,Se.left-ce.right),rt=Math.abs(Me-Z),Ye=Ie(Se.top,Se.bottom,ce.top,ce.bottom)):B==="right"?(qe=Pe>Ae,Oe=Math.max(0,ce.left-Se.right),rt=Math.abs(Me-Z),Ye=Ie(Se.top,Se.bottom,ce.top,ce.bottom)):B==="above"?(qe=Me<Z,Oe=Math.max(0,Se.top-ce.bottom),rt=Math.abs(Pe-Ae),Ye=Ie(Se.left,Se.right,ce.left,ce.right)):(qe=Me>Z,Oe=Math.max(0,ce.top-Se.bottom),rt=Math.abs(Pe-Ae),Ye=Ie(Se.left,Se.right,ce.left,ce.right)),!qe)return Number.POSITIVE_INFINITY;const He=Ye>0?0:120;return Oe*3+rt+He};let Ue=null,M=Number.POSITIVE_INFINITY;for(const re of O){if(re.id===de.id)continue;const ce=De(re);Number.isFinite(ce)&&(ce>=M||(M=ce,Ue=re))}return Ue||void 0},[]),F=a.useCallback(B=>{var O;const U=ye(B);if(!U)return;const q=U.activePanel||U.panels[0];q&&(U.model.openPanel(q),q.api.setActive(),Fr((O=U.element)==null?void 0:O.ownerDocument))},[ye]),me=a.useCallback((B,U)=>{const q=g.current,O=q==null?void 0:q.activePanel,de=(q==null?void 0:q.activeGroup)||(O==null?void 0:O.group);if(!q||!O||!de)return;let Se=ye(B);!Se&&(U!=null&&U.createGroupIfMissing)&&(Se=q.addGroup({referenceGroup:de,direction:B})),Se&&(O.api.moveTo({group:Se,position:"center"}),O.group.model.openPanel(O),O.api.setActive())},[ye]),{isMac:Ce,tabShortcuts:xe,shortcutListening:Le,setShortcutListening:Be,saveShortcuts:Fe}=ri({sortedTabKeys:t.map(B=>B.tabKey),onFocus:oe,onSelectTab:ge}),st=a.useCallback(()=>{var q;const B=g.current;if(!B)return;const U=B.activePanel;if(U){if(Wt(U.id)){const O=((q=U.params)==null?void 0:q.routeId)||U.id.slice(7),de=Dt(t,O);de!=null&&de.tabKey&&Be(de.tabKey);return}je.has(U.id)&&Be(U.id)}},[je,ge,Be,t]),ze=a.useCallback(B=>{const U=[];return B.metaKey&&U.push(Ce?"⌘":"Meta"),B.ctrlKey&&U.push("Ctrl"),B.altKey&&U.push(Ce?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&U.push(Ce?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(U.push(ii(B.key)),U.join("+"))},[Ce]),dt=a.useCallback(B=>{var U,q;switch(B){case"splitActiveTabRight":me("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":me("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const O=J();O&&le(O);return}case"popoutActiveTab":{const O=J();O&&ue(O);return}case"dockActiveTab":{const O=J();if(!O)return;ae(O)?te(O):he(O)&&pe(O);return}case"focusLeftPane":F("left");return;case"focusRightPane":F("right");return;case"focusUpPane":F("above");return;case"focusDownPane":F("below");return;case"moveActiveTabToLeftPane":me("left");return;case"moveActiveTabToRightPane":me("right");return;case"moveActiveTabToUpPane":me("above");return;case"moveActiveTabToDownPane":me("below");return;case"selectPreviousGroupTab":P(-1);return;case"selectNextGroupTab":P(1);return;case"setActiveTabShortcut":st();return;case"hideCurrentTab":{const O=(q=(U=g.current)==null?void 0:U.activePanel)==null?void 0:q.id;O&&!Wt(O)&&fe(O);return}default:return}},[P,pe,F,le,J,fe,he,ae,te,me,ue,st]);a.useEffect(()=>{if(!V)return;const B=V.sourceDocument,U=B.defaultView??window,q=O=>{const de=B.querySelector("[data-dockview-tab-context-menu]");de&&de.contains(O.target)||_(null)};return U.addEventListener("mousedown",q,!0),U!==window&&window.addEventListener("mousedown",()=>_(null),!0),()=>{U.removeEventListener("mousedown",q,!0),U!==window&&window.removeEventListener("mousedown",()=>_(null),!0)}},[V]);const gt=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:je,detectedIdes:h,handleLaunchIde:w,ides:r,isStandalone:d,hasRegisteredMachines:p,liveSessionInboxState:G,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:fe,userName:m,scrollToBottomRequest:A,tabShortcuts:xe,openTabContextMenu:({x:B,y:U,tabKey:q,sourceDocument:O})=>_({x:B,y:U,tabKey:q,sourceDocument:O??document}),popoutTab:ue,moveTabBackToMain:te,isTabInPopout:ae,floatTab:le,isTabFloating:he}),[n,s,je,h,w,r,d,p,G,o,c,i,fe,m,A,xe,ue,te,ae,le,he]),Ge=a.useCallback(B=>{if(!B)return!1;const U=g.current;if(!U)return!1;const q=U.getPanel(B);return q?(q.group.model.openPanel(q),q.api.setActive(),N==null||N(),!0):!1},[N]),at=a.useCallback(()=>{if(R.current)return!1;const B=Ge(K.current);return B&&(R.current=!0),B},[Ge]),ot=a.useCallback(()=>{var U;const B=g.current;B&&cu(Y,{activeTabId:((U=B.activePanel)==null?void 0:U.id)??null,layout:B.toJSON()})},[Y]),Ke=a.useCallback(()=>{du(Y,ie.current)},[Y]),ct=a.useCallback(B=>{var O,de,Se,Ae;const U=g.current;if(!U)return{kind:"grid"};const q=U.toJSON();for(const Z of q.floatingGroups||[])if((de=(O=Z.data)==null?void 0:O.views)!=null&&de.includes(B)&&Z.position)return{kind:"floating",position:Z.position};for(const Z of q.popoutGroups||[])if((Ae=(Se=Z.data)==null?void 0:Se.views)!=null&&Ae.includes(B))return{kind:"popout",position:Z.position,popoutUrl:Z.url};return{kind:"grid"}},[]),ut=a.useCallback(B=>{const U=g.current;if(!U)return;const q=U.getPanel(B),O=ie.current[B];if(!q||!O||O.kind==="grid")return;if(q.group.model.location.type===O.kind){delete ie.current[B],Ke();return}if(O.kind==="floating"){U.addFloatingGroup(q,{x:O.position.left??24,y:O.position.top??24,width:O.position.width,height:O.position.height}),delete ie.current[B],Ke();return}delete ie.current[B],Ke()},[Ke]);a.useEffect(()=>(u==null||u({setShortcutForActiveTab:st,restoreHiddenTabToSavedLocation:ut,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>P(-1),activateNextTabInGroup:()=>P(1),floatActiveTab:()=>{const B=J();B&&le(B)},popoutActiveTab:()=>{const B=J();B&&ue(B)},dockActiveTab:()=>{const B=J();B&&(ae(B)?te(B):he(B)&&pe(B))},splitActiveTabRight:()=>me("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>me("below",{createGroupIfMissing:!0}),focusLeftPane:()=>F("left"),focusRightPane:()=>F("right"),focusUpPane:()=>F("above"),focusDownPane:()=>F("below"),moveActiveTabToLeftPane:()=>me("left"),moveActiveTabToRightPane:()=>me("right"),moveActiveTabToUpPane:()=>me("above"),moveActiveTabToDownPane:()=>me("below")}),()=>u==null?void 0:u(null)),[P,pe,le,F,J,he,ae,me,te,ue,u,ne,ut,st]);const it=a.useCallback(()=>{const B=y.current;if(!B)return;const U=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const q of U)q.setAttribute("data-adhdev-force-hidden","true")},[]),Q=a.useCallback(()=>{const B=y.current;if(!B)return;const U=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const q of U)q.removeAttribute("data-adhdev-force-hidden")},[]),_e=a.useCallback(()=>{const B=y.current;if(!B)return;const U=B.querySelectorAll(".dv-drop-target-container");for(const de of U)de.remove();const q=B.querySelectorAll(".dv-drop-target-dropzone");for(const de of q)de.remove();const O=B.querySelectorAll(".dv-drop-target");for(const de of O)de.classList.remove("dv-drop-target")},[]),Re=a.useCallback(()=>{T(!1),L(!1),Q(),it(),_e(),!(typeof window>"u")&&(se.current!=null&&window.clearTimeout(se.current),window.requestAnimationFrame(()=>{it(),_e()}),se.current=window.setTimeout(()=>{it(),_e(),se.current=null},80))},[Q,it,_e]),We=a.useCallback(B=>{var q;g.current=B.api;const U=iu(Y);K.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&B.api.fromJSON(U.layout,{reuseExistingPanels:!1}),E.current=!!(U!=null&&U.layout)&&!f&&t.length===0,E.current||(Ea(B.api,t),$a(B.api,t,l)),B.api.totalPanels===0&&t.length>0?Qu(B.api,t,v):!E.current&&!Ge(v)&&at(),j.current=!0,B.api.onDidActivePanelChange(O=>{var Se;if(K.current=(O==null?void 0:O.id)??null,R.current=!0,we(),O&&Wt(O.id)){const Ae=((Se=O.params)==null?void 0:Se.routeId)||O.id.slice(7),Z=Dt(t,Ae);b((Z==null?void 0:Z.tabKey)??null),ot();return}if(b((O==null?void 0:O.id)??null),ot(),!O)return;const de=je.get(O.id);(de==null?void 0:de.streamSource)==="agent-stream"&&de.agentType&&x(de.routeId,"focus_session",{agentType:de.agentType,...de.sessionId&&{targetSessionId:de.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{ot(),we(),H(O=>O+1)}),B.api.onWillDragPanel(()=>{T(!0),L(!1),it()}),B.api.onWillDragGroup(()=>{T(!0),L(!1),it()}),B.api.onWillShowOverlay(()=>{Q(),L(!0)}),B.api.onDidMovePanel(Re),B.api.onDidDrop(Re),B.api.onDidAddGroup(O=>{requestAnimationFrame(()=>{var de,Se;try{const Ae=(de=O.element)==null?void 0:de.ownerDocument;if(!Ae||Ae===document)return;(Se=Ae.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Z=document.documentElement.getAttribute("data-theme");Z&&Ae.documentElement.setAttribute("data-theme",Z),Ae.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&Ae.documentElement.setAttribute("style",Ie)}catch{}we(),H(Ae=>Ae+1)})}),b(((q=B.api.activePanel)==null?void 0:q.id)??null)},[Ge,Re,Q,je,f,Y,it,_e,b,ot,v,l,x,we,t]);a.useLayoutEffect(()=>{const B=g.current;if(!B||!j.current||E.current&&!f)return;E.current&&(E.current=!1);const U=D.current,q=new Set(U),O=t.map(De=>De.tabKey),de=new Set(O);let Se=!1;for(const De of U)de.has(De)||(ie.current[De]=ct(De),Se=!0);Se&&Ke(),Ea(B,t),$a(B,t,l);const Ae=O.filter(De=>!q.has(De));let Z=!1;for(const De of Ae){const Ue=B.getPanel(De),M=ie.current[De];if(!Ue||!M||M.kind==="grid")continue;if(Ue.group.model.location.type===M.kind){delete ie.current[De],Z=!0;continue}if(M.kind==="floating"){B.addFloatingGroup(Ue,{x:M.position.left??24,y:M.position.top??24,width:M.position.width,height:M.position.height}),delete ie.current[De],Z=!0;continue}}if(Z&&Ke(),D.current=O,v&&Ge(v))return;!B.activePanel&&B.panels[0]&&(B.panels[0].group.model.openPanel(B.panels[0]),B.panels[0].api.setActive()),!!(B.activePanel&&B.getPanel(B.activePanel.id))||at()},[Ge,at,f,Ke,ct,v,l,t]),a.useEffect(()=>{j.current&&Ge(v)},[Ge,v]),a.useEffect(()=>{if(!C||typeof window>"u")return;const B=()=>Re();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[Re,C]),a.useEffect(()=>()=>{typeof window>"u"||se.current!=null&&window.clearTimeout(se.current)},[]),a.useEffect(()=>{const B=q=>{const O=q.target;if(!O)return;const de=O.querySelector("[data-tab-key]")||O.closest("[data-tab-key]");if(de){const Se=de.getAttribute("data-tab-key");if(Se&&q.dataTransfer){const Ae=O.closest(".dv-tab")||de.closest(".dv-tab")||de;q.dataTransfer.effectAllowed="move",q.dataTransfer.setData("text/tab-key",Se),Ae instanceof HTMLElement&&q.dataTransfer.setDragImage(Ae,Math.max(12,Math.round(Ae.clientWidth/2)),Math.max(10,Math.round(Ae.clientHeight/2)))}}};window.addEventListener("dragstart",B);const U=Da(g.current);for(const q of U)q.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const q of U)q.removeEventListener("dragstart",B)}},[$]),a.useEffect(()=>{var U;const B=(U=y.current)==null?void 0:U.querySelector(".adhdev-dockview");B instanceof HTMLElement&&sr(B,k),be(),we(),X()},[we,X,be,k]),a.useEffect(()=>{we(),X()},[we,X]),a.useEffect(()=>{const B=U=>{if(U.defaultPrevented||Le)return;const q=ze(U);if(!q)return;const O=U.metaKey||U.ctrlKey||U.altKey;pn(U.target)&&!O||gr(Ce).setActiveTabShortcut!==q||(U.preventDefault(),U.stopPropagation(),st())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[ze,Ce,Le,st]),a.useEffect(()=>{const B=Da(g.current);if(B.length===0)return;const U=B.map(q=>{let O=[],de=null;const Se=()=>{de!=null&&q.clearTimeout(de),de=null,O=[]},Ae=()=>{de!=null&&q.clearTimeout(de),de=q.setTimeout(()=>{de=null,O=[]},1200)},Z=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const Ue=ze(De);if(!Ue)return;const M=si();for(const[ee,re]of Object.entries(M))if(t.some(ce=>ce.tabKey===ee)&&re===Ue){De.preventDefault(),ge(ee);return}},Ie=De=>{if(De.defaultPrevented||Le)return;const Ue=ze(De);if(!Ue)return;const M=De.metaKey||De.ctrlKey||De.altKey;if(pn(De.target)&&!M)return;const ee=gr(Ce),re=Object.entries(ee).filter(([He,os])=>!!os&&(He==="splitActiveTabRight"||He==="splitActiveTabDown"||He==="floatActiveTab"||He==="popoutActiveTab"||He==="dockActiveTab"||He==="focusLeftPane"||He==="focusRightPane"||He==="focusUpPane"||He==="focusDownPane"||He==="moveActiveTabToLeftPane"||He==="moveActiveTabToRightPane"||He==="moveActiveTabToUpPane"||He==="moveActiveTabToDownPane"||He==="selectPreviousGroupTab"||He==="selectNextGroupTab"||He==="setActiveTabShortcut"||He==="hideCurrentTab")),ce=M?[Ue]:[...O.slice(-1),Ue].slice(-2),Pe=ce.join(" "),Me=ce[ce.length-1],Oe=re.find(([,He])=>He===Pe);if(Oe){De.preventDefault(),Se(),dt(Oe[0]);return}if(re.some(([,He])=>He.startsWith(`${Pe} `))){De.preventDefault(),O=ce,Ae();return}const Ye=re.find(([,He])=>He===Me);if(Ye){De.preventDefault(),Se(),dt(Ye[0]);return}if(re.some(([,He])=>He.startsWith(`${Me} `))){De.preventDefault(),O=[Me],Ae();return}Se()};return q.addEventListener("keydown",Z),q.addEventListener("keydown",Ie),()=>{Se(),q.removeEventListener("keydown",Z),q.removeEventListener("keydown",Ie)}});return()=>{for(const q of U)q()}},[ze,Ce,$,ge,Le,dt,t]);const Ct=k==="light"?en:tn,pt=((Tt=(bt=(wt=g.current)==null?void 0:wt.activePanel)==null?void 0:bt.group.element)==null?void 0:Tt.ownerDocument)??document;return e.jsxs(ci.Provider,{value:gt,children:[e.jsx("div",{ref:y,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(Wi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${z?" is-showing-dockview-overlay":""}`,components:{conversation:ep,remote:tp},defaultTabComponent:rp,watermarkComponent:sp,onReady:We,singleTabMode:"default",tabAnimation:"smooth",theme:Ct,popoutUrl:"/popout.html"})}),V&&Ls.createPortal(e.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[180px]",style:{left:V.x,top:V.y},children:[ae(V.tabKey)?e.jsxs(e.Fragment,{children:[he(V.tabKey)&&e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{pe(V.tabKey),_(null)},children:[e.jsx(qn,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Dock in window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]}),e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{te(V.tabKey),_(null)},children:[e.jsx(wc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Move back to main window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]})]}):he(V.tabKey)?e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{pe(V.tabKey),_(null)},children:[e.jsx(qn,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Dock back to grid"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.dockActiveTab||""})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{le(V.tabKey),_(null)},children:[e.jsx(kc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Float as panel"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.floatActiveTab||""})]}),e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{ue(V.tabKey),_(null)},children:[e.jsx(vc,{size:13,className:"shrink-0 opacity-70"}),e.jsx("span",{className:"flex-1 min-w-0",children:"Open in new window"}),e.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:I.popoutActiveTab||""})]})]}),e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:B=>{B.stopPropagation(),Be(V.tabKey),_(null)},children:[e.jsx(jc,{size:13,className:"shrink-0 opacity-70"})," ",xe[V.tabKey]?`Change shortcut (${xe[V.tabKey]})`:"Set shortcut"]}),xe[V.tabKey]&&e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{const B={...xe};delete B[V.tabKey],Fe(B),_(null)},children:[e.jsx(vt,{size:13,className:"shrink-0 opacity-70"})," Remove shortcut"]}),e.jsx("div",{className:"border-t border-border-subtle my-1"}),e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{fe(V.tabKey),_(null)},children:[e.jsx(no,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),V.sourceDocument.body),Le&&Ls.createPortal(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:()=>Be(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.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. ",Ce?"⌘+1":"Ctrl+1",", ",Ce?"⌥+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"})]})}),pt.body)]})}const li="adhdev-recent-launch-args-v1",ap=8;function op(t){return String(t||"").trim().replace(/\s+/g," ")}function di(t,s){return`${t.trim()}::${s.trim()}`}function ui(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(li)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function ip(t){if(!(typeof window>"u"))try{window.localStorage.setItem(li,JSON.stringify(t))}catch{}}function pi(t,s){var i;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=ui().byKey[di(r,n)])==null?void 0:i.items)||[]}function mi(t,s,r){var m;const n=String(t||"").trim(),o=String(s||"").trim(),i=op(r);if(!n||!o||!i)return;const c=ui(),d=di(n,o),p=((m=c.byKey[d])==null?void 0:m.items)||[],f=[i,...p.filter(h=>h!==i)].slice(0,ap);c.byKey[d]={items:f},ip(c)}function Vr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function cp(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Ba(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Ka(t){if(!t)return"unknown";const s=Date.now()-t,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function lp(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function dp(t){const s=typeof(t==null?void 0:t.runtimeRecoveryState)=="string"?String(t.runtimeRecoveryState):"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function up(t){switch(t){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function pp(t){var r;const s=new Map;for(const n of t){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function mp({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var V;const[d,p]=a.useState(n||((V=t[0])==null?void 0:V.id)||null),[f,m]=a.useState(""),[h,w]=a.useState(null),[S,I]=a.useState(!1);a.useEffect(()=>{var _;p(n||((_=t[0])==null?void 0:_.id)||null)},[n,t]);const u=a.useMemo(()=>t.find(_=>_.id===d)||t[0]||null,[d,t]),b=a.useMemo(()=>r.filter(_=>{if(_.type==="adhdev-daemon"||_.transport!=="pty")return!1;const C=cp(_.daemonId||_.id);return!!(u!=null&&u.id)&&C===u.id}),[u==null?void 0:u.id,r]),v=Fo(u==null?void 0:u.id,{enabled:!!(u!=null&&u.id),includeSessions:!0,limit:6,intervalMs:1e4}),l=v.diagnostics,N=v.loading,A=v.applyDiagnostics,k=a.useMemo(()=>{const _=new Map;for(const C of b){const T=s.find(z=>z.sessionId===C.sessionId||z.routeId===C.id);C.sessionId&&T&&_.set(C.sessionId,T)}return _},[b,s]),x=a.useCallback(async()=>{if(u!=null&&u.id){I(!0);try{const _=await o(u.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),C=Vr(_);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Could not load session host diagnostics");A(C.diagnostics||C.result||null),m("")}catch(_){const C=_ instanceof Error?_.message:"Could not load session host diagnostics";m(C)}finally{I(!1)}}},[u==null?void 0:u.id,A,o]);a.useEffect(()=>{!(u!=null&&u.id)||l||N||S||x()},[u==null?void 0:u.id,l,N,x,S]);const g=a.useCallback(async(_,C)=>{if(!(u!=null&&u.id)||_==="session_host_stop_session"&&!window.confirm(`Stop ${C.displayName}?
|
|
54
|
-
This will terminate the hosted runtime.`))return;const T=`${_}:${C.sessionId}`;w(T);try{const z=await o(u.id,_,{sessionId:C.sessionId}),L=Vr(z);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const $=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${$}: ${C.displayName}`,"success"),await x()}catch(z){const L=z instanceof Error?z.message:"Session host action failed";m(L),ht.showToast(L,"warning")}finally{w(z=>z===T?null:z)}},[u==null?void 0:u.id,x,o]),y=a.useCallback(async()=>{if(!(!(u!=null&&u.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
55
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){w("session_host_prune_duplicate_sessions");try{const C=await o(u.id,"session_host_prune_duplicate_sessions",{}),T=Vr(C);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const z=T.result||{},L=Array.isArray(z.prunedSessionIds)?z.prunedSessionIds.length:0,$=typeof z.duplicateGroupCount=="number"?z.duplicateGroupCount:0;ht.showToast(`Pruned ${L} duplicate runtime(s) across ${$} group(s)`,"success"),await x()}catch(C){const T=C instanceof Error?C.message:"Duplicate prune failed";m(T),ht.showToast(T,"warning")}finally{w(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[u==null?void 0:u.id,x,o]),j=a.useMemo(()=>[...(l==null?void 0:l.sessions)||[]].sort((_,C)=>(C.lastActivityAt||0)-(_.lastActivityAt||0)),[l==null?void 0:l.sessions]),E=a.useMemo(()=>pp(j),[j]),R=a.useMemo(()=>j.reduce((_,C)=>{var T;return _+(((T=C.attachedClients)==null?void 0:T.length)||0)},0),[j]),K=a.useMemo(()=>[...(l==null?void 0:l.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[l==null?void 0:l.recentLogs]),D=a.useMemo(()=>[...(l==null?void 0:l.recentTransitions)||[]].slice(-3).reverse(),[l==null?void 0:l.recentTransitions]);return e.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:e.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:_=>_.stopPropagation(),children:[e.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(u==null?void 0:u.label)||"No machine selected"}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Hosted CLI runtime recovery and control."})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:()=>{x()},disabled:N||S,"aria-label":"Refresh session host",children:e.jsx(gs,{size:16})}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close session host",children:e.jsx(vt,{size:16})})]})]}),t.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:t.map(_=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${_.id===(u==null?void 0:u.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>p(_.id),children:_.label},_.id))}),e.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[f&&!l&&e.jsx("div",{className:"rounded-2xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-4 py-3 text-[12px] text-amber-100",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ts,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Session host unavailable"}),e.jsx("div",{className:"mt-1 text-amber-200/90",children:f})]})]})}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:l.runtimeCount})]}),e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Clients"}),e.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:R})]}),e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),e.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:Ka(l.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Ba(l.hostStartedAt)})]})]}),K&&e.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[e.jsx(ts,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:K.message})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[e.jsx(wr,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[E>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:h==="session_host_prune_duplicate_sessions",onClick:()=>{y()},children:h==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${E}`}),e.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),j.length===0?e.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No hosted CLI runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:j.map(_=>{var Y,ie;const C=k.get(_.sessionId),T=b.find(je=>je.sessionId===_.sessionId),z=h===`session_host_resume_session:${_.sessionId}`,L=h===`session_host_restart_session:${_.sessionId}`,$=h===`session_host_stop_session:${_.sessionId}`,H=dp(_.meta),se=typeof((Y=_.meta)==null?void 0:Y.runtimeRecoveryError)=="string"?String(_.meta.runtimeRecoveryError):"";return e.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:_.displayName||(T==null?void 0:T.runtimeDisplayName)||(T==null?void 0:T.cliName)||_.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${up(_.lifecycle)}`,children:_.lifecycle}),H&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:H})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:_.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[e.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((ie=_.writeOwner)==null?void 0:ie.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:lp(_.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(hn,{size:11})," ",_.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Ka(_.lastActivityAt),_.osPid?` · pid ${_.osPid}`:""]}),se&&e.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:se})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[C&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(C),c()},children:"Open chat"}),(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{g("session_host_resume_session",_)},children:z?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{g("session_host_restart_session",_)},children:L?"Restarting…":"Restart"}),(_.lifecycle==="running"||_.lifecycle==="starting"||_.lifecycle==="interrupted")&&e.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!h,onClick:()=>{g("session_host_stop_session",_)},children:$?"Stopping…":"Stop"})]})]},_.sessionId)})}),D.length>0&&e.jsxs("div",{className:"pb-1",children:[e.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),e.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:D.map(_=>{const C=j.find(T=>T.sessionId===_.sessionId);return e.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(C==null?void 0:C.displayName)||_.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Ba(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]})]})]})]})})}function Gr(t){var n;if(!t)return null;const s=t.availableProviders||[];return s.some(o=>o.category==="cli"&&o.installed!==!1)?"cli":(((n=t.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(o=>o.category==="acp"&&o.installed!==!1)?"acp":null}function rr(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fp({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:d,onListSavedSessions:p,sendDaemonCommand:f,onOpenConversation:m}){var ut,it;const h=Hs(),w=a.useMemo(()=>[...t].sort(wn),[t]),[S,I]=a.useState(((ut=w[0])==null?void 0:ut.id)||""),u=a.useMemo(()=>w.find(Q=>Q.id===S)||w[0],[S,w]),b=a.useMemo(()=>((u==null?void 0:u.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[u]),v=(u==null?void 0:u.defaultWorkspaceId)||null,[l,N]=a.useState(""),[A,k]=a.useState(""),[x,g]=a.useState(Gr(w[0])),[y,j]=a.useState(""),[E,R]=a.useState(""),[K,D]=a.useState([]),[V,_]=a.useState(""),[C,T]=a.useState([]),[z,L]=a.useState(!1),[$,H]=a.useState(""),[se,Y]=a.useState(!1),[ie,je]=a.useState(!1),[G,oe]=a.useState(null),[W,be]=a.useState(!1),[X,ue]=a.useState(""),[te,ae]=a.useState(!1),[fe,le]=a.useState(""),[he,J]=a.useState([]),[pe,ne]=a.useState(!1),[we,ge]=a.useState(""),[P,ye]=a.useState(!1),F=a.useRef(null),me=a.useRef(0);a.useEffect(()=>{var Q;!S&&((Q=w[0])!=null&&Q.id)&&I(w[0].id)},[S,w]),a.useEffect(()=>{!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||h(u.id,{minFreshMs:3e4}).catch(()=>{})},[h,u]);const Ce=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(Q=>Q.category==="cli"&&Q.installed!==!1),[u]),xe=a.useMemo(()=>((u==null?void 0:u.availableProviders)||[]).filter(Q=>Q.category==="acp"&&Q.installed!==!1),[u]),Le=a.useMemo(()=>((u==null?void 0:u.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[u]),Be=a.useMemo(()=>x==="cli"?Ce.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):x==="acp"?xe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):Le,[xe,x,Ce,Le]);a.useEffect(()=>{var _e;if(!u)return;if(F.current!==u.id){F.current=u.id,N(v||((_e=b[0])==null?void 0:_e.id)||"__home__"),k(""),g(Gr(u)),j(""),R(""),_(""),T([]),H(""),ue("");return}N(Re=>{var We;return Re==="__custom__"||Re==="__home__"||b.some(Ct=>Ct.id===Re)?Re:v||((We=b[0])==null?void 0:We.id)||"__home__"}),g(Re=>Re==="ide"&&Le.length>0||Re==="cli"&&Ce.length>0||Re==="acp"&&xe.length>0?Re:Gr(u))},[xe.length,Ce.length,v,Le.length,u,b]),a.useEffect(()=>{var Q;x&&(Be.some(_e=>_e.id===y)||j(((Q=Be[0])==null?void 0:Q.id)||""))},[x,Be,y]);const Fe=a.useCallback(async(Q,_e)=>{const Re=me.current+1;return me.current=Re,L(!0),H(""),p(Q,_e).then(We=>{me.current===Re&&T(We)}).catch(We=>{me.current===Re&&(T([]),H(We instanceof Error?We.message:"Could not load saved sessions"))}).finally(()=>{me.current===Re&&L(!1)})},[p]),st=a.useCallback((Q,_e)=>{D(pi(Q,_e))},[]);a.useEffect(()=>{if(_(""),!u||!y||x==="ide"?D([]):st(u.id,y),x!=="cli"){T([]),H(""),L(!1);return}if(!u||!y){T([]),H(""),L(!1);return}Fe(u.id,y)},[x,st,Fe,u,y]),a.useEffect(()=>{if(!V)return;const Q=C.find(_e=>_e.providerSessionId===V);Q!=null&&Q.canResume||_("")},[C,V]);const ze=l==="__custom__"?A.trim():l==="__home__"?"":((it=b.find(Q=>Q.id===l))==null?void 0:it.path)||"",dt=a.useCallback(Q=>{const _e=String(Q.workspace||"").trim();if(!_e)return;const Re=b.find(We=>rr(We.path)===rr(_e));if(Re){N(Re.id),k("");return}N("__custom__"),k(_e)},[b]),gt=a.useCallback(Q=>{const _e=String(Q.workspace||"").trim();if(!_e)return{workspaceId:null,workspacePath:null};const Re=b.find(We=>rr(We.path)===rr(_e));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:_e}},[b]),Ge=a.useMemo(()=>{var _e;if(x!=="cli"||!u||!y)return null;const Q=((_e=Ce.find(Re=>Re.type===y))==null?void 0:_e.displayName)||y;return{routeId:u.id,daemonId:u.id,providerSessionId:V||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:y,status:"idle",title:Q,messages:[],ideType:y,workspaceName:ze,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${u.id}:${y}`,machineName:kt(u,{fallbackId:u.id})}},[x,Ce,ze,u,V,y]),at=a.useCallback(()=>{var _e,Re;if(!u)return;N("__custom__"),ae(!0),ge("");const Q=Cr(u.platform,[A.trim(),ze,(_e=b.find(We=>We.id===v))==null?void 0:_e.path,(Re=b[0])==null?void 0:Re.path]);ne(!0),o(u.id,Q).then(We=>{le(We.path),k(We.path),J(We.directories)}).catch(We=>{ge(We instanceof Error?We.message:"Could not load folder")}).finally(()=>ne(!1))},[A,v,o,ze,u,b]),ot=a.useCallback(Q=>{u&&(ne(!0),ge(""),o(u.id,Q).then(_e=>{le(_e.path),k(_e.path),J(_e.directories)}).catch(_e=>{ge(_e instanceof Error?_e.message:"Could not load folder")}).finally(()=>ne(!1)))},[o,u]),Ke=a.useCallback(async()=>{if(!u||!ze)return;ye(!0),ue("");const Q=await i(u.id,ze);if(ye(!1),!Q.ok){ue(Q.error||"Could not save workspace");return}ue("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,ze,u]),ct=a.useCallback(async()=>{if(!u||!x||!y)return;be(!0),ue("");const Q=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],_e=x==="ide"?await c(u.id,y,{workspacePath:ze||null}):await d(u.id,x,y,{workspaceId:l!=="__home__"&&l!=="__custom__"?l:null,workspacePath:l==="__custom__"&&ze||null,resumeSessionId:x==="cli"&&V?V:null,cliArgs:Q});if(be(!1),!_e.ok){ue(_e.error||"Could not start session");return}x!=="ide"&&E.trim()&&(mi(u.id,y,E),st(u.id,y)),n()},[x,E,st,n,c,d,ze,u,V,y,l]);return u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/60 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:e.jsxs("div",{className:"w-full max-w-3xl max-h-[min(88vh,860px)] rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"New session"}),e.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine, choose a workspace, then start IDE, CLI, or ACP without leaving the dashboard."})]}),e.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:n,"aria-label":"Close new session dialog",children:e.jsx(vt,{size:16})})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Machine"}),e.jsx("select",{value:u.id,onChange:Q=>I(Q.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W,children:w.map(Q=>e.jsx("option",{value:Q.id,children:kt(Q,{fallbackId:Q.id})},Q.id))})]}),x==="cli"&&e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Session Host"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Inspect hosted runtimes first, then resume or restart without leaving this flow."})]}),e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u,onClick:()=>je(!0),children:[e.jsx(Ut,{size:14}),"Open"]})]})}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Workspace"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Saved workspace is preferred. Home and custom folders are still available."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:W,children:"Browse…"})]}),e.jsxs("select",{value:l,onChange:Q=>{const _e=Q.target.value;N(_e),_e==="__custom__"?at():ue("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W,children:[e.jsx("option",{value:"__home__",children:"Home directory"}),b.map(Q=>e.jsxs("option",{value:Q.id,children:[Q.id===v?"⭐ ":"",kr(Q.path,Q.label)||Q.path]},Q.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l==="__home__"?"Launch without a workspace.":ze||"Select a workspace folder."}),l==="__custom__"&&ze&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:at,disabled:W,children:[e.jsx(xs,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ke,disabled:W||P,children:P?"Saving…":"Save workspace"})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ce.length>0},{id:"ide",label:"IDE",enabled:Le.length>0},{id:"acp",label:"ACP",enabled:xe.length>0}].map(Q=>e.jsx("button",{type:"button",className:`btn btn-sm ${x===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>g(Q.id),disabled:!Q.enabled||W,children:Q.label},Q.id))})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:x==="ide"?"Choose IDE":x==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Be.map(Q=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>j(Q.id),disabled:W,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),Be.length===0&&e.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),x!=="ide"&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Startup arguments"}),e.jsx("input",{type:"text",value:E,onChange:Q=>R(Q.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W}),K.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:K.map(Q=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>R(Q),disabled:W,title:Q,children:Q},Q))})]}),x==="cli"&&e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume from history"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Pick a saved CLI session, then launch with optional args."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u||!y||z,onClick:()=>{!u||!y||Fe(u.id,y)},children:z?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:W||!u||!y,onClick:()=>{!u||!y||(Y(!0),Fe(u.id,y))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:V,onChange:Q=>{const _e=Q.target.value;if(_(_e),!_e)return;const Re=C.find(We=>We.providerSessionId===_e);!Re||!Re.canResume||dt(Re)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:W||z,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),C.map(Q=>e.jsxs("option",{value:Q.providerSessionId,disabled:!Q.canResume,children:[Q.title||Q.providerSessionId,Q.canResume?"":" (workspace missing)"]},Q.providerSessionId))]})}),V&&(()=>{const Q=C.find(_e=>_e.providerSessionId===V);return Q?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:Q.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[Q.workspace||"Workspace unknown",Q.currentModel?` · ${Q.currentModel}`:""]})]}):null})(),$&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:$}),!z&&!$&&C.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),X&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:X})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[e.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:W,children:"Cancel"}),e.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:ct,disabled:W||!x||!y||l==="__custom__"&&!ze,children:[e.jsx(gn,{size:14}),W?"Starting…":"Start session"]})]})]})}),te&&e.jsx(Ar,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:fe,directories:he,busy:pe,error:we,onClose:()=>ae(!1),onNavigate:ot,onConfirm:Q=>{k(Q),le(Q),N("__custom__"),ae(!1)}}),se&&Ge&&e.jsx(Cn,{activeConv:Ge,ides:[],isCreatingChat:!1,isRefreshingHistory:z,savedSessions:C,isSavedSessionsLoading:z,isResumingSavedSessionId:G,onClose:()=>Y(!1),onNewChat:()=>{_(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!u||!y||Fe(u.id,y)},onResumeSavedSession:Q=>{if(!u||!y||G||!Q.canResume)return;const _e=gt(Q);_(Q.providerSessionId),dt(Q),oe(Q.providerSessionId),Y(!1),be(!0),ue(""),d(u.id,"cli",y,{workspaceId:_e.workspaceId,workspacePath:_e.workspacePath,resumeSessionId:Q.providerSessionId}).then(Re=>{if(!Re.ok){ue(Re.error||"Could not resume session");return}n()}).finally(()=>{be(!1),oe(Re=>Re===Q.providerSessionId?null:Re)})}}),ie&&u&&e.jsx(mp,{machineCards:[{id:u.id,label:kt(u,{fallbackId:u.id}),subtitle:[u.platform||"machine",ei(u)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:u.id,sendDaemonCommand:f,onOpenConversation:Q=>{je(!1),n(),m(Q)},onClose:()=>je(!1)})]}):null}function xp(t){switch(t.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function hp(t){return t instanceof Error?t.message:String(t||"")}function bp(t){const s=hp(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function gp({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:d,onStopCli:p,activeCliViewMode:f,onSetActiveCliViewMode:m,mobileChatConversations:h,hiddenConversations:w,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:l,initialDataLoaded:N,userName:A,requestedMobileTabKey:k,onRequestedMobileTabConsumed:x,requestedMachineId:g,onRequestedMachineConsumed:y,requestedMobileSection:j,onRequestedMobileSectionConsumed:E,containerRef:R,isSplitMode:K,numGroups:D,groupSizes:V,groupedConvs:_,clearedTabs:C,focusedGroup:T,setFocusedGroup:z,moveTabToGroup:L,splitTabRelative:$,closeGroup:H,handleResizeStart:se,detectedIdes:Y,handleLaunchIde:ie,groupActiveTabIds:je,setGroupActiveTabIds:G,groupTabOrders:oe,setGroupTabOrders:W,toggleHiddenTab:be,visibleConversations:X,requestedDesktopTabKey:ue,onRequestedDesktopTabConsumed:te,onDesktopActiveTabChange:ae,onHideConversation:fe,onShowHiddenConversation:le,onShowAllHiddenConversations:he,scrollToBottomRequest:J,machineEntries:pe,onBrowseMachineDirectory:ne,onSaveMachineWorkspace:we,onLaunchMachineIde:ge,onLaunchMachineProvider:P,onListMachineSavedSessions:ye}){const F=et.useRef(null),[me,Ce]=et.useState(!1),[xe,Le]=et.useState(!1),[Be,Fe]=et.useState(!1),[st,ze]=et.useState(!1),dt=et.useCallback(Z=>{var Ie;Ls.flushSync(()=>{le(Z)}),(Ie=F.current)==null||Ie.restoreHiddenTabToSavedLocation(Z.tabKey)},[le]),[gt,Ge]=et.useState(!1),[at,ot]=et.useState("quickstart"),[Ke,ct]=et.useState("workspace"),ut=!t&&!s,it=et.useCallback(Z=>{Ce(Z),Z&&Le(!1)},[]),Q=et.useCallback(Z=>{Le(Z),Z&&Ce(!1)},[]),_e=et.useCallback(()=>{var Ie;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ie=F.current)==null||Ie.resetAllPanelsToMain(),Le(!1))},[]),Re=et.useCallback(()=>{ot(X.length===0?"quickstart":"shortcuts"),ct("workspace"),Fe(!0),Ce(!1),Le(!1)},[X.length]),We=et.useCallback(async Z=>{var ee;if(!r)return;const Ie=(ee=r.modalButtons)==null?void 0:ee[Z];if(!Ie)return;const De=Bs(r);if(!De)return;const Ue=Ie.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),M=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ue);try{await u(De,"resolve_action",{button:Ie,action:M?"approve":"reject",buttonIndex:Z,...fs(r)})}catch(re){bp(re)||console.error("[Shortcut approval] Failed:",re)}},[r,u]),{isMac:Ct,actionDefinitions:pt,actionShortcuts:wt,shortcutListening:bt,shortcutListeningDraft:Tt,setShortcutListening:B,setShortcutListeningDraft:U,saveShortcuts:q}=Xu({enabled:ut&&!Be,onTrigger:Z=>{var Ie,De,Ue,M,ee,re,ce,Pe,Me,Oe,rt,Ye,qe,He,os,Us;if(Z==="openShortcutHelp"){Re();return}if(Z==="hideCurrentTab"){r&&fe(r);return}if(Z==="toggleHiddenTabs"){Q(!xe);return}if(Z==="openHistoryForActiveTab"){r&&!Ve(r)&&c(r);return}if(Z==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ve(r)&&d(r);return}if(Z==="splitActiveTabRight"){(Ie=F.current)==null||Ie.splitActiveTabRight();return}if(Z==="splitActiveTabDown"){(De=F.current)==null||De.splitActiveTabDown();return}if(Z==="floatActiveTab"){(Ue=F.current)==null||Ue.floatActiveTab();return}if(Z==="popoutActiveTab"){(M=F.current)==null||M.popoutActiveTab();return}if(Z==="dockActiveTab"){(ee=F.current)==null||ee.dockActiveTab();return}if(Z==="focusLeftPane"){(re=F.current)==null||re.focusLeftPane();return}if(Z==="focusRightPane"){(ce=F.current)==null||ce.focusRightPane();return}if(Z==="focusUpPane"){(Pe=F.current)==null||Pe.focusUpPane();return}if(Z==="focusDownPane"){(Me=F.current)==null||Me.focusDownPane();return}if(Z==="moveActiveTabToLeftPane"){(Oe=F.current)==null||Oe.moveActiveTabToLeftPane();return}if(Z==="moveActiveTabToRightPane"){(rt=F.current)==null||rt.moveActiveTabToRightPane();return}if(Z==="moveActiveTabToUpPane"){(Ye=F.current)==null||Ye.moveActiveTabToUpPane();return}if(Z==="moveActiveTabToDownPane"){(qe=F.current)==null||qe.moveActiveTabToDownPane();return}if(Z==="triggerPrimaryApprovalAction"){We(0);return}if(Z==="triggerSecondaryApprovalAction"){We(1);return}if(Z==="triggerTertiaryApprovalAction"){We(2);return}if(Z==="setActiveTabShortcut"){(He=F.current)==null||He.setShortcutForActiveTab();return}if(Z==="selectPreviousGroupTab"){(os=F.current)==null||os.activatePreviousTabInGroup();return}if(Z==="selectNextGroupTab"){(Us=F.current)==null||Us.activateNextTabInGroup();return}!r||!Xe(r)||Ve(r)||Z==="toggleCliView"&&m(f==="chat"?"terminal":"chat")}}),O=et.useCallback(()=>{Fe(!1),B(null),U([])},[B,U]),de=et.useMemo(()=>Ke==="all"?pt:pt.filter(Z=>xp(Z)===Ke),[pt,Ke]),Se=et.useCallback(()=>{const Z=Object.fromEntries(pt.map(Ie=>[Ie.id,""]));q(Z)},[pt,q]),Ae=et.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Z=Object.fromEntries(pt.map(Ie=>[Ie.id,Ie.defaultShortcut]));q(Z)},[pt,q]);return et.useEffect(()=>{const Z=Ie=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ie.metaKey&&Ie.key.toLowerCase()==="w":Ie.ctrlKey&&Ie.key.toLowerCase()==="w")&&(Ie.preventDefault(),r&&fe&&fe(r))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[r,fe]),et.useEffect(()=>{if(!Be||bt)return;const Z=Ie=>{Ie.key==="Escape"&&(Ie.preventDefault(),O())};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[O,Be,bt]),et.useEffect(()=>{if(!ut){Ge(!1);return}Ge(!0);const Z=window.setTimeout(()=>{Ge(!1)},1e4);return()=>window.clearTimeout(Z)},[ut]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(El,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:X,hiddenConversations:w,onOpenHistory:c,onOpenConversation:dt,onHideConversation:fe,onShowConversation:dt,onShowAllHidden:he,onResetPanelsToMain:_e,inboxOpen:me,onInboxOpenChange:it,hiddenOpen:xe,onHiddenOpenChange:Q,onOpenNewSession:s?void 0:()=>ze(!0),actionShortcuts:wt,onOpenRemote:()=>{!r||Xe(r)||Ve(r)||d(r)},onStopCli:p,activeCliViewMode:f,onSetCliViewMode:m}),t?e.jsx(Bu,{conversations:h,hiddenConversations:w,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:l,userName:A,requestedActiveTabKey:k,onRequestedActiveTabConsumed:x,requestedMachineId:g,onRequestedMachineConsumed:y,requestedMobileSection:j,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:d,onStopCli:p,wsStatus:o,isConnected:i,onShowHiddenConversation:dt,onShowAllHiddenConversations:he,onOpenNewSession:()=>ze(!0)}):s?e.jsx(Vu,{containerRef:R,isSplitMode:K,numGroups:D,groupSizes:V,groupedConvs:_,clearedTabs:C,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:l,hasRegisteredMachines:pe.length>0,userName:A,focusedGroup:T,setFocusedGroup:z,moveTabToGroup:L,splitTabRelative:$,closeGroup:H,handleResizeStart:se,detectedIdes:Y,handleLaunchIde:ie,groupActiveTabIds:je,setGroupActiveTabIds:G,groupTabOrders:oe,setGroupTabOrders:W,toggleHiddenTab:be,allowTabShortcuts:!1}):e.jsx(np,{visibleConversations:X,clearedTabs:C,ides:S,actionLogs:I,sendDaemonCommand:u,setLocalUserMessages:b,setActionLogs:v,isStandalone:l,hasRegisteredMachines:pe.length>0,initialDataLoaded:N,userName:A,detectedIdes:Y,handleLaunchIde:ie,toggleHiddenTab:be,actionShortcuts:wt,registerActionHandlers:Z=>{F.current=Z},onActiveTabChange:ae,requestedActiveTabKey:ue,onRequestedActiveTabConsumed:te,scrollToBottomRequest:J}),st&&e.jsx(fp,{machines:pe,conversations:h,ides:S,onClose:()=>ze(!1),onBrowseDirectory:ne,onSaveWorkspace:we,onLaunchIde:ge,onLaunchProvider:P,onListSavedSessions:ye,sendDaemonCommand:u,onOpenConversation:Z=>{ze(!1),le(Z),ae(Z.tabKey)}}),Be&&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:O,children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Z=>Z.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:O,"aria-label":"Close dashboard guide",children:e.jsx(vt,{size:14})})]}),e.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Z=>e.jsx("button",{type:"button",className:`btn btn-sm ${at===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(Z.id),children:Z.label},Z.id))}),at==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Ct?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),at==="quickstart"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),at==="shortcuts"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Z=>e.jsx("button",{type:"button",className:`btn btn-sm ${Ke===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>ct(Z.id),children:Z.label},Z.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Se,children:"Disable all"}),e.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ae,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:de.map(Z=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${bt===Z.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:Z.defaultShortcut})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:bt===Z.id?Tt.length>0?`${Tt.join(" ")} ...`:"Listening...":wt[Z.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{B(Z.id),U([])},children:bt===Z.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ie={...wt};Ie[Z.id]="",q(Ie)},children:"Disable"})]})]})},Z.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ct?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:Re,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${gt?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),gt&&e.jsx("span",{children:"Guide"})]})]})}const qr=[{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 yp({onClose:t}){const[s,r]=a.useState(0),n=qr[s],o=s===qr.length-1;return e.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.target===i.currentTarget&&t()},children:[e.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[e.jsx("button",{onClick:t,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:e.jsx(vt,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:qr.map((i,c)=>e.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),e.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),e.jsxs("div",{style:{textAlign:"center"},children:[e.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[e.jsx("span",{children:n.icon})," ",n.title]}),e.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&e.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[e.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),o&&e.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),e.jsxs("div",{className:"flex justify-between items-center mt-6",children:[e.jsx("button",{onClick:t,className:"btn btn-secondary border-none",children:"Skip"}),e.jsx("button",{onClick:()=>o?t():r(i=>i+1),className:"btn btn-primary",children:o?"Get Started →":"Next →"})]})]}),e.jsx("style",{children:`
|
|
56
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
57
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
58
|
-
`})]})}function vp({hasExtensions:t,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:o}){return t?e.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[e.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:s}),n.map(i=>{const c=r===i.tabKey,d=i.status==="waiting_approval",p=i.status==="generating";return e.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(i.tabKey),children:[e.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:d?"var(--status-warning)":p?"var(--accent-primary)":"var(--text-muted)",boxShadow:p?"0 0 6px var(--accent-primary)":"none"}}),i.title,d&&e.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function wp({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,d]=a.useState(()=>i||"native"),p=a.useMemo(()=>Mo(s),[s]),f=a.useMemo(()=>t?In(t,n,{machineNames:p,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,p,r]),m=a.useMemo(()=>f.find(b=>b.streamSource==="native"),[f]),h=a.useMemo(()=>f.filter(b=>b.streamSource==="agent-stream"),[f]),w=a.useMemo(()=>t?Dt(f,t.id):null,[f,t]);a.useEffect(()=>{i&&d(i)},[i]),a.useEffect(()=>{if(i||!w)return;const b=w.streamSource==="native"?"native":w.tabKey;!b||c===b||c==="native"&&d(b)},[c,w,i]),a.useEffect(()=>{var b;c!=="native"&&(h.some(v=>v.tabKey===c)||d(((b=h[0])==null?void 0:b.tabKey)||"native"))},[c,h]),a.useEffect(()=>{c==="native"&&(m||h[0]&&d(h[0].tabKey))},[c,m,h]);const S=a.useMemo(()=>c==="native"&&m?m:h.find(b=>b.tabKey===c)||w||m||h[0],[c,m,w,h]),I=a.useMemo(()=>h.map(b=>({tabKey:b.tabKey,title:So(b)||o,status:b.status})),[h,o]),u=a.useCallback(b=>{if(b)return f.find(v=>v.sessionId===b||v.routeId===b||v.tabKey===b)},[f]);return{activeChatTab:c,setActiveChatTab:d,activeConv:S,conversations:f,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:u}}function jp({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:p,isStandalone:f,userName:m,onOpenHistory:h,onConversationChange:w,onClose:S}){const[I,u]=a.useState("split"),[b,v]=a.useState(()=>Bt(t)?"native":t.tabKey),l=a.useRef(null),N=a.useMemo(()=>s||r.find(L=>L.id===t.routeId),[t.routeId,s,r]),A=a.useMemo(()=>Ze((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:k,extensionTabs:x,hasExtensions:g}=wp({ideData:N,allIdes:r,connectionStates:n,localUserMessages:i,ideName:A||"IDE",preferredTabKey:Bt(t)?void 0:t.tabKey}),y=a.useMemo(()=>N?Dt(k,N.id):null,[N,k]);a.useEffect(()=>{const L=l.current,$={routeId:t.routeId,tabKey:t.tabKey,streamSource:t.streamSource};if(l.current=$,!(L&&L.routeId===$.routeId&&L.tabKey===$.tabKey&&L.streamSource===$.streamSource)){if(Bt(t)){v("native");return}v(t.tabKey)}},[t.routeId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(b==="native"){if(k.some(L=>L.streamSource==="native"))return;(y==null?void 0:y.streamSource)==="agent-stream"&&v(y.tabKey);return}if(!k.some(L=>L.tabKey===b)){if((y==null?void 0:y.streamSource)==="agent-stream"){v(y.tabKey);return}v("native")}},[k,b,y]);const j=a.useMemo(()=>b==="native"?k.find(L=>L.streamSource==="native")||t:k.find(L=>L.tabKey===b)||t,[t,k,b]),E=Vo(j),R=a.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...j,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:j,[j,E]),K=mr(R),D=Sr({sendDaemonCommand:c,activeConv:R,setLocalUserMessages:d,setActionLogs:p,isStandalone:f}),{connScreenshot:V,screenshotUsage:_,handleRemoteAction:C}=ni({doId:K,targetSessionId:Nn(R),connState:R.connectionState||"new",viewMode:I}),T=a.useMemo(()=>o.filter(L=>L.routeId===R.tabKey),[o,R.tabKey]);a.useEffect(()=>{w==null||w(R)},[R,w]),a.useEffect(()=>{const L=$=>{$.key==="Escape"&&S()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[S]);const z=a.useCallback(L=>{L.stopPropagation()},[]);return e.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:S,children:e.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:z,children:[e.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[e.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[e.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:e.jsx(Nt,{size:16})}),e.jsx("span",{className:"truncate",children:Nr(j)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:S,children:"Close"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[e.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(L=>{const $=I===L;return e.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${$?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>u(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?e.jsx(cc,{size:15}):e.jsx(Nt,{size:15})},L)})}),e.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),e.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>h(j),title:"Chat History",children:[e.jsx(bn,{size:14,className:"md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:"History"})]}),e.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:S,children:"Close"})]})]}),e.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${I==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[I!=="remote"&&e.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${I==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[e.jsx(vp,{hasExtensions:g,ideName:A||"IDE",activeChatTab:b,extensionTabs:x,onSelectTab:v}),e.jsx(po,{activeConv:R,onModalButton:D.handleModalButton}),e.jsx(nn,{activeConv:R,ideEntry:N,showMetaChips:!1,handleSendChat:D.handleSendChat,isSendingChat:D.isSendingChat,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:T,userName:m})]}),e.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${I==="split"?"order-1 md:order-2":""}`,children:e.jsx(lo,{addLog:()=>{},connState:R.connectionState||"new",connScreenshot:V,screenshotUsage:_,transportType:R.transport,onAction:C})})]})]})})}function kp({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Ml(t);return e.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-center justify-center p-4",children:[e.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] flex flex-col overflow-hidden rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[e.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[e.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),e.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),e.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&e.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),e.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),e.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Np({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:p,onNewHistoryChat:f,onSwitchHistorySession:m,onRefreshHistory:h,onResumeSavedHistorySession:w,remoteDialogConv:S,remoteDialogIdeEntry:I,connectionStates:u,actionLogs:b,localUserMessages:v,sendDaemonCommand:l,setLocalUserMessages:N,setActionLogs:A,isStandalone:k,userName:x,onOpenRemoteHistory:g,onRemoteConversationChange:y,onCloseRemoteDialog:j,cliStopDialogOpen:E,cliStopTargetConv:R,onCancelCliStop:K,onStopCliNow:D,onSaveCliAndStop:V,toasts:_,onDismissToast:C,onClickToast:T,showOnboarding:z,onCloseOnboarding:L}){var $;return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx(Cn,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:d,onClose:p,onNewChat:f,onSwitchSession:m,onRefreshHistory:h,onResumeSavedSession:w}),S&&e.jsx(jp,{activeConv:S,ideEntry:I,ides:r,connectionStates:u,actionLogs:b,localUserMessages:v,sendDaemonCommand:l,setLocalUserMessages:N,setActionLogs:A,isStandalone:k,userName:x,onOpenHistory:g,onConversationChange:y,onClose:j}),E&&R&&(Xe(R)||Ve(R))&&e.jsx(kp,{activeConv:R,canSaveAndStop:Xe(R)&&!Ve(R)&&!!(($=R.resume)!=null&&$.supported),onCancel:K,onStopNow:D,onSaveAndStop:V}),e.jsx(Ao,{toasts:_,onDismiss:C,onClickToast:T}),z&&e.jsx(yp,{onClose:L})]})}function Sp({daemons:t,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:o,onDismiss:i}){return t.length===0?null:e.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[e.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:e.jsx(gs,{size:14})}),e.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[e.jsxs("span",{children:[r?"Daemon update required":"Update available",s?e.jsxs(e.Fragment,{children:[": ",e.jsxs("strong",{children:["v",s]})]}):null]}),t.map(c=>{const d=kt(c,{fallbackId:c.id}),p=n[c.id],f=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[e.jsx("span",{className:"font-medium text-text-primary",children:d}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),m&&e.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),p==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:m?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):p==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):p==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:m?"Update now":"Upgrade"})]},c.id)})]}),!r&&e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:e.jsx(vt,{size:16})})]})}function Cp(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function Wa(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ip(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ap(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Mp(){var Wn,On,Hn,Un,zn;const{sendCommand:t}=St(),s=Hs(),r=fn(),n=bs(),[o,i]=Oi(),c=o.get("activeTab"),d=((Wn=r.state)==null?void 0:Wn.openRemoteForTabKey)||null,p=((On=r.state)==null?void 0:On.openMachineId)||null,f=((Hn=r.state)==null?void 0:Hn.mobileSection)||null,m=wo(),h=m.ides||[],w=m.initialLoaded??!0,{updateRouteChats:S,setToasts:I}=m,[u,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),v=m.toasts||[],l=m.wsStatus||"connected",N=m.isConnected??!0,A=m.connectionStates||{},k=m.showReconnected||!1,{groupAssignments:x,setGroupAssignments:g,focusedGroup:y,setFocusedGroup:j,groupActiveTabIds:E,setGroupActiveTabIds:R,groupTabOrders:K,setGroupTabOrders:D,groupSizes:V,setGroupSizes:_,isMobile:C,hasHydratedStoredLayout:T,hydrateStoredLayout:z}=pu(),[L,$]=a.useState(!1),[H,se]=a.useState(!1),[Y,ie]=a.useState(null),[je,G]=a.useState([]),[oe,W]=a.useState(!1),[be,X]=a.useState(null),[ue]=a.useState(()=>zo()),[te,ae]=a.useState([]),[fe,le]=a.useState({}),[he,J]=a.useState({}),[pe,ne]=a.useState(null),[we,ge]=a.useState(null),[P,ye]=a.useState(null),F=a.useRef(null);Ks("Dashboard",{ideCount:h.length,toastCount:v.length,focusedGroup:y,groupCount:Object.keys(x).length,localMessageTabs:Object.keys(fe).length,actionLogCount:te.length});const me=h.find(ve=>ve.type==="adhdev-daemon"),Ce=(me==null?void 0:me.detectedIdes)||[],xe=a.useMemo(()=>h.filter(ve=>ve.type==="adhdev-daemon").sort(wn),[h]),Le=!!me;a.useEffect(()=>{!me||!(!me.detectedIdes||!me.availableProviders||!me.recentLaunches||!me.workspaces)||s(me.id,{minFreshMs:3e4}).catch(()=>{})},[me,s]);const Be=(me==null?void 0:me.terminalBackend)||null,Fe=me?kt(me,{fallbackId:me.id}):null,st=(me==null?void 0:me.id)||null,{hiddenTabs:ze,hideTab:dt,toggleTab:gt,showTab:Ge,showAllTabs:at}=Fd(),{chatIdes:ot,conversations:Ke,visibleConversations:ct,visibleTabKeys:ut,resolveConversationBySessionId:it,resolveConversationByTarget:Q}=Qd({ides:h,connectionStates:A,localUserMessages:fe,clearedTabs:he,hiddenTabs:ze}),_e=a.useMemo(()=>Ws(h),[h]),Re=a.useRef(null),{containerRef:We,normalizedGroupAssignments:Ct,numGroups:pt,isSplitMode:wt,groupedConvs:bt,moveTabToGroup:Tt,closeGroup:B,handleResizeStart:U,splitTabRelative:q}=vu({groupAssignments:x,setGroupAssignments:g,setFocusedGroup:j,setGroupActiveTabIds:R,setGroupTabOrders:D,groupSizes:V,setGroupSizes:_,isMobile:C,visibleConversations:ct,visibleTabKeys:ut}),O=a.useMemo(()=>{var Te,Ne;if(!C){if(pe){const ke=Ke.find($e=>$e.tabKey===pe);if(ke)return ke}return ct[0]}const ve=E[y];if(ve){const ke=Ke.find($e=>$e.tabKey===ve);if(ke)return ke}return((Te=bt[y])==null?void 0:Te[0])||((Ne=bt[0])==null?void 0:Ne[0])},[pe,C,E,y,Ke,bt,ct]);a.useEffect(()=>{if(C){Re.current=null;return}if(!(O!=null&&O.sessionId)){Re.current=null;return}const ve=`${O.tabKey}:${O.sessionId}`;if(Re.current===ve)return;const Te=()=>{if(document.visibilityState!=="visible"||Re.current===ve)return;Re.current=ve;const Ne=Ds(O,_e),ke=Math.max(Date.now(),Ht(O),Ne.lastUpdated||0);t(O.daemonId||O.routeId,"mark_session_seen",{sessionId:O.sessionId,seenAt:ke}).catch(()=>{})};if(document.visibilityState==="visible"){const Ne=setTimeout(Te,1500),ke=()=>{document.visibilityState!=="visible"&&clearTimeout(Ne)};return document.addEventListener("visibilitychange",ke),()=>{clearTimeout(Ne),document.removeEventListener("visibilitychange",ke)}}else{const Ne=()=>{document.visibilityState==="visible"&&(setTimeout(Te,800),document.removeEventListener("visibilitychange",Ne))};return document.addEventListener("visibilitychange",Ne),()=>{document.removeEventListener("visibilitychange",Ne)}}},[O,C,_e,t]);const{requestedDesktopTabKey:de,requestedMobileTabKey:Se,consumeRequestedActiveTab:Ae}=eu({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:it,setSearchParams:i}),{remoteDialogConv:Z,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:De,setRemoteDialogActiveConv:Ue,openRemoteDialog:M,closeRemoteDialog:ee}=xu({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:d,requestedDesktopTabKey:de,conversations:Ke,ides:h,resolveConversationByTarget:Q}),re=De||Z||O,ce=!!re&&Xe(re)&&!Ve(re),Pe=a.useMemo(()=>{if(!re||!ce)return null;const ve=re.daemonId||re.routeId||"",Te=jt(re);return`${ve}:${Te}`},[re,ce]),Me=a.useMemo(()=>ct,[ct]),Oe=C&&ue==="chat",rt=a.useMemo(()=>Ke.filter(ve=>ze.has(ve.tabKey)),[Ke,ze]),Ye=a.useCallback(ve=>{const Te=new URLSearchParams(o);Te.set("activeTab",ve),i(Te,{replace:!0})},[o,i]),qe=a.useCallback(async(ve,Te)=>Ir(t,ve,Te),[t]),He=a.useCallback(async(ve,Te)=>{if(!Te.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ne=await t(ve,"workspace_add",{path:Te.trim()});return Ne!=null&&Ne.success?{ok:!0}:{ok:!1,error:(Ne==null?void 0:Ne.error)||"Could not save workspace"}}catch(Ne){return{ok:!1,error:Ne instanceof Error?Ne.message:"Could not save workspace"}}},[t]),os=a.useCallback(async(ve,Te,Ne)=>{var ke;try{const $e={ideType:Te,enableCdp:!0};(ke=Ne==null?void 0:Ne.workspacePath)!=null&&ke.trim()&&($e.workspace=Ne.workspacePath.trim());const lt=await t(ve,"launch_ide",$e);return!(lt!=null&<.success)&&(lt==null?void 0:lt.success)!==void 0?{ok:!1,error:(lt==null?void 0:lt.error)||"Could not launch IDE"}:(ye({machineId:ve,kind:"ide",providerType:Te,workspacePath:(Ne==null?void 0:Ne.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch($e){return{ok:!1,error:$e instanceof Error?$e.message:"Could not launch IDE"}}},[t]),Us=a.useCallback(async(ve,Te,Ne,ke)=>{var lt,vs,is;const $e=Date.now();try{const _t={cliType:Ne};(lt=ke==null?void 0:ke.workspacePath)!=null&<.trim()?_t.dir=ke.workspacePath.trim():ke!=null&&ke.workspaceId&&(_t.workspaceId=ke.workspaceId),(vs=ke==null?void 0:ke.resumeSessionId)!=null&&vs.trim()&&(_t.resumeSessionId=ke.resumeSessionId.trim()),Array.isArray(ke==null?void 0:ke.cliArgs)&&ke.cliArgs.length>0&&(_t.cliArgs=ke.cliArgs),(is=ke==null?void 0:ke.initialModel)!=null&&is.trim()&&(_t.initialModel=ke.initialModel.trim());const mt=await t(ve,"launch_cli",_t),yt=(mt==null?void 0:mt.result)||mt,ws=(yt==null?void 0:yt.sessionId)||(yt==null?void 0:yt.id);return mt!=null&&mt.success&&ws?(Ye(ws),{ok:!0}):mt!=null&&mt.success?(ye({machineId:ve,kind:Te,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:(mt==null?void 0:mt.error)||(yt==null?void 0:yt.error)||`Could not launch ${Te.toUpperCase()} session`}}catch(_t){return Ip(_t)?(ye({machineId:ve,kind:Te,providerType:Ne,workspacePath:(ke==null?void 0:ke.workspacePath)||null,resumeSessionId:(ke==null?void 0:ke.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:_t instanceof Error?_t.message:`Could not launch ${Te.toUpperCase()} session`}}},[Ye,t]),fi=a.useCallback(async(ve,Te)=>{if(!ve||!Te)return[];try{const Ne=await t(ve,"list_saved_sessions",{providerType:Te,kind:"cli",limit:30}),ke=(Ne==null?void 0:Ne.result)??Ne;return Array.isArray(ke==null?void 0:ke.sessions)?ke.sessions:[]}catch(Ne){return console.error("List saved sessions failed",Ne),[]}},[t]);a.useEffect(()=>{var ke;if(!P)return;const ve=Wa(P.workspacePath),Te=h.find($e=>{var mt,yt,ws,Fn;if(!$e||$e.type==="adhdev-daemon"||Cp($e.daemonId||$e.id)!==P.machineId||($s($e)?"cli":ms($e)?"acp":"ide")!==P.kind||String($e.agentType||$e.type||"")!==P.providerType)return!1;if(P.resumeSessionId)return String($e.providerSessionId||"")===P.resumeSessionId;if(ve){const _r=Wa($e.workspace||$e.runtimeWorkspaceLabel);return _r?_r===ve:!1}return Number($e.lastUpdated||$e._lastUpdate||$e.timestamp||((Fn=(ws=(yt=(mt=$e.activeChat)==null?void 0:mt.messages)==null?void 0:yt.at)==null?void 0:ws.call(yt,-1))==null?void 0:Fn.timestamp)||0)>=P.startedAt-5e3});if(!Te)return;const Ne=typeof Te.sessionId=="string"&&Te.sessionId?Te.sessionId:typeof Te.instanceId=="string"&&Te.instanceId?Te.instanceId:(ke=Ke.find($e=>$e.routeId===Te.id))==null?void 0:ke.sessionId;Ne&&(ye(null),Ye(Ne))},[Ke,Ye,h,P]),a.useEffect(()=>{if(!P)return;const ve=window.setTimeout(()=>{ye(Te=>!Te||Te.startedAt!==P.startedAt?Te:null)},45e3);return()=>window.clearTimeout(ve)},[P]),Vd({visibleConversations:ct,clearedTabs:he,setClearedTabs:J,setActionLogs:ae}),tu({ides:h,sendDaemonCommand:t,setToasts:I,setLocalUserMessages:le,resolveConversationByTarget:Q});const{isRefreshingHistory:xi,handleLaunchIde:hi,handleRefreshHistory:bi}=ka({sendDaemonCommand:t,activeConv:O,chats:(Un=h.find(ve=>ve.id===(O==null?void 0:O.routeId)))==null?void 0:Un.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:le,setClearedTabs:J}),{isCreatingChat:gi,isRefreshingHistory:yi,handleSwitchSession:vi,handleNewChat:wi,handleRefreshHistory:ji}=ka({sendDaemonCommand:t,activeConv:re,chats:(zn=h.find(ve=>ve.id===(re==null?void 0:re.routeId)))==null?void 0:zn.chats,updateRouteChats:S,setToasts:I,setLocalUserMessages:le,setClearedTabs:J}),Tr=a.useCallback(async()=>{if(!(!re||!ce||oe)){W(!0);try{const ve=re.daemonId||re.routeId,Te=jt(re),Ne=await t(ve,"list_saved_sessions",{agentType:Te,providerType:Te,kind:"cli",limit:50}),ke=(Ne==null?void 0:Ne.result)??Ne;G(Array.isArray(ke==null?void 0:ke.sessions)?ke.sessions:[])}catch(ve){console.error("Refresh saved sessions failed",ve),G([])}finally{W(!1)}}},[re,oe,ce,t]);a.useEffect(()=>{if(!L){F.current=null;return}if(!ce){F.current=null,G([]),W(!1);return}!Pe||oe||F.current!==Pe&&(F.current=Pe,Tr())},[Tr,L,oe,ce,Pe]);const ki=a.useCallback(async ve=>{if(!re||!ce||!ve.providerSessionId||!ve.workspace)return;const Te=re.daemonId||re.routeId,Ne=jt(re);try{X(ve.providerSessionId);const ke=await t(Te,"launch_cli",{cliType:Ne,dir:ve.workspace,resumeSessionId:ve.providerSessionId,initialModel:ve.currentModel}),$e=(ke==null?void 0:ke.result)??ke,lt=typeof($e==null?void 0:$e.sessionId)=="string"?$e.sessionId:typeof($e==null?void 0:$e.id)=="string"?$e.id:"";lt&&i(vs=>{const is=new URLSearchParams(vs);return is.set("activeTab",lt),is},{replace:!0}),$(!1)}catch(ke){console.error("Resume saved session failed",ke)}finally{X(null)}},[re,ce,t,i]);fu({urlActiveTab:C&&!Oe?c:null,conversations:Ke,resolveConversationBySessionId:it,normalizedGroupAssignments:Ct,hasHydratedStoredLayout:C&&!Oe?T:!0,hydrateStoredLayout:C&&!Oe?z:()=>{},setGroupActiveTabIds:R,setFocusedGroup:j,setSearchParams:i,historyModalOpen:L,activeConv:O,isRefreshingHistory:xi,ides:h,handleRefreshHistory:bi});const En=a.useCallback(async(ve,Te)=>{const Ne=Te||Y||O;if(!Ne||!Xe(Ne)&&!Ve(Ne))return;const ke=jt(Ne),$e=Ne.routeId||Ne.daemonId||"";try{await t($e,"stop_cli",{cliType:ke,targetSessionId:Ne.sessionId,mode:ve})}catch(lt){console.error("Stop CLI failed:",lt)}},[O,Y,t]),Ni=a.useCallback(async ve=>{const Te=ve||O;!Te||!Xe(Te)&&!Ve(Te)||(ie(Te),se(!0))},[O]),Si=a.useMemo(()=>!O||!Xe(O)||Ve(O)?null:hs(O),[O]),Ci=a.useCallback(async ve=>{if(!(!O||!Xe(O)||Ve(O)||hs(O)===ve))try{await t(zt(O)||O.routeId,"set_cli_view_mode",{targetSessionId:O.sessionId,cliType:jt(O),mode:ve})}catch(Ne){Ap(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},[O,t]),{versionMismatchDaemons:Ii,hasRequiredVersionDaemons:$n,appVersion:Ai,versionBannerDismissed:Mi,setVersionBannerDismissed:Ti,upgradingDaemons:_i,handleBannerUpgrade:Pi}=wu({ides:h,sendDaemonCommand:t}),Bn=a.useCallback(ve=>{ne(ve.tabKey),i(Te=>{const Ne=new URLSearchParams(Te),ke=nl(ve);return ke?Ne.set("activeTab",ke):Ne.delete("activeTab"),Ne},{replace:!0})},[i]),Kn=a.useCallback(ve=>{Ge(ve.tabKey),Bn(ve)},[Bn,Ge]),Li=a.useCallback(ve=>{dt(ve.tabKey)},[dt]);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(_l,{wsStatus:l,showReconnected:k}),e.jsx(Pl,{terminalBackend:Be,isStandalone:Le,machineLabel:Fe,machineKey:st}),(!Mi||$n)&&e.jsx(Sp,{daemons:Ii,targetVersion:Ai,required:$n,upgradingDaemons:_i,onUpgrade:Pi,onDismiss:()=>Ti(!0)}),e.jsx(gp,{showMobileChatMode:Oe,isMobile:C,activeConv:O,chatIdes:ot,wsStatus:l,isConnected:N,onOpenHistory:ve=>{ve&&Ue(ve),$(!0)},onOpenRemote:M,onStopCli:Ni,activeCliViewMode:Si,onSetActiveCliViewMode:Ci,mobileChatConversations:Me,ides:h,actionLogs:te,sendDaemonCommand:t,setLocalUserMessages:le,setActionLogs:ae,isStandalone:Le,initialDataLoaded:w,userName:m.userName,requestedMobileTabKey:Se,onRequestedMobileTabConsumed:Ae,requestedMachineId:p,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:f,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:We,isSplitMode:wt,numGroups:pt,groupSizes:V,groupedConvs:bt,clearedTabs:he,focusedGroup:y,setFocusedGroup:j,moveTabToGroup:Tt,splitTabRelative:q,closeGroup:B,handleResizeStart:U,detectedIdes:Ce,handleLaunchIde:hi,groupActiveTabIds:E,setGroupActiveTabIds:R,groupTabOrders:K,setGroupTabOrders:D,toggleHiddenTab:gt,visibleConversations:ct,hiddenConversations:rt,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:Ae,onDesktopActiveTabChange:ne,onHideConversation:Li,onShowHiddenConversation:Kn,onShowAllHiddenConversations:at,scrollToBottomRequest:we,machineEntries:xe,onBrowseMachineDirectory:qe,onSaveMachineWorkspace:He,onLaunchMachineIde:os,onLaunchMachineProvider:Us,onListMachineSavedSessions:fi}),e.jsx("style",{children:`
|
|
59
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
60
|
-
`}),e.jsx(Np,{historyModalOpen:L,historyTargetConv:re,ides:h,isHistoryCreatingChat:gi,isHistoryRefreshingHistory:ce?!1:yi,savedHistorySessions:je,isSavedHistoryLoading:oe,isResumingSavedHistorySessionId:be,onCloseHistory:()=>$(!1),onNewHistoryChat:wi,onSwitchHistorySession:vi,onRefreshHistory:ce?Tr:ji,onResumeSavedHistorySession:ki,remoteDialogConv:Z,remoteDialogIdeEntry:Ie,connectionStates:A,actionLogs:te,localUserMessages:fe,sendDaemonCommand:t,setLocalUserMessages:le,setActionLogs:ae,isStandalone:Le,userName:m.userName,onOpenRemoteHistory:ve=>{ve&&Ue(ve),$(!0)},onRemoteConversationChange:Ue,onCloseRemoteDialog:ee,cliStopDialogOpen:H,cliStopTargetConv:Y,onCancelCliStop:()=>{se(!1),ie(null)},onStopCliNow:async()=>{se(!1),await En("hard",Y),ie(null)},onSaveCliAndStop:async()=>{se(!1),await En("save",Y),ie(null)},toasts:v,onDismissToast:ve=>I(Te=>Te.filter(Ne=>Ne.id!==ve)),onClickToast:ve=>{if(ve.targetKey){const Te=Q(ve.targetKey);Te&&(j(Ct.get(Te.tabKey)??0),Kn(Te),ge({tabKey:Te.tabKey,nonce:Date.now()}))}},showOnboarding:u,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Tp({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[d,p]=a.useState(null),[f,m]=a.useState(null),[h,w]=a.useState(!1),[S,I]=a.useState(null),[u,b]=a.useState(!1),[v,l]=a.useState(""),N=a.useRef(null),A=a.useCallback(L=>{N.current=L},[]),k=a.useCallback((L,$,H=!1)=>{c(se=>[...se.slice(-100),{timestamp:Date.now(),level:L,message:$}]),setTimeout(()=>{var se;return(se=o.current)==null?void 0:se.scrollIntoView({behavior:"smooth"})},100),H&&ht.showToast($,L==="error"||L==="warn"?"warning":"success")},[o]),x=a.useCallback(L=>{const $=L instanceof Error?L.message:String(L||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),g=a.useCallback(async(L,$)=>{var H;if(!t||d)return!1;p(L),k("info",`Launching ${Ze(L)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const se={ideType:L,enableCdp:!0};(H=$==null?void 0:$.workspace)!=null&&H.trim()?se.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(se.useDefaultWorkspace=!0);const Y=await r(t,"launch_ide",se);return k(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${Ze(L)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(se){return k("error",`Launch error: ${se.message}`,!0),!1}finally{p(null)}},[t,d,k,r]),y=a.useCallback(async L=>{if(!t)return{success:!1};const{cliType:$,dir:H,workspaceId:se,useDefaultWorkspace:Y,useHome:ie,argsStr:je,model:G,resumeSessionId:oe}=L;if(!$)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const W=je?je.split(/\s+/).filter(Boolean):void 0,be=(H==null?void 0:H.trim())||(se?"(saved id)":Y?"(default workspace)":ie?"(home)":"");k("info",`Launching ${$}${be?` in ${be}`:""}${G?` (model: ${G})`:""}...`),m($);try{const X={cliType:$,cliArgs:W,initialModel:G||void 0};H!=null&&H.trim()?X.dir=H.trim():se?X.workspaceId=se:Y?X.useDefaultWorkspace=!0:ie&&(X.useHome=!0),oe&&(X.resumeSessionId=oe);const ue=await r(t,"launch_cli",X),te=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(k("info",`${$} launched`,!0),(te==null?void 0:te.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(te==null?void 0:te.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:te==null?void 0:te.sessionId}):(k("error",`Failed: ${(ue==null?void 0:ue.error)||(te==null?void 0:te.error)}`,!0),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&I({cliType:$,argsStr:je,model:G}),{success:!1,sessionId:te==null?void 0:te.sessionId})}catch(X){return x(X)?(k("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${X.message}`,!0),{success:!1})}finally{m(null)}},[t,k,x,r]),j=a.useCallback(async(L,$,H,se)=>t?L?$.trim()?y({cliType:L,dir:$,argsStr:H,model:se}):(I({cliType:L,argsStr:H,model:se}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[t,k,y]),E=a.useCallback(async(L,$,H)=>{if(t&&window.confirm(`Stop ${L}?
|
|
61
|
-
This will terminate the process.`))try{const se=await r(t,"stop_cli",{cliType:L,dir:$,targetSessionId:H});se!=null&&se.success?k("info",`${L} stopped`,!0):k("error",`Stop failed: ${(se==null?void 0:se.error)||"Unknown error"}`,!0)}catch(se){k("error",`Stop failed: ${se.message}`,!0)}},[t,k,r]),R=a.useCallback(async L=>{try{await r(L.daemonId,"restart_ide",{ideType:L.type}),k("info",`${Ze(L.type)} restart initiated`,!0)}catch($){k("error",`Restart failed: ${$.message}`,!0)}},[k,r]),K=a.useCallback(async L=>{if(window.confirm(`Stop ${Ze(L.type)}?
|
|
62
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(L.daemonId,"stop_ide",{ideType:L.type,killProcess:!0});$!=null&&$.success?k("info",`${Ze(L.type)} stopped`,!0):k("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){k("error",`Stop failed: ${$.message}`,!0)}},[k,r]),D=a.useCallback(async()=>{if(t)try{const L=await r(t,"detect_ides",{});k("info",`Found ${((L==null?void 0:L.result)||[]).length} IDE(s)`,!0)}catch(L){k("error",`Detection failed: ${L.message}`,!0)}},[t,k,r]),V=a.useCallback(async L=>{if(!t||!L.trim())return!1;w(!0);try{const $=await r(t,"workspace_add",{path:L.trim()});return $!=null&&$.success?(k("info",`Workspace added: ${L.trim()}`),!0):(k("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return k("error",$.message),!1}finally{w(!1)}},[t,k,r]),_=a.useCallback(async L=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){w(!0);try{const $=await r(t,"workspace_remove",{id:L});$!=null&&$.success?k("info","Workspace removed",!0):k("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){k("error",$.message,!0)}finally{w(!1)}}},[t,k,r]),C=a.useCallback(async L=>{var $;if(t){w(!0);try{const H=await r(t,"workspace_set_default",L===null?{clear:!0}:{id:L});if(H!=null&&H.success){k("info",L?"Default workspace updated":"Default workspace cleared",!0);const se=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";se&&(($=N.current)==null||$.call(N,se))}else k("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){k("error",H.message,!0)}finally{w(!1)}}},[t,k,r]),T=a.useCallback(async L=>{var H;if(!t||!L.trim())return;const $=L.trim();w(!0);try{const se=await r(t,"workspace_set_default",{path:$});se!=null&&se.success?(k("info","Default workspace set from history"),(H=N.current)==null||H.call(N,$)):k("error",(se==null?void 0:se.error)||"Could not set default (path missing on disk?)")}catch(se){k("error",se.message)}finally{w(!1)}},[t,k,r]),z=a.useCallback(async()=>{if(t)try{if(await r(t,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:t,registeredMachineId:s,nickname:v})}catch(L){k("warn",`Live nickname updated, but account sync failed: ${L.message}`)}k("info",`Nickname set to "${v||"(cleared)"}"`),b(!1)}catch(L){k("error",`Failed: ${L.message}`)}},[t,v,s,k,n,r]);return{logs:i,launchingIde:d,launchingAgentType:f,workspaceBusy:h,launchPick:S,setLaunchPick:I,editingNickname:u,setEditingNickname:b,nicknameInput:v,setNicknameInput:l,addLog:k,handleLaunchIde:g,runLaunchCliCore:y,handleLaunchCli:j,handleStopCli:E,handleRestartIde:R,handleStopIde:K,handleDetectIdes:D,handleWorkspaceAdd:V,handleWorkspaceRemove:_,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:T,handleSaveNickname:z,setOnDefaultWorkspaceChanged:A}}function _p({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var R;const{workspaceBusy:d,handleWorkspaceAdd:p,handleWorkspaceRemove:f,handleWorkspaceSetDefault:m}=i,[h,w]=a.useState(!1),[S,I]=a.useState(""),[u,b]=a.useState([]),[v,l]=a.useState(!1),[N,A]=a.useState(""),k=a.useCallback(async K=>{l(!0),A("");try{const D=await Ir(c,t,K);I(D.path),b(D.directories)}catch(D){A(D instanceof Error?D.message:"Could not load folder")}finally{l(!1)}},[t,c]),x=a.useCallback(()=>{var D;w(!0);const K=Cr(s.platform,[s.defaultWorkspacePath,(D=s.workspaces[0])==null?void 0:D.path]);k(K)},[k,s.defaultWorkspacePath,s.platform,s.workspaces]),g=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,y=s.availableMem??s.freeMem??s.totalMem,j=g&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/s.totalMem*100))):0,E=((R=s.loadavg)==null?void 0:R[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(Fs,{icon:e.jsx(ao,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Vc(s.uptime):"Waiting…"}),e.jsx(Fs,{icon:e.jsx(Nt,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Fs,{icon:e.jsx(wr,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Fs,{icon:e.jsx(dc,{size:16}),label:"ACPs",value:`${o.length}`})]}),e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx(Qn,{value:g?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:g?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),e.jsx(Qn,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:g?`${Rr(s.totalMem-y)} / ${Rr(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Rr(s.totalMem)} total`})]})]}),e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[e.jsx(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:d,value:s.defaultWorkspaceId||"",onChange:K=>void m(K.target.value===""?null:K.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(K=>e.jsx("option",{value:K.id,children:K.label||K.path},K.id))]}),s.defaultWorkspacePath&&e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:d,onClick:x,children:"Select workspace…"}),e.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&e.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(K=>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:[K.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:kr(K.path,K.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:K.path,children:K.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:d,onClick:()=>void f(K.id),children:"Remove"})]},K.id))})]}),h&&e.jsx(Ar,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:u,busy:v,error:N,confirmLabel:"Add workspace",onClose:()=>w(!1),onNavigate:K=>{k(K)},onConfirm:K=>{(async()=>{if(!K)return;await p(K)&&w(!1)})()}})]})}function Pp(t){if(!t||typeof t!="object")return null;const s=t,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Lp(t,s,r){const n=[];for(const[o,i]of Object.entries(t.settings)){const c=i;if(c.length===0)continue;const d=s.find(p=>p.type===o);n.push({type:o,displayName:(d==null?void 0:d.displayName)||o,icon:(d==null?void 0:d.icon)||"",category:(d==null?void 0:d.category)||"unknown",schema:c,values:t.values[o]||{}})}return n}const Oa=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Rp=[{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 Dp({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,d]=a.useState("codex-cli"),[p,f]=a.useState([]),[m,h]=a.useState(""),[w,S]=a.useState([]),[I,u]=a.useState(""),b=a.useRef(null),v=a.useRef(null),l=y=>{f(j=>j.includes(y)?j.filter(E=>E!==y):[...j,y])},N=()=>f([...Oa]),A=()=>f([]);a.useEffect(()=>{var y;(y=b.current)==null||y.scrollIntoView({behavior:"smooth"})},[w]),a.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const k=a.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const y=await r(t,"provider_auto_fix_status",{providerType:s.type});(y==null?void 0:y.running)===!1&&o==="running"&&(i("done"),S(j=>[...j,`
|
|
63
|
-
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[t,s.type,r,o]),x=async()=>{if(p.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${p.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),u("");try{const y=await r(t,"provider_auto_fix",{providerType:s.type,functions:p,agent:c,...m?{comment:m}:{}});y!=null&&y.success&&(y!=null&&y.started||y!=null&&y.running)?(S(j=>[...j,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),u((y==null?void 0:y.error)||"Failed to start auto-fix"))}catch(y){i("error"),u((y==null?void 0:y.message)||"Connection failed")}}},g=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),S(y=>[...y,`
|
|
64
|
-
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.current)}catch{}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.jsxs("div",{className:"w-full max-w-[560px] max-h-[85vh] overflow-hidden rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),e.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),e.jsx("div",{className:"flex gap-2",children:Rp.map(y=>e.jsxs("button",{onClick:()=>d(y.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===y.value?y.color+"66":"var(--border-subtle)",background:c===y.value?y.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===y.value?y.color:"var(--text-primary)"},children:y.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:y.desc})]},y.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:N,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:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Oa.map(y=>e.jsxs("button",{onClick:()=>l(y),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:p.includes(y)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:p.includes(y)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:p.includes(y)?"#a78bfa":"var(--text-secondary)"},children:[p.includes(y)?"☑ ":"☐ ",y]},y))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",e.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:m,onChange:y=>h(y.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(o==="running"||o==="done"||o==="error")&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),e.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[w.map((y,j)=>e.jsx("div",{className:y.startsWith("✅")?"text-green-400":"",style:y.startsWith("❌")||y.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:y},j)),o==="running"&&e.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),e.jsx("div",{ref:b})]}),I&&e.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:I})]})]}),e.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[e.jsxs("div",{className:"text-[10px] text-text-muted",children:[o==="config"&&p.length>0&&`${p.length} script(s) selected`,o==="running"&&"Agent is generating...",o==="done"&&"Run `adhdev provider verify` to validate"]}),e.jsxs("div",{className:"flex gap-2",children:[o==="config"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:x,disabled:p.length===0,className:"machine-btn",style:{background:p.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:p.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:p.length>0?"#a78bfa":void 0,opacity:p.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:g,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{i("config"),S([]),u("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Ep({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var k;const i=s.filter(x=>x.category==="ide"),[c,d]=a.useState(((k=i[0])==null?void 0:k.type)||""),[p,f]=a.useState(""),[m,h]=a.useState(""),[w,S]=a.useState(!1),[I,u]=a.useState(""),[b,v]=a.useState(!1),l=x=>{const g=x.toLowerCase().replace(/[^a-z0-9-]/g,"");f(g),(!m||m===N(p))&&h(N(g))},N=x=>x.split("-").map(g=>g.charAt(0).toUpperCase()+g.slice(1)).join(" "),A=async()=>{if(!(!p||!m||!c)){S(!0),u("");try{const x=await r(t,"provider_clone",{type:p,name:m,category:"ide",location:"user",cloneFrom:c});x!=null&&x.success||x!=null&&x.created?(v(!0),o==null||o(p)):u((x==null?void 0:x.error)||"Failed to create provider")}catch(x){u((x==null?void 0:x.message)||"Connection failed")}S(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:e.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),e.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:b?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),e.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[e.jsx("code",{className:"text-violet-400",children:p})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",p,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",p]})," or use Auto-Fix to implement scripts."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(x=>e.jsxs("button",{onClick:()=>d(x.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===x.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===x.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[e.jsx("div",{className:"text-lg",children:x.icon}),e.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===x.type?"#a78bfa":"var(--text-secondary)"},children:x.displayName})]},x.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:p,onChange:x=>l(x.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/",p||"...","/"]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),e.jsx("input",{value:m,onChange:x=>h(x.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),I&&e.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:I})]})}),e.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:b?e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),e.jsx("button",{onClick:A,disabled:!p||!m||w,className:"machine-btn",style:{background:p&&m?"rgba(34,197,94,0.12)":void 0,borderColor:p&&m?"rgba(34,197,94,0.3)":void 0,color:p&&m?"#86efac":void 0,opacity:!p||!m||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function $p({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[d,p]=a.useState(null),[f,m]=a.useState("all"),[h,w]=a.useState(null),[S,I]=a.useState(!1),u=a.useCallback(async()=>{if(t){c(!0);try{const v=await r(t,"get_provider_settings",{}),l=Pp(v);if(l){const N=Lp(l,s);N.sort((A,k)=>A.category.localeCompare(k.category)||A.displayName.localeCompare(k.displayName)),o(N)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&u()},[]);const b=async(v,l,N)=>{p(`${v}.${l}`),o(A=>A.map(k=>k.type===v?{...k,values:{...k.values,[l]:N}}:k));try{const A=await r(t,"set_provider_setting",{providerType:v,key:l,value:N});A!=null&&A.success||u()}catch{u()}p(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(v=>e.jsx("button",{onClick:()=>m(v),className:`machine-btn text-[10px] px-2 py-0.5 ${f===v?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.toUpperCase()},v))]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>I(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),e.jsx("button",{onClick:u,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(v=>v.category===f).length>1&&(()=>{const v=n.filter(k=>k.category===f),l=new Map;for(const k of v)for(const x of k.schema){if(x.type!=="boolean")continue;const g=l.get(x.key),y=!!(k.values[x.key]??x.default);g?(g.onCount+=y?1:0,g.total+=1):l.set(x.key,{label:x.label||x.key,onCount:y?1:0,total:1})}const N=[...l.entries()].filter(([,k])=>k.total===v.length);if(N.length===0)return null;const A=async(k,x)=>{for(const g of v)await b(g.type,k,x)};return e.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[e.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",v.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(([k,x])=>{const g=x.onCount===x.total,y=x.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:x.label}),e.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",x.onCount,"/",x.total,")"]}),e.jsx("button",{onClick:()=>void A(k,!0),disabled:g,className:`machine-btn text-[9px] px-1.5 py-px ${g?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void A(k,!1),disabled:y,className:`machine-btn text-[9px] px-1.5 py-px ${y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},k)})})]})})(),i&&n.length===0?e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):e.jsx("div",{className:"flex flex-col gap-2",children:n.filter(v=>f==="all"||v.category===f).map(v=>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:v.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:v.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:v.category==="acp"?"rgba(139,92,246,0.08)":v.category==="cli"?"rgba(59,130,246,0.08)":v.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:v.category==="acp"?"#a78bfa":v.category==="cli"?"#60a5fa":v.category==="ide"?"#86efac":"var(--status-warning)"},children:v.category}),v.category==="ide"&&e.jsx("button",{onClick:()=>w(s.find(l=>l.type===v.type)||{type:v.type,name:v.displayName,displayName:v.displayName,icon:v.icon,category:v.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:v.schema.map(l=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[l.label||l.key,d===`${v.type}.${l.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),l.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:l.description})]}),e.jsx("div",{className:"shrink-0",children:l.type==="boolean"?e.jsx("button",{onClick:()=>b(v.type,l.key,!(v.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:v.values[l.key]??l.default?"#8b5cf6":"var(--border-subtle)"},children:e.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:v.values[l.key]??l.default?21:3}})}):l.type==="number"?e.jsx("input",{type:"number",value:Number(v.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:N=>{const A=parseInt(N.target.value)||0;l.min!==void 0&&A<l.min||l.max!==void 0&&A>l.max||b(v.type,l.key,A)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?e.jsx("select",{value:String(v.values[l.key]??l.default??""),onChange:N=>b(v.type,l.key,N.target.value),className:"machine-input text-[11px]",children:l.options.map(N=>e.jsx("option",{value:N,children:N},N))}):e.jsx("input",{type:"text",value:String(v.values[l.key]??l.default??""),onBlur:N=>b(v.type,l.key,N.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},v.type))}),h&&e.jsx(Dp,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>w(null)}),S&&e.jsx(Ep,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),u()}})]})}function Ha(t){if(!t||Object.keys(t).length===0)return"";try{const s=JSON.stringify(t);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function Bp({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,d]=a.useState([]),[p,f]=a.useState(0),[m,h]=a.useState(0),[w,S]=a.useState(!0),[I,u]=a.useState("debug"),b=a.useRef(null),v=a.useRef(!1);return a.useEffect(()=>{if(!t||!w)return;const l=async()=>{try{const[A,k]=await Promise.all([s(t,"get_logs",{count:200,minLevel:I,since:p}),s(t,"get_debug_trace",{count:120,since:m})]),x=(A==null?void 0:A.result)||A;if(A!=null&&A.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(j=>[...j,...x.logs.map(R=>({timestamp:R.ts,level:R.level,message:`[${R.category}] ${R.message}`}))].slice(-300));const y=Math.max(...x.logs.map(j=>j.ts));f(y)}const g=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(g==null?void 0:g.trace)){i(g.trace.slice(-120));const y=g.trace.reduce((j,E)=>Math.max(j,Number(E.ts||0)),m);y>m&&h(y)}}catch{}d(Qt.list({limit:120}))};l();const N=setInterval(l,3e3);return()=>clearInterval(N)},[t,w,p,m,I,s]),a.useEffect(()=>{if(w&&(r.length>0||o.length>0||c.length>0)){const l=v.current?"smooth":"instant";setTimeout(()=>{var N;(N=b.current)==null||N.scrollIntoView({behavior:l}),v.current=!0},50)}},[r.length,o.length,c.length,w]),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(l=>e.jsx("button",{onClick:()=>{u(l),n([]),f(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${I===l?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:l.toUpperCase()},l))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",o.length," web=",c.length]}),e.jsx("button",{onClick:()=>S(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),i([]),d([]),f(0),h(0),Qt.clear()},className:"machine-btn",children:"Clear"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((l,N)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:l.level==="error"?"#ef4444":l.level==="warn"?"var(--status-warning)":l.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(l.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:l.level==="error"?"ERR":l.level==="warn"?"WRN":l.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:l.message})]},`log-${N}`))]}),e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Structured daemon trace"}),o.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"No trace entries yet. Run daemon with --dev or --trace."}),o.map(l=>e.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[e.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[e.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{children:l.level.toUpperCase()}),e.jsxs("span",{children:[l.category,".",l.stage]}),l.interactionId&&e.jsxs("span",{children:["ix=",l.interactionId]})]}),e.jsx("div",{children:Ha(l.payload)})]},l.id))]}),e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&e.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(l=>e.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[e.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[e.jsx("span",{children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{children:l.kind}),l.topic&&e.jsxs("span",{children:["topic=",l.topic]}),l.interactionId&&e.jsxs("span",{children:["ix=",l.interactionId]})]}),e.jsx("div",{children:Ha(l.payload)})]},l.id))]})]}),e.jsx("div",{ref:b})]})}function Yr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Xr(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ua(t){if(!t)return"unknown";const s=Date.now()-t,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const o=Math.round(n/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function Kp(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Wp(t){const s=typeof(t==null?void 0:t.runtimeRecoveryState)=="string"?String(t.runtimeRecoveryState):"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function Op(t){switch(t){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function Hp(t){var r;const s=new Map;for(const n of t){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const o=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!o)continue;const i=`${n.providerType}::${n.workspace}::${o}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Up({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[d,p]=a.useState(!1),f=Fo(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),m=f.diagnostics,h=f.loading,w=f.applyDiagnostics,S=a.useMemo(()=>new Map(s.map(x=>[x.sessionId||x.id,x])),[s]),I=a.useCallback(async()=>{if(t){p(!0);try{const x=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),g=Yr(x);if(!(g!=null&&g.success))throw new Error((g==null?void 0:g.error)||"Could not load session host diagnostics");w(g.diagnostics||g.result||null),o("")}catch(x){const g=x instanceof Error?x.message:"Could not load session host diagnostics";o(g)}finally{p(!1)}}},[w,t,r]);a.useEffect(()=>{!t||m||h||d||I()},[m,h,t,I,d]);const u=a.useCallback(async(x,g)=>{const y=`${x}:${g.sessionId}`;if(!(x==="session_host_stop_session"&&!window.confirm(`Stop ${g.displayName}?
|
|
65
|
-
This will terminate the hosted runtime.`))){c(y);try{const j=await r(t,x,{sessionId:g.sessionId}),E=Yr(j);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Session host action failed");const R=x==="session_host_resume_session"?"resumed":x==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${R}: ${g.displayName}`,"success"),await I()}catch(j){const E=j instanceof Error?j.message:"Session host action failed";ht.showToast(E,"warning"),o(E)}finally{c(j=>j===y?null:j)}}},[t,I,r]),b=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
66
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const g=await r(t,"session_host_prune_duplicate_sessions",{}),y=Yr(g);if(!(y!=null&&y.success))throw new Error((y==null?void 0:y.error)||"Duplicate prune failed");const j=y.result||{},E=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,R=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;ht.showToast(`Pruned ${E} duplicate runtime(s) across ${R} group(s)`,"success"),await I()}catch(g){const y=g instanceof Error?g.message:"Duplicate prune failed";ht.showToast(y,"warning"),o(y)}finally{c(g=>g==="session_host_prune_duplicate_sessions"?null:g)}}},[t,I,r]),v=a.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((x,g)=>(g.lastActivityAt||0)-(x.lastActivityAt||0)),[m==null?void 0:m.sessions]),l=a.useMemo(()=>Hp(v),[v]),N=a.useMemo(()=>v.reduce((x,g)=>{var y;return x+(((y=g.attachedClients)==null?void 0:y.length)||0)},0),[v]),A=a.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),k=a.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(x=>x.level==="warn"||x.level==="error")||null,[m==null?void 0:m.recentLogs]);return e.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]}),e.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:"Hosted CLI runtime diagnostics and recovery controls."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&e.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${l})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${m?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:m?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||d,children:[e.jsx(gs,{size:13}),h||d?"Refreshing…":"Refresh"]})]})]}),n&&!m&&e.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ts,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-amber-100",children:"Session host diagnostics unavailable"}),e.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Runtimes"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Clients"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:N})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),e.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),e.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ua(m.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Xr(m.hostStartedAt)})]})]}),k&&e.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[e.jsx(ts,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Xr(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[e.jsx(wr,{size:14})," Hosted Runtimes"]}),v.length===0?e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No hosted runtimes on this machine yet."}):e.jsx("div",{className:"space-y-2",children:v.map(x=>{var D;const g=i===`session_host_resume_session:${x.sessionId}`,y=i===`session_host_restart_session:${x.sessionId}`,j=i===`session_host_stop_session:${x.sessionId}`,E=Wp(x.meta),R=S.get(x.sessionId),K=x.attachedClients.length===1?"1 client":`${x.attachedClients.length} clients`;return e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:x.displayName||(R==null?void 0:R.cliName)||x.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Op(x.lifecycle)}`,children:x.lifecycle}),E&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:E})]}),e.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:"text-text-primary/90",children:x.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||x.workspace||"No workspace"}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:"font-mono text-text-primary",children:x.runtimeKey}),x.osPid?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/90",children:["pid ",x.osPid]})]}):null]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[e.jsx("span",{className:((D=x.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Kp(x.writeOwner)}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[e.jsx(hn,{size:11})," ",K]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",Ua(x.lastActivityAt)]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(x.lifecycle==="interrupted"||x.lifecycle==="failed"||x.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_resume_session",x)},children:g?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{u("session_host_restart_session",x)},children:y?"Restarting…":"Restart"}),(x.lifecycle==="running"||x.lifecycle==="starting"||x.lifecycle==="interrupted")&&e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{u("session_host_stop_session",x)},children:j?"Stopping…":"Stop"})]})]})},x.sessionId)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),A.length===0?e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):e.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:A.map(x=>{var y;const g=v.find(j=>j.sessionId===x.sessionId);return e.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary font-medium",children:(g==null?void 0:g.displayName)||((y=S.get(x.sessionId))==null?void 0:y.cliName)||x.sessionId}),e.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[x.action,x.lifecycle?` · ${x.lifecycle}`:"",x.detail?` · ${x.detail}`:"",x.error?` · ${x.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${x.success===!1?"text-red-300":"text-text-secondary"}`,children:Xr(x.timestamp)})]},`${x.sessionId}:${x.timestamp}:${x.action}`)})})]}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",e.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function zp({machine:t,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return e.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/55 backdrop-blur-[2px]",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:e.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[e.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),e.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),e.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(t.workspaces||[]).length===0?e.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(t.workspaces||[]).map(i=>e.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[e.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!t.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),e.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function Jr({icon:t,children:s}){return e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[t,e.jsx("span",{children:s})]})}function Zr({children:t,className:s=""}){return e.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:t})}function Fp({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),p=r.slice(0,4),m=Ts(t,"0.8.51"),h=w=>w==="ide"?"IDE":w==="cli"?"CLI":"ACP";return e.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(Kt,{size:13}),children:"Current Chats"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(w=>{const S=an(w);return e.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(w),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Qe(w)}),S>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:vn(S)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ns(w)})]},w.tabKey)})})})]}),p.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ao,{size:13}),children:"Recent Launches"}),e.jsx(Zr,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(w=>e.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(w),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:w.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[h(w.kind),w.subtitle?` · ${w.subtitle}`:""]})]},w.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Jr,{icon:e.jsx(ts,{size:13}),children:"Daemon Update"}),e.jsx(Zr,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),e.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[e.jsx(gs,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Vp(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const Gp={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 nr(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qp(t){const s=t instanceof Error?t.message:String(t||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Qr({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:p,initialWorkspacePath:f}){const m=bs(),{handleLaunchIde:h,handleStopCli:w,handleRestartIde:S,handleStopIde:I,handleDetectIdes:u,launchingIde:b,launchingAgentType:v,addLog:l}=c,[N,A]=a.useState(null),k=a.useCallback(M=>{M&&m({pathname:"/",search:`?activeTab=${encodeURIComponent(M)}`})},[m]),x=Gp[t],g=t==="ide",y=t==="acp",j=a.useMemo(()=>n.filter(M=>M.category===t&&(t==="ide"||M.installed!==!1)),[t,n]),E=a.useMemo(()=>new Map(j.map(M=>[M.type,M.displayName||M.type])),[j]),[R,K]=a.useState(""),[D,V]=a.useState(""),[_,C]=a.useState([]),[T,z]=a.useState(""),[L,$]=a.useState(""),[H,se]=a.useState([]),[Y,ie]=a.useState(!1),[je,G]=a.useState(""),[oe,W]=a.useState(!1),[be,X]=a.useState(null),[ue,te]=a.useState(f?"__custom__":p||s.defaultWorkspaceId||""),[ae,fe]=a.useState(f||""),[le,he]=a.useState([]),[J,pe]=a.useState(!1),[ne,we]=a.useState(""),[ge,P]=a.useState([]),[ye,F]=a.useState(!1),[me,Ce]=a.useState(""),xe=a.useRef(null),[Le,Be]=a.useState(null),Fe=a.useRef("__home__"),[st,ze]=a.useState("__home__"),[dt,gt]=a.useState(!1),Ge=a.useRef(0),at=le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")),ot=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!ue&&te(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){te("__custom__"),fe(f);return}p&&(te(p),fe(""))},[p,f]),a.useEffect(()=>{g||R&&(j.some(M=>M.type===R)||(K(""),$("")))},[j,g,R]);const Ke=(()=>{if(ue==="__custom__")return ae.trim();if(!ue)return"";const M=(s.workspaces||[]).find(ee=>ee.id===ue);return(M==null?void 0:M.path)||""})(),ct=a.useCallback(M=>{const ee=ot.current[M];ee&&(clearTimeout(ee),delete ot.current[M]),he(re=>re.includes(M)?re.filter(ce=>ce!==M):re)},[]),ut=a.useRef(new Set),it=a.useCallback(async M=>{if(d){F(!0),Ce("");try{const ee=await Ir(d,r,M);we(ee.path),fe(ee.path),P(ee.directories)}catch(ee){Ce(ee instanceof Error?ee.message:"Could not load folder")}finally{F(!1)}}},[r,d]),Q=a.useCallback(()=>{var ee;if(!d)return;te("__custom__"),pe(!0);const M=Cr(s.platform,[ae.trim(),Ke,s.defaultWorkspacePath,(ee=s.workspaces[0])==null?void 0:ee.path]);it(M)},[ae,it,s.defaultWorkspacePath,s.platform,s.workspaces,Ke,d]),_e=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return;const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));if(re){te(re.id),fe("");return}te("__custom__"),fe(ee)},[s.workspaces]),Re=a.useCallback(M=>{const ee=String(M.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(ce=>nr(ce.path)===nr(ee));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),We=a.useCallback(async M=>{if(!d||!M||t!=="cli"){se([]),ie(!1),G("");return}const ee=Ge.current+1;Ge.current=ee,ie(!0),G("");try{const re=await d(r,"list_saved_sessions",{providerType:M,kind:"cli",limit:30});if(Ge.current!==ee)return;const ce=(re==null?void 0:re.result)??re;se(Array.isArray(ce==null?void 0:ce.sessions)?ce.sessions:[])}catch(re){if(Ge.current!==ee)return;se([]),G(re instanceof Error?re.message:"Could not load saved sessions")}finally{Ge.current===ee&&ie(!1)}},[t,r,d]),Ct=a.useMemo(()=>{if(t!=="cli"||!R)return null;const M=E.get(R)||R;return{routeId:r,daemonId:r,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:M,agentType:R,status:"idle",title:M,messages:[],ideType:R,workspaceName:Ke,displayPrimary:M,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${R}`}},[t,r,E,Ke,L,R]),pt=a.useCallback(M=>{if(t==="ide"||!M){C([]);return}C(pi(r,M))},[t,r]);a.useEffect(()=>{if($(""),pt(R),t!=="cli"||!R){se([]),G(""),ie(!1);return}We(R)},[t,pt,We,R]),a.useEffect(()=>{if(!L)return;const M=H.find(ee=>ee.providerSessionId===L);M!=null&&M.canResume||$("")},[H,L]);const wt=a.useCallback((M,ee)=>{xe.current=ee,Fe.current=M.selectedWorkspaceKey||"__home__",ze(M.selectedWorkspaceKey||"__home__"),Be(M)},[]),bt=a.useCallback(()=>{xe.current&&(gt(!0),xe.current().finally(()=>{xe.current=null,gt(!1),Be(null)}))},[]),Tt=a.useCallback(M=>{if(!M)return;he(re=>re.includes(M)?re:[...re,M]);const ee=ot.current[M];ee&&clearTimeout(ee),ot.current[M]=setTimeout(()=>{he(re=>re.includes(M)?re.filter(ce=>ce!==M):re),delete ot.current[M]},2e4)},[]);a.useEffect(()=>{for(const ee of o)xt(ee.status)!=="stopped"&&(le.includes(ee.type)&&!ut.current.has(ee.type)&&(ut.current.add(ee.type),l("info",`${E.get(ee.type)||ee.type} launched`,!0)),ct(ee.type));const M=new Set(o.filter(ee=>xt(ee.status)!=="stopped").map(ee=>ee.type));ut.current.forEach(ee=>{!le.includes(ee)&&!M.has(ee)&&ut.current.delete(ee)})},[l,ct,o,le,E]),a.useEffect(()=>()=>{Object.values(ot.current).forEach(clearTimeout),ot.current={}},[]);const[B,U]=a.useState({}),[q,O]=a.useState(null);a.useEffect(()=>{if(!g||!r||!d)return;(async()=>{try{const ee=await d(r,"get_ide_extensions",{}),re=(ee==null?void 0:ee.result)||ee;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&U(re.ideExtensions)}catch{}})()},[g,r,d]);const de=M=>g?Ze(M.type):t==="cli"?M.cliName:M.acpName,Se=g?s.detectedIdes||[]:[],Ae=a.useCallback(async M=>{const ee=(M==null?void 0:M.type)||R,re=(M==null?void 0:M.workspacePath)??Ke;if(g){await h(ee,re?{workspace:re}:void 0)&&Tt(ee);return}const ce=await c.runLaunchCliCore({cliType:ee,dir:M!=null&&M.workspaceId?void 0:re||void 0,workspaceId:(M==null?void 0:M.workspaceId)||void 0,useHome:(M==null?void 0:M.useHome)||!(M!=null&&M.workspaceId)&&!re,argsStr:(M==null?void 0:M.argsStr)??(D||void 0),model:(M==null?void 0:M.model)??(y&&T||void 0),resumeSessionId:(M==null?void 0:M.resumeSessionId)||!y&&t==="cli"&&ee===R&&L||void 0});if(ce.success||ce.pending){const Pe=(M==null?void 0:M.argsStr)??D;!g&&(Pe!=null&&Pe.trim())&&(mi(r,ee,Pe),pt(ee)),Tt(ee),ce.success&&ce.sessionId&&k(ce.sessionId)}},[c,h,y,g,D,T,pt,Tt,r,k,Ke,L,R]),Z=()=>{var ce;const M=g?Ze(R):E.get(R)||R,{options:ee,selectedKey:re}=Zt({machine:s,currentWorkspaceId:ue&&ue!=="__custom__"?ue:null,currentWorkspacePath:Ke});wt({title:`Launch ${M}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:ee,selectedWorkspaceKey:re,details:[{label:"Mode",value:x.label},{label:"Provider",value:M},...!g&&t==="cli"&&L?[{label:"Resume",value:((ce=H.find(Pe=>Pe.providerSessionId===L))==null?void 0:ce.title)||L}]:[],...!g&&D.trim()?[{label:"Arguments",value:D.trim()}]:[],...y&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Pe=ee.find(Me=>Me.key===Fe.current);Pe!=null&&Pe.workspaceId?(te(Pe.workspaceId),fe("")):Pe!=null&&Pe.workspacePath?(te("__custom__"),fe(Pe.workspacePath)):(te(""),fe("")),await Ae({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Ie=M=>{g?I(M):w(M.type,M.workspace,M.id)},De=a.useCallback(async(M,ee,re=!1)=>{if(M.mode===ee){re&&M.sessionId&&k(M.sessionId);return}if(!d||!M.sessionId){re&&M.sessionId&&k(M.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:M.sessionId,cliType:M.type,mode:ee}),re&&k(M.sessionId)}catch(ce){qp(ce)?console.warn("Skipped CLI view mode switch:",ce instanceof Error?ce.message:String(ce)):console.error("Failed to switch CLI view mode:",ce)}},[r,k,d]),Ue=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:ue,onChange:M=>{const ee=M.target.value;if(te(ee),ee==="__custom__"&&d){Q();return}ee!=="__custom__"&&fe("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(M=>e.jsxs("option",{value:M.id,children:[M.id===s.defaultWorkspaceId?"⭐ ":"",kr(M.path,M.label)]},M.id)),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),ue==="__custom__"&&(d?e.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:Q,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ae,onChange:M=>fe(M.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ue==="__custom__"?Ke?e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:ue===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ke,children:Ke})]}):"No workspace selected. This launches in the home directory."})]});return e.jsxs("div",{children:[e.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${x.accent} relative overflow-hidden`,children:[e.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",x.label," to Launch"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:g?Se.length>0?Se.map(M=>{const ee=o.find(Oe=>(Oe.type||"").toLowerCase()===(M.type||"").toLowerCase()&&xt(Oe.status)!=="stopped"),re=M.running||!!ee,ce=!!ee&&ee.cdpConnected,Pe=le.includes(M.type||M.id||""),Me=R===(M.type||"");return e.jsxs("button",{onClick:()=>{if(ce&&ee){const Oe=ee.sessionId;Oe?m(`/dashboard?activeTab=${encodeURIComponent(Oe)}`,{state:{openRemoteForTabKey:Oe}}):m("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Pe||K(Oe=>Oe===(M.type||"")?"":M.type||"")},disabled:!!b||Pe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ce?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==M.type?.4:1},children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(M.type)}),re&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ce?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.name||Ze(M.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-green-400":Pe?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:ce?"Open Session":Pe?"Starting...":Me?"Configure":"Select"})]})]},M.type)}):e.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",e.jsxs("button",{onClick:u,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[e.jsx(oc,{size:14})," Scan System"]})]}):j.length>0?j.map(M=>{const ee=R===M.type,re=le.includes(M.type),Pe=!!o.find(Me=>Me.type===M.type&&xt(Me.status)!=="stopped");return e.jsxs("button",{onClick:()=>K(Me=>Me===M.type?"":M.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:M.icon}),Pe&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:M.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":ee?"Configure":"Select"})]})]},M.type)}):e.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",t.toUpperCase()," providers available.",e.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),R&&(g?Se.find(M=>M.type===R):j.find(M=>M.type===R))&&e.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"Launch Settings"}),e.jsx("span",{className:"text-accent-primary font-bold",children:g?Ze(R):E.get(R)||R})]}),Ue,!g&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!y&&t==="cli"&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Resume from History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void We(R),disabled:!R||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{R&&(W(!0),We(R))},disabled:!R,children:"Open History"})]})]}),L?(()=>{const M=H.find(ee=>ee.providerSessionId===L);return M?e.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:M.title||M.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:M.providerSessionId}),e.jsx("div",{children:M.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>$(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),je&&e.jsx("div",{className:"text-[10px] text-red-400",children:je})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),e.jsx("input",{type:"text",placeholder:"Leave empty for default",value:T,onChange:M=>z(M.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:D,onChange:M=>V(M.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(M=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>V(M),title:M,children:M},M))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:Z,disabled:!!v||!!b||le.includes(R),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===R||b===R?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+le.filter(M=>!o.some(ee=>ee.type===M&&xt(ee.status)!=="stopped")).length,")"]}),o.length===0&&at.length===0?e.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",x.plural," running"]}):e.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map(M=>e.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:g?Ze(M):E.get(M)||M}),e.jsx("div",{className:"text-[11px] text-text-muted",children:v===M?"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:${M}`)),o.map(M=>{const ee=g?M:null,re=y?M:null,ce=!g&&!y?M:null,Pe=xt(M.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(M.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[de(M),(ee==null?void 0:ee.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:M.workspace||"—"}),(re==null?void 0:re.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",re.currentModel]}),(re==null?void 0:re.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",re.currentPlan]}),(ce==null?void 0:ce.mode)&&e.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.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 ",ce.runtimeKey]}),e.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ce.runtimeKey}`),A(ce.runtimeKey||null),window.setTimeout(()=>{A(Oe=>Oe===ce.runtimeKey?null:Oe)},1200)},children:N===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&e.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Vp(ce.runtimeWriteOwner)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),g&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Me=M.sessionId;if(Me){m(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});return}m("/dashboard",{state:{openRemoteForTabKey:M.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:e.jsx(Nt,{size:13})}),e.jsx("button",{onClick:()=>{const Me=M.workspace||"",{options:Oe,selectedKey:rt}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Restart ${Ze(M.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Oe,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Ze(M.type)}]},async()=>{const Ye=Oe.find(He=>He.key===Fe.current),qe=(Ye==null?void 0:Ye.workspacePath)??"";if(qe&&qe!==Me){await Ae({type:M.type,workspacePath:qe});return}await S(M)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:e.jsx(gs,{size:14})})]}),y&&e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!M.sessionId,children:e.jsx(Kt,{size:14})}),ce&&Pe!=="stopped"&&e.jsxs(e.Fragment,{children:[ce.mode&&e.jsx(Sn,{mode:ce.mode,onChange:Me=>void De(ce,Me,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Me=M.sessionId;Me&&k(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!M.sessionId,children:ce.mode==="chat"?e.jsx(Kt,{size:14}):e.jsx(Nt,{size:13})})]}),Pe==="stopped"?e.jsx("button",{onClick:()=>{const Me=M.workspace||"",Oe=g?Ze(M.type):de(M),{options:rt,selectedKey:Ye}=Zt({machine:s,currentWorkspacePath:Me});wt({title:`Launch ${Oe}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:rt,selectedWorkspaceKey:Ye,details:[{label:"Mode",value:x.label},{label:"Provider",value:Oe}]},async()=>{const qe=rt.find(He=>He.key===Fe.current);await Ae({type:M.type,workspaceId:(qe==null?void 0:qe.workspaceId)??null,workspacePath:(qe==null?void 0:qe.workspacePath)??"",useHome:!(qe!=null&&qe.workspaceId)&&!(qe!=null&&qe.workspacePath),model:re==null?void 0:re.currentModel})})},disabled:le.includes(M.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:le.includes(M.type)?"⏳":e.jsx(gn,{size:14})}):e.jsx("button",{onClick:()=>Ie(M),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:e.jsx(vt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Me=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${mo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",xt(Me.status)]},Me.id))}),ee&&(B[ee.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:(B[ee.type]||[]).map(Me=>e.jsxs("button",{disabled:q===`${ee.type}.${Me.type}`,onClick:async()=>{const Oe=`${ee.type}.${Me.type}`;O(Oe);try{await d(r,"set_ide_extension",{ideType:ee.type,extensionType:Me.type,enabled:!Me.enabled}),U(rt=>({...rt,[ee.type]:(rt[ee.type]||[]).map(Ye=>Ye.type===Me.type?{...Ye,enabled:!Ye.enabled}:Ye)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{O(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 ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,e.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},M.id)})]}),J&&d&&e.jsx(Ar,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ne,directories:ge,busy:ye,error:me,confirmLabel:"Use this folder",onClose:()=>pe(!1),onNavigate:M=>{it(M)},onConfirm:M=>{fe(M),te("__custom__"),pe(!1)}}),Le&&e.jsx(Rn,{title:Le.title,description:Le.description,details:Le.details,workspaceOptions:Le.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:M=>{Fe.current=M,ze(M)},confirmLabel:Le.confirmLabel,busy:dt,onConfirm:bt,onCancel:()=>{xe.current=null,Be(null)}}),oe&&Ct&&e.jsx(Cn,{activeConv:Ct,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:H,isSavedSessionsLoading:Y,isResumingSavedSessionId:be,onClose:()=>W(!1),onNewChat:()=>{$(""),W(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{We(R)},onResumeSavedSession:M=>{if(!M.canResume||be)return;const ee=Re(M);$(M.providerSessionId),_e(M),X(M.providerSessionId),W(!1),Ae({type:M.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:M.providerSessionId}).finally(()=>{X(re=>re===M.providerSessionId?null:re)})}})]})}const za=[{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 Yp({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:p="ide",initialWorkspaceId:f,initialWorkspacePath:m,sendDaemonCommand:h}){var u;const[w,S]=a.useState(p);a.useEffect(()=>{S(p)},[p]);const I=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[e.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[e.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),e.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[e.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:za.map(b=>e.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:I[b.id]})]},b.id))}),e.jsx("div",{className:"text-xs text-text-muted italic",children:(u=za.find(b=>b.id===w))==null?void 0:u.helper})]}),w==="ide"&&e.jsx(Qr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="cli"&&e.jsx(Qr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m}),w==="acp"&&e.jsx(Qr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:m})]})}function Xp({onNicknameSynced:t}={}){var ae,fe,le,he,J,pe,ne,we,ge;const{id:s}=Hi(),r=bs(),n=fn(),{sendCommand:o}=St(),i=Hs(),c=wo(),d=c.ides||[],p=c.initialLoaded??!0,f=d.find(P=>P.id===s&&P.type==="adhdev-daemon"),m=d.some(P=>P.type==="adhdev-daemon"),[h,w]=a.useState("workspace"),[S,I]=a.useState("ide"),u=a.useRef(null),[b,v]=a.useState(null),l=a.useRef("__home__"),[N,A]=a.useState("__home__"),[k,x]=a.useState(!1),g=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),Od(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const y=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=Tp({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:g});a.useEffect(()=>ht.onToast(ye=>{c.setToasts(me=>{if(me.some(Le=>Le.message===ye.message&&ye.timestamp-Le.timestamp<3e3))return me;const xe={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...me.slice(-4),xe]});const F=ye.duration||5e3;setTimeout(()=>c.setToasts(me=>me.filter(Ce=>Ce.id!==ye.id)),F)}),[c]);const E=(f==null?void 0:f.availableProviders)||[],R={};for(const P of E)R[P.type]=P.icon;const K=P=>R[P]||"",D=f?{id:f.id,hostname:fo(f,{fallbackId:f.id}),platform:((ae=f.machine)==null?void 0:ae.platform)||"unknown",arch:((fe=f.machine)==null?void 0:fe.arch)||"",cpus:((le=f.machine)==null?void 0:le.cpus)||0,totalMem:((he=f.machine)==null?void 0:he.totalMem)||0,freeMem:(J=f.machine)==null?void 0:J.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ne=f.machine)==null?void 0:ne.loadavg,uptime:(we=f.machine)==null?void 0:we.uptime,release:((ge=f.machine)==null?void 0:ge.release)||"",cdpConnected:!!f.cdpConnected,machineNickname:f.machineNickname||null,p2p:f.p2p?{screenshotActive:!1,...f.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:f.detectedIdes||[],workspaces:f.workspaces||[],defaultWorkspaceId:f.defaultWorkspaceId??f.activeWorkspaceId??null,defaultWorkspacePath:f.defaultWorkspacePath??f.activeWorkspacePath??null}:null,V=d.filter(P=>P.daemonId===s&&P.type!=="adhdev-daemon").filter(P=>!$s(P)&&!ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Zc(P.aiAgents||(P.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:s})),_=d.filter(P=>P.daemonId===s&&$s(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:s})),C=d.filter(P=>P.daemonId===s&&ms(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,currentModel:P.currentModel,currentPlan:P.currentPlan,daemonId:s})),T=f?kt(f,{fallbackId:s}):"",z="workspace",L=n.state,$=L==null?void 0:L.initialMachineTab,H=L==null?void 0:L.initialWorkspaceCategory,se=L==null?void 0:L.initialWorkspaceId,Y=L==null?void 0:L.initialWorkspacePath,ie=$==="ides"||$==="clis"||$==="acps"?"workspace":$||z,je=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":H,G=[...V.map(P=>{var ye,F,me,Ce,xe;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),..._.map(P=>{var ye,F,me,Ce,xe;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}}),...C.map(P=>{var ye,F,me,Ce,xe;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ye=P.activeChat)==null?void 0:ye.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace||void 0,currentModel:P.currentModel,timestamp:((xe=(Ce=(me=(F=P.activeChat)==null?void 0:F.messages)==null?void 0:me.at)==null?void 0:Ce.call(me,-1))==null?void 0:xe.timestamp)||0}})].sort((P,ye)=>ye.timestamp-P.timestamp).map(({timestamp:P,...ye})=>ye),oe=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:P.currentModel||P.workspace||void 0,workspace:P.workspace,currentModel:P.currentModel})):G,W=a.useMemo(()=>{var ye;const P=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return d.filter(F=>F.daemonId===s&&F.type!=="adhdev-daemon").flatMap(F=>In(F,{},{connectionStates:s&&P?{[s]:P}:void 0,defaultConnectionState:P})).filter(F=>!(F.transport==="pty"&&F.mode==="terminal")).sort((F,me)=>an(me)-an(F))},[d,c.connectionStates,s]),be=a.useCallback(P=>{const ye=P.sessionId||P.tabKey;ye&&r(`/dashboard?activeTab=${encodeURIComponent(ye)}`)},[r]),X=a.useCallback(()=>{u.current&&(x(!0),u.current().finally(()=>{u.current=null,x(!1),v(null)}))},[]),ue=a.useCallback(P=>{if(!D)return;const{options:ye,selectedKey:F}=Zt({machine:D,currentWorkspacePath:P.workspace}),me=async()=>{I(P.kind),w("workspace")};u.current=async()=>{const Ce=ye.find(Be=>Be.key===l.current),xe=(Ce==null?void 0:Ce.workspacePath)??null,Le=(Ce==null?void 0:Ce.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await j.handleLaunchIde(P.providerType,xe?{workspace:xe}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await j.runLaunchCliCore({cliType:P.providerType,dir:Le?void 0:xe||"",workspaceId:Le||void 0,model:P.kind==="acp"?P.currentModel:void 0,resumeSessionId:P.providerSessionId});return}await me()},l.current=F,A(F),v({title:`Launch ${P.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:ye,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[j,D]);if(a.useEffect(()=>{w(ie)},[z,ie,s]),a.useEffect(()=>{je&&I(je)},[je,s]),!D)return p?e.jsxs("div",{className:"p-10 text-center text-text-muted",children:[e.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),e.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),e.jsx("button",{onClick:y,className:"machine-btn-back",children:"← Back"})]}):e.jsx("div",{className:"p-10 text-center text-text-muted",children:e.jsx("p",{children:"⏳ Loading machine..."})});const te=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{size:14})," Workspace"]}),count:V.length+_.length+C.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(vr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ic,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(nc,{size:14})," Logs"]})}];return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[e.jsx("div",{className:"flex items-center justify-between w-full",children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[e.jsx("button",{onClick:y,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[j.editingNickname?e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsx("input",{autoFocus:!0,value:j.nicknameInput,onChange:P=>j.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&j.handleSaveNickname(),P.key==="Escape"&&j.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),e.jsx("button",{onClick:j.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),e.jsx("button",{onClick:()=>j.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{j.setEditingNickname(!0),j.setNicknameInput(D.machineNickname||"")},title:"Click to set nickname",children:T}),e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[e.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[D.platform," · ",D.arch]}),e.jsxs("span",{children:[D.cpus," cores"]}),(f==null?void 0:f.version)&&e.jsxs("span",{children:["v",f.version]}),D.p2p.available&&e.jsxs("span",{children:["P2P ",D.p2p.state==="connected"?"connected":D.p2p.state]}),D.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:D.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:te.map(P=>e.jsxs("button",{onClick:()=>w(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:e.jsx("div",{className:"max-w-7xl mx-auto h-full",children:e.jsxs("div",{className:"h-full",children:[h==="workspace"&&e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[e.jsx(Fp,{machineEntry:f,providers:E,recentLaunches:oe,currentConversations:W,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:be}),e.jsx(Yp,{machine:D,machineId:s,providers:E,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,getIcon:K,initialCategory:S,initialWorkspaceId:se,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx($p,{machineId:s,providers:E,sendDaemonCommand:o}),h==="overview"&&e.jsx(_p,{machineId:s,machine:D,ideSessions:V,cliSessions:_,acpSessions:C,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(Up,{machineId:s,cliSessions:_,sendDaemonCommand:o}),h==="logs"&&e.jsx(Bp,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&D&&e.jsx(zp,{machine:D,launchPick:j.launchPick,actions:j}),b&&e.jsx(Rn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:P=>{l.current=P,A(P)},confirmLabel:b.confirmLabel,busy:k,onConfirm:X,onCancel:()=>{u.current=null,v(null)}}),e.jsx(Ao,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ye=>ye.filter(F=>F.id!==P)),onClickToast:P=>{P.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(P.targetKey)}`)}}),e.jsx("style",{children:`
|
|
67
|
-
@keyframes toast-in {
|
|
68
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
69
|
-
to { opacity: 1; transform: translateX(0); }
|
|
70
|
-
}
|
|
71
|
-
`})]})}class Jp{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,o){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,o=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:o})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const o=this.runtimeListeners.get(s);o&&(o.delete(r),o.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const o=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(o=>o(r))}}const Et=new Jp;function Zp(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const ar=Zp(),Fa=3e3,Qp=3e4;let Rt=null,em=0;const yr=new Map;let Gt=null,Ps=null;function Va(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function Cs(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function tm(t){return t==="connected"?"connected":t}async function dr(t,s,r){const n=Ul(t,r||{}),o=Rt;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++em}_${Date.now()}`;return new Promise((c,d)=>{const p=setTimeout(()=>{yr.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);yr.set(i,{resolve:f=>{clearTimeout(p),c(f)},reject:f=>{clearTimeout(p),d(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function mn(t,s){const r=Rt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class sm{constructor(s){nt(this,"daemonId");nt(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return dr(this.daemonId,s,r)}async sendInput(s,r){return dr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Gt&&(clearInterval(Gt),Gt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await dr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const o=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Et.emitScreenshot(this.daemonId,o)}}catch{}};r(),Gt=setInterval(r,2e3)}stopScreenshots(s){Gt&&(clearInterval(Gt),Gt=null)}}let Mt=null;function rm(t){return(!Mt||Mt.daemonId!==t)&&(Mt=new sm(t)),Mt}function nm({children:t}){const s=a.useRef(pr()),r=pr();s.current=r;const{setUserName:n}=es(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),p=a.useCallback((u,b)=>{d(u),Ps==null||Ps(u,b)},[]),f=a.useRef(null),m=a.useRef(),h=a.useRef(Fa),w=a.useRef(!0),S=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{w.current=!0,S.current=!1;function u(){var l,N;if(!w.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;p("connecting"),console.log(`[Standalone WS] Connecting to ${ar}...`),Cs("connect_attempt",{url:ar,reason:I.current,delayMs:h.current});let v;try{v=new WebSocket(ar)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),b();return}f.current=v,v.onopen=()=>{if(!w.current){v.close();return}p("connected"),h.current=Fa,Cs("open",{url:ar,reason:I.current}),Ot.resubscribeAll({sendData:mn}),console.log("[Standalone WS] Connected")},Rt=v,v.onmessage=A=>{var k,x;try{const g=JSON.parse(A.data);if((g.type==="command_result"||g.type==="error")&&g.requestId){const y=yr.get(g.requestId);y&&(yr.delete(g.requestId),g.type==="error"?y.reject(new Error(((k=g.data)==null?void 0:k.message)||"Command failed")):y.resolve(g.data));return}if(g.type==="session_output"){const y=g.sessionId||g.cliId||g.cliType;y&&Et.emitSessionOutput(y,typeof g.data=="string"?g.data:"",typeof g.seq=="number"?g.seq:void 0);return}if(g.type==="runtime_snapshot"){Et.emitRuntimeSnapshot(g.sessionId,typeof g.text=="string"?g.text:"",typeof g.seq=="number"?g.seq:0,!!g.truncated);return}if(g.type==="topic_update"){const y=g.update;y&&Ot.publish(y);return}if(g.type==="status"||g.type==="initial_state"){const y=g.data;if(!y)return;const{injectEntries:j,markLoaded:E,getIdes:R}=s.current,K=y.instanceId||"standalone",D=R().find(C=>C.id===K),V=rm(K);Et.register(K,V),Et.setState(K,"connected"),p("connected",K),Et.emitStatus(K,y);const _=fr(y,{daemonId:K,existingDaemon:D,existingEntries:R()});Va("ws_status",{type:g.type,daemonId:K,sessions:(y.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(y.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Va("entries",{daemonId:K,entries:_.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),_.length>0&&j(_,{authoritativeDaemonIds:[K]}),E(),c.current!==K&&((x=i.current)==null||x.call(i),c.current=K,i.current=Ot.subscribe({sendData:mn},K,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${K}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const T=s.current.getIdes(),z=T.find($=>$.id===K),L=fr(C.status,{daemonId:K,existingDaemon:z,existingEntries:T,timestamp:C.timestamp});L.length>0&&s.current.injectEntries(L),C.userName&&o.current&&o.current(C.userName)}))}}catch(g){console.error("[Standalone WS] Parse error:",g)}},v.onclose=A=>{w.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Et.setState(Mt.daemonId,"disconnected"),p("disconnected"),f.current=null,I.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,Cs("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),b())},v.onerror=A=>{S.current||!w.current||(I.current="error",Cs("error",{message:A instanceof Event?"event":String(A),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function b(){if(!w.current)return;clearTimeout(m.current);const v=h.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Cs("schedule_reconnect",{reason:I.current,delayMs:v}),m.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Qp),u()},v)}return u(),()=>{var v;w.current=!1,S.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Rt=null),Mt&&(Mt.stopScreenshots(),Et.unregister(Mt.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function am({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Ps=(c,d)=>{r(c),d&&o(d)},()=>{Ps=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=tm(s),p={};return n&&(p[n]=d),p.standalone=d,{wsStatus:s,isConnected:c,connectionStates:p}},[s,n]);return e.jsx(Xi,{connectionOverrides:i,children:e.jsx(nm,{children:t})})}const om=[{id:"dashboard",path:"/dashboard",icon:e.jsx(eo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Ut,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(vr,{}),label:"Settings"}];function im({children:t}){const s=bs(),r=fn(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=m=>{s(m),o(!1)},p=()=>{c(m=>{const h=!m;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},f=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return e.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[e.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"}),e.jsx("span",{className:"mobile-menu-icon"})]}),n&&e.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:m=>m.key==="Escape"&&o(!1)}),e.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[e.jsxs("div",{className:"sidebar-header",children:[e.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[e.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&e.jsx("span",{children:"ADHDev"})]}),e.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:"✕"})]}),e.jsx("nav",{className:"sidebar-nav",children:om.map(m=>e.jsxs("div",{className:f(m.path),id:`nav-${m.id}`,onClick:()=>d(m.path),title:i?m.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),e.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(to,{})}),!i&&e.jsxs(e.Fragment,{children:["Docs",e.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),e.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[e.jsx("span",{className:"nav-icon",children:e.jsx(so,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.51"]}),e.jsx(wd,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:p,title:i?"Expand sidebar":"Collapse sidebar",children:[e.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&e.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),e.jsx("main",{className:"main-content relative",children:e.jsx("div",{className:"main-content-inner",children:t})})]})}const cm=[{icon:e.jsx(Ut,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Kt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(ro,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(Nt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Rs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(to,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],lm=[{icon:e.jsx(oo,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(eo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(rc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(hn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(ac,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],dm=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function um(){return e.jsxs(Eo,{icon:e.jsx(so,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:e.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.51"]}),children:[e.jsx(Pt,{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(Pt,{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:cm.map(t=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:_o.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Lo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Po.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(Pt,{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:lm.map(t=>e.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),e.jsx(Pt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:e.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-bg-secondary",children:[e.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),e.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),e.jsx("tbody",{children:dm.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($o,{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(yc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function pm(){const{ides:t}=es(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=St(),{userName:o}=es(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=h=>{const w=h.target.value.trim();s!=null&&s.id&&w!==o&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[p,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=h=>{f(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(Eo,{icon:e.jsx(vr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(xd,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(Pt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[e.jsx("span",{className:"text-text-muted",children:"Version"}),e.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.51"]}),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(Pt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(h=>e.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${h.running?"bg-green-400":"bg-text-muted/30"}`}),e.jsx("span",{className:"text-sm font-medium",children:h.name})]}),e.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:h.type})]},h.type))})}),e.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Sd,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(Pt,{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(Md,{})]}),e.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[e.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"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($d,{})]}),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(Kd,{})]})]})}),e.jsx(Pt,{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(jd,{}),e.jsx(qt,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:p,onChange:m})]})}),e.jsx(Pt,{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(sc,{size:16,className:"text-text-secondary"})," Display Name"]}),e.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),e.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:h=>c(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}vd();Dd();const mm=Za({baseUrl:""});function Ga(){const{ides:t,initialLoaded:s}=es();if(!s)return e.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=t.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?e.jsx(sn,{to:`/machines/${r.id}`,replace:!0}):e.jsx(sn,{to:"/dashboard",replace:!0})}function fm(){const t=a.useMemo(()=>({sendCommand:dr,sendData:mn}),[]);return e.jsx(Ui,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Qi,{client:mm,children:e.jsx(am,{children:e.jsx(tc,{value:t,children:e.jsx(im,{children:e.jsxs(zi,{children:[e.jsx(Ft,{path:"/dashboard",element:e.jsx(Mp,{})}),e.jsx(Ft,{path:"/machine",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/machines/:id",element:e.jsx(Xp,{})}),e.jsx(Ft,{path:"/machines",element:e.jsx(Ga,{})}),e.jsx(Ft,{path:"/about",element:e.jsx(um,{})}),e.jsx(Ft,{path:"/settings",element:e.jsx(pm,{})}),e.jsx(Ft,{path:"*",element:e.jsx(sn,{to:"/dashboard",replace:!0})})]})})})})})})}Sl({connectionManager:Et});Fi(document.getElementById("root")).render(e.jsx(fm,{}));
|