@adhdev/daemon-standalone 0.8.37 → 0.8.39
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 +146 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/{index-lGhguu4V.js → index-DJmVwnzu.js} +17 -17
- package/public/index.html +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
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 ci=Object.defineProperty;var li=(t,s,r)=>s in t?ci(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var qe=(t,s,r)=>li(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as ka,a as Na,b as di,c as ui,u as ds,R as Ge,d as Sa,t as mi,e as pi,D as fi,f as xi,g as hi,h as Xr,i as bi,k as gi,B as yi,l as vi,m as Ot,N as Wr,n as wi}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)}})();const Ca=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}),Ia=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Cn(t){var r,n;let s=0;return"activeChat"in t&&(s+=4),(r=t.childSessions)!=null&&r.length&&(s+=2),t.workspace&&(s+=1),t.machine&&(s+=1),(n=t.agents)!=null&&n.length&&(s+=1),s}function vr(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;return o&&(n.version=o),i&&(n.serverVersion=i),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),n)}function sr(t){return Array.isArray(t)?t.map(sr):!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,sr(r)]))}function ji(t,s){try{return JSON.stringify(sr(t))===JSON.stringify(sr(s))}catch{return!1}}function Ds(t,s,r){return ji(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function ki(t,s,r){var m,f,p,h,g,C,I;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(l=>({...l,_lastUpdate:n}));const i=new Map;for(const l of s)i.set(l.id,l);for(const l of t){const b=i.get(l.id);if(!b){i.set(l.id,{...l,_lastUpdate:n});continue}const y=Cn(l),u=Cn(b);if(y>u){const S=(m=l.chats)!=null&&m.length?l.chats:b.chats,_=vr(b,l,{...b,...l,chats:S,_lastUpdate:n});i.set(l.id,Ds(b,_,n))}else if(y<u){const S={};if(l.status&&l.status!==b.status&&(S.status=l.status),l.cdpConnected!==void 0&&(S.cdpConnected=l.cdpConnected),(f=l.chats)!=null&&f.length&&!((p=b.chats)!=null&&p.length)&&(S.chats=l.chats),l.machineNickname!==void 0&&l.machineNickname!==b.machineNickname&&(S.machineNickname=l.machineNickname),l.version!==void 0&&(S.version=l.version),l.serverVersion!==void 0&&(S.serverVersion=l.serverVersion),l.versionMismatch===!0&&(S.versionMismatch=!0),Object.keys(S).length>0){const _=vr(b,l,{...b,...S,_lastUpdate:b._lastUpdate});i.set(l.id,Ds(b,_,n))}else Ds(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const S=l.timestamp||n,_=b._lastUpdate||b.timestamp||0;if(S>=_){const N=(h=l.chats)!=null&&h.length?l.chats:b.chats,x=vr(b,l,{...b,...l,chats:N,_lastUpdate:n});i.set(l.id,Ds(b,x,n))}else(g=l.chats)!=null&&g.length&&!((C=b.chats)!=null&&C.length)&&i.set(l.id,{...b,chats:l.chats})}}const c=new Set(t.map(l=>l.id)),d=new Set;for(const l of t){const b=l.daemonId||((I=l.id)==null?void 0:I.split(":")[0]);b&&d.add(b)}for(const[l,b]of i){const y=b.daemonId||l.split(":")[0];if(!d.has(y))continue;if(o.has(y)&&!c.has(l)){i.delete(l);continue}const u=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(l)&&u>1e4||b.transport==="acp"&&!c.has(l)&&u>1e4||b.transport==="cdp-page"&&!c.has(l)&&u>3e4)&&i.delete(l)}for(const[l,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(l);return Array.from(i.values())}function Ni(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 Si({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,d]=a.useState([]),[m,f]=a.useState(void 0),p=a.useRef(r);a.useEffect(()=>{p.current=r},[r]);const h=a.useCallback((y,u)=>{n(S=>{let _=!1;const N=S.map(x=>x.id!==y||x.chats===u?x:(_=!0,{...x,chats:u}));return _?N:S})},[]),g=a.useCallback((y,u)=>{n(S=>{const _=S.length===0?y:ki(y,S,u);return Ni(S,_)?S:_})},[]),C=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:g,markLoaded:C,getIdes:()=>p.current}),[g,C]),l=s,b=a.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:o,toasts:c,setToasts:d,wsStatus:(l==null?void 0:l.wsStatus)??"connected",isConnected:(l==null?void 0:l.isConnected)??!0,connectionStates:(l==null?void 0:l.connectionStates)??{},connectionTransports:(l==null?void 0:l.connectionTransports)??{},showReconnected:(l==null?void 0:l.showReconnected)??!1,retryConnection:l==null?void 0:l.retryConnection,isP2PActive:(l==null?void 0:l.isP2PActive)??!1,p2pStates:(l==null?void 0:l.p2pStates)??{},userRole:l==null?void 0:l.userRole,userName:m,setUserName:f}),[r,h,o,c,l==null?void 0:l.wsStatus,l==null?void 0:l.isConnected,l==null?void 0:l.connectionStates,l==null?void 0:l.connectionTransports,l==null?void 0:l.showReconnected,l==null?void 0:l.retryConnection,l==null?void 0:l.isP2PActive,l==null?void 0:l.p2pStates,l==null?void 0:l.userRole,m]);return e.jsx(Ia.Provider,{value:I,children:e.jsx(Ca.Provider,{value:b,children:t})})}function Yt(){return a.useContext(Ca)}function rr(){return a.useContext(Ia)}function _a(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 m=r==null?void 0:r(),f=o(d),p=d.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return m&&p.searchParams.set("token",m),!d.startsWith("http")&&!s?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function c(d,m={}){const f={"Content-Type":"application/json",...m.headers||{}},p=r==null?void 0:r();p&&(f.Authorization=`Bearer ${p}`);const h=o(d),g=new AbortController,C=setTimeout(()=>g.abort(),15e3);try{const I=await fetch(h,{...m,headers:f,signal:g.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const l=await I.json().catch(()=>({error:I.statusText}));throw new Error(l.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(C)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:d=>c(`/api/v1/daemons/${d}/status`),sendCommand:(d,m,f={})=>c(`/api/v1/daemons/${d}/command`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),execTerminal:(d,m,f)=>c(`/api/v1/daemons/${d}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:f})}),sendAgentMessage:(d,m,f)=>c(`/api/v1/shortcuts/${d}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:f})}),getAgentStatus:d=>c(`/api/v1/shortcuts/${d}/status`),approveAgent:(d,m,f)=>c(`/api/v1/shortcuts/${d}/approve`,{method:"POST",body:JSON.stringify({agentType:m,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,m,f={})=>c(`/api/v1/mux/${encodeURIComponent(d)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),getMuxEventsUrl:d=>i(`/api/v1/mux/${encodeURIComponent(d)}/events`),getRuntimeEventsUrl:d=>i(`/api/v1/runtime/${encodeURIComponent(d)}/events`),request:c}}const Ci=_a({baseUrl:"http://localhost:3847"}),Ii=a.createContext(Ci);function _i({client:t,children:s}){return e.jsx(Ii.Provider,{value:t,children:s})}const Ai={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Aa=a.createContext(Ai);function Mi({value:t,children:s}){return e.jsx(Aa.Provider,{value:t,children:s})}function mt(){return a.useContext(Aa)}const Le={size:18};function Ma({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Jr({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Bt({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),e.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),e.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),e.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Zr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Ti({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"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 Li({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ta({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),e.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),e.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),e.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Pi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),e.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),e.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),e.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),e.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function cr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function La({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),e.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Ri({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Pt({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ut({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Qr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),e.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ei({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function cs({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function us({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Xt({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Is({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M12 22v-5"}),e.jsx("path",{d:"M9 8V2"}),e.jsx("path",{d:"M15 8V2"}),e.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Pa({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function $i({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),e.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),e.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Ra({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Di({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),e.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),e.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function lr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"4 17 10 11 4 5"}),e.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Bi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function en({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ki({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function bt({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ea({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),e.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),e.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),e.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Wi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("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 Oi({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function zi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),e.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function dr({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),e.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Ui({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"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 Hi({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Fi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",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 Vi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gi({size:t=Le.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function qi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Yi({size:t=Le.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),e.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),e.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function In(t){return!!t&&typeof t=="object"&&"text"in t}function tn(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:In(i)?String(i.text||""):"").join(r):In(t)?o=String(t.text||""):o=String(t||""),n?o.replace(/\s+/g," ").trim():o}function Jt(t){return tn(t,{normalizeWhitespace:!0})}function $a(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Xi(t,s,r){return Number(t.receivedAt||r[ns(t,s)]||0)||0}function Ji(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ns(t,s){const r=t,n=tn(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
|
|
4
|
-
`});if(p==="thought"){const w=typeof((
|
|
5
|
-
`)[0].slice(0,80)})]});if(p==="terminal"){const w=(N=s.meta)!=null&&N.isRunning?"⏳":"✅",v=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:w}),e.jsx("span",{children:v})]}),e.jsx("pre",{className:"chat-msg-body",children:h})]})}if(p==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:h.slice(0,100)});const g=s.meta,I=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",l=h,b=i&&!f&&!I&&l.length>_n,y=b&&!c?l.slice(0,_n):l,u=I,S=!u&&Ji(y);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(l||f)&&e.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${l?"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:$a(r)})]}),l&&e.jsx("div",{className:"chat-markdown",children:u?e.jsx("pre",{className:"chat-preformatted",children:y}):S?e.jsx(ka,{remarkPlugins:[Na,di,ui],children:y}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),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(l.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),ec=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:d="",receivedAtMap:m={},emptyState:f,onLoadMore:p,isLoadingMore:h,hasMoreHistory:g,hiddenLiveCount:C=0,loadError:I,scrollToBottomRequestNonce:l},b){var pe;const y=a.useRef(null),u=a.useRef(null),S=a.useRef(null),_=a.useRef(0),N=a.useRef(""),x=a.useRef(!1),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(null),B=a.useRef(!1),[E,W]=a.useState(new Set),T=a.useRef(!1),G=()=>{const O=y.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<200:!0},A=a.useCallback((O="auto")=>{const F=y.current;F&&F.scrollTo({top:F.scrollHeight,behavior:O})},[]),k=a.useCallback(()=>{var ie;const O=y.current,F=(ie=window.getSelection)==null?void 0:ie.call(window);if(!O||!F||F.rangeCount===0||F.isCollapsed){B.current=!1;return}const D=F.anchorNode,me=F.focusNode;B.current=!!(D&&me&&O.contains(D)&&O.contains(me))},[]),K=a.useCallback((O="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,A(O)})},[A]),J=s.length>0?`${s.length}:${(((pe=s[s.length-1])==null?void 0:pe.content)||"").length}`:"0:0";a.useEffect(()=>{const O=!x.current,F=N.current!==d;if(N.current=d,O||F){x.current=!0,T.current=!1,v.current=!0,B.current||K("auto"),_.current=s.length;return}s.length>_.current?!T.current&&!B.current&&K("auto"):G()&&!T.current&&!B.current&&K("auto"),_.current=s.length},[J,d,c,s.length,K]),a.useEffect(()=>{l&&(T.current=!1,v.current=!0,j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{v.current=!1,j.current=null},180),B.current||K("auto"))},[K,l]),a.useEffect(()=>()=>{w.current!=null&&cancelAnimationFrame(w.current),j.current!=null&&window.clearTimeout(j.current)},[]),a.useEffect(()=>{const O=u.current;if(!O)return;const F=()=>{j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{v.current=!1,j.current=null},180)},D=new ResizeObserver(()=>{v.current&&(B.current||(K("auto"),F()))});return D.observe(O),()=>{D.disconnect(),j.current!=null&&(window.clearTimeout(j.current),j.current=null)}},[K,d]),a.useImperativeHandle(b,()=>({scrollToBottom:(O="smooth")=>{A(O)}}),[A]),a.useEffect(()=>{const O=y.current;if(!O)return;let F;const D=()=>{clearTimeout(F),F=setTimeout(()=>{T.current=!G()},50)};return O.addEventListener("scroll",D,{passive:!0}),()=>{O.removeEventListener("scroll",D),clearTimeout(F)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",k),()=>document.removeEventListener("selectionchange",k)),[k]);const L=a.useRef(0),$=a.useRef(!1);a.useEffect(()=>{const O=y.current;if(!O||!$.current||L.current===0)return;const F=O.scrollHeight-L.current;F>0&&(O.scrollTop=F),L.current=0,$.current=!1},[s.length]);const z=()=>{const O=y.current;O&&(L.current=O.scrollHeight),$.current=!0,p==null||p()},H=a.useMemo(()=>{const O=s.map((ie,X)=>({type:"message",data:ie,index:X,ts:Xi(ie,X,m)}));if(!r||r.length===0)return O;const F=[...r].sort((ie,X)=>ie.timestamp-X.timestamp).map((ie,X)=>({type:"action",data:ie,index:X,ts:ie.timestamp})),D=[];let me=0;for(const ie of O){for(;me<F.length&&ie.ts>0&&F[me].ts<ie.ts;)D.push(F[me++]);D.push(ie)}for(;me<F.length;)D.push(F[me++]);return D},[s,r,m]),Y=C>0||!!g,re=C>0?`↑ Show ${Math.min(C,80)} earlier messages${C>80?` (${C} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return e.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:e.jsxs("div",{ref:u,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..."}),Y&&!h&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:z,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${I&&C===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:re})}),H.length===0&&!Y&&(f||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),H.map(O=>{if(O.type==="action"){const ne=O.data;return e.jsx(Zi,{log:ne},`action-${O.index}`)}const F=O.data,D=O.index,me=ns(F,D),ie=F.receivedAt||m[me],X=`${d}-${me}`,be=E.has(X);return e.jsx(Qi,{message:F,receivedAt:ie,agentName:n,userName:o,isCliMode:i,isTextExpanded:be,onToggleTextExpanded:()=>W(ne=>{const le=new Set(ne);return be?le.delete(X):le.add(X),le})},`msg-${me}`)}),c&&e.jsx("div",{className:"self-start chat-typing-wrapper",children:e.jsxs("div",{className:"typing-indicator",children:[e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),e.jsx("div",{className:"min-h-10",ref:S})]})})}),tc=a.memo(ec,(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),sc="modulepreload",rc=function(t){return"/"+t},An={},nc=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(m=>{if(m=rc(m),m in An)return;An[m]=!0;const f=m.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${p}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":sc,f||(h.as="script"),h.crossOrigin="",h.href=m,d&&h.setAttribute("nonce",d),document.head.appendChild(h),f)return new Promise((g,C)=>{h.addEventListener("load",g),h.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${m}`)))})}))}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 Mn=!1;const Da=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,d]=a.useState(null),m=a.useRef([]),f=a.useRef(!1),p=a.useRef(!1),h=a.useRef(!1),g=()=>{const C=i.current;if(C){f.current&&(C.clear(),f.current=!1);for(const I of m.current)C.write(I);m.current=[],p.current&&(C.fit(),p.current=!1),h.current&&(C.bumpResize(),h.current=!1)}};return a.useImperativeHandle(o,()=>({write:C=>{i.current?i.current.write(C):m.current.push(C)},clear:()=>{i.current?i.current.clear():(m.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.current=[],f.current=!0)},resize:(C,I)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(C,I)},fit:()=>{i.current?i.current.fit():p.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():h.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const C=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(C)},[c]),a.useEffect(()=>{let C=!1;return nc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(I=>{Mn||(Mn=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),C||d(()=>I.GhosttyTerminalView)}).catch(I=>{console.error("[CliTerminal] failed to load terminal renderer",I)}),()=>{C=!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"}})});Da.displayName="CliTerminal";function Bs({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 Tn({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 ac({cursorPos:t,viewportRef:s,imgRef:r}){var u;if(!t||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(u=s.current)==null?void 0:u.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,d=n.naturalHeight||o.height,m=c/d,f=o.width/o.height;let p,h,g,C;m>f?(p=o.width,h=o.width/m,g=0,C=(o.height-h)/2):(h=o.height,p=o.height*m,g=(o.width-p)/2,C=0);const I=o.left-i.left+g+p*t.nx,l=o.top-i.top+C+h*t.ny,b=Math.max(8,Math.min(i.width-8,I)),y=Math.max(8,Math.min(i.height-8,l));return e.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 oc({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:d,handleImeSubmit:m,isConnActive:f,zoom:p,isMobile:h,mobileFillZoom:g,onZoomOut:C,onZoomReset:I,onZoomIn:l,transportType:b,screenshotUsage:y,lastActionStatus:u}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[e.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${t==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[e.jsx("span",{className:"text-sm",children:t==="mouse"?"🖱️":"👆"}),e.jsx("span",{className:`text-[10px] font-bold ${t==="mouse"?"text-blue-400":"text-slate-400"}`,children:t==="mouse"?"Mouse":"Touch"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{onClick:()=>{n(S=>!S),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:S=>S.stopPropagation(),onChange:S=>d(S.target.value),onKeyDown:S=>{m(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),e.jsx("div",{className:"relative",children:e.jsx("div",{onClick:()=>{i(S=>!S),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"})]}),p>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*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"}),y&&y.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),u&&e.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:u})]})]}),o&&e.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",p<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(p*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),C()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),e.jsx("button",{onClick:S=>{S.stopPropagation(),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:S=>{S.stopPropagation(),l()},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 ic({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 cc(){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 Ln(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 Ps(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!cc())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,Ln(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,Ln(s[c])]))}),r.current=s})}function lc({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:d,panYRef:m,setPanX:f,setPanY:p,setZoom:h,lastWheelTimeRef:g,onAction:C,setLastActionStatus:I,spawnRippleFromNormalized:l,clampPan:b,isMobile:y,mobileFillZoom:u}){const[S,_]=a.useState(null),N=a.useRef(null),x=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(null),B=a.useRef(0),E=a.useRef(null),W=a.useRef(1),T=a.useRef({x:0,y:0}),G=a.useRef(!1),A=a.useRef(n),k=a.useRef(C),K=30,J=550,L=18,$=60,z=400,H=12,Y=()=>{if(N.current)return;const O={nx:.5,ny:.5};N.current=O,_(O)};return a.useEffect(()=>{A.current=n,n==="mouse"&&Y()},[n]),a.useEffect(()=>{k.current=C},[C]),a.useEffect(()=>{const O=t.current;if(!O)return;const F=ne=>{if(!r.current)return null;const le=r.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(ne.clientY-le.top)/le.height))}},D=(ne,le)=>{if(!r.current)return{dnx:0,dny:0};const ae=r.current,de=ae.getBoundingClientRect(),q=ae.naturalWidth||de.width,se=ae.naturalHeight||de.height,te=q/se,ge=de.width/de.height;let fe,R;return te>ge?(fe=de.width,R=de.width/te):(R=de.height,fe=de.height*te),{dnx:ne/fe,dny:le/R}},me=(ne,le,ae)=>{if(ae<=1.05)return;const de=-(ne-.5)*100,q=-(le-.5)*100,se=b(de,q,ae);(Math.abs(se.x-d.current)>.1||Math.abs(se.y-m.current)>.1)&&(f(se.x),p(se.y),d.current=se.x,m.current=se.y)},ie=ne=>{const le=s.current;if(le&&ne.target instanceof Node&&le.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const ae=ne.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},w.current={x:ae.clientX,y:ae.clientY},G.current||(v.current=!1),j.current=setTimeout(()=>{if(!v.current&&!G.current)if(v.current=!0,A.current==="mouse"){const de=N.current||{nx:.5,ny:.5};I("Right Click"),l(de.nx,de.ny,"right"),k.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=F(ae);de&&(I("Right Click"),l(de.nx,de.ny,"right"),k.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){j.current&&clearTimeout(j.current),v.current=!0,G.current=!0;const ae=ne.touches[1].clientX-ne.touches[0].clientX,de=ne.touches[1].clientY-ne.touches[0].clientY;E.current=Math.sqrt(ae*ae+de*de),W.current=c.current,T.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},X=ne=>{const le=s.current;if(le&&ne.target instanceof Node&&le.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&w.current){const ae=ne.touches[0],de=ae.clientX-w.current.x,q=ae.clientY-w.current.y;if(!v.current&&x.current){const se=ae.clientX-x.current.x,te=ae.clientY-x.current.y;Math.sqrt(se*se+te*te)>8&&(v.current=!0,j.current&&clearTimeout(j.current))}if(v.current)if(A.current==="mouse"){const se=D(de,q),te=N.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,te.nx+se.dnx)),fe=Math.max(0,Math.min(1,te.ny+se.dny));N.current={nx:ge,ny:fe},_({nx:ge,ny:fe}),I(`Cursor: ${Math.round(ge*100)}%, ${Math.round(fe*100)}%`),me(ge,fe,c.current);const R=Date.now();R-g.current>=30&&(g.current=R,k.current("input_mouseMoved",{nx:ge,ny:fe}).catch(()=>{}))}else if(c.current>1){const se=s.current;if(se){const te=se.clientWidth,ge=se.clientHeight,fe=d.current+de/te*100,R=m.current+q/ge*100,xe=b(fe,R,c.current);f(xe.x),p(xe.y),d.current=xe.x,m.current=xe.y}}else{const se=F(ae);if(se){const te=Date.now();te-g.current>=40&&(g.current=te,I("Scroll"),k.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-q*2.5)}).catch(()=>{}))}}w.current={x:ae.clientX,y:ae.clientY};return}if(ne.touches.length===2&&E.current!==null){const ae=ne.touches[1].clientX-ne.touches[0].clientX,de=ne.touches[1].clientY-ne.touches[0].clientY,se=Math.sqrt(ae*ae+de*de)/E.current,te=(ne.touches[0].clientX+ne.touches[1].clientX)/2,ge=(ne.touches[0].clientY+ne.touches[1].clientY)/2,fe=te-T.current.x,R=ge-T.current.y,xe=Math.abs(se-1)>.03;if(A.current==="mouse"){if(xe){const M=Math.max(i,Math.min(5,W.current*se));h(M),c.current=M}else if(Math.abs(fe)>2||Math.abs(R)>2){const M=N.current||{nx:.5,ny:.5},U=Date.now();U-g.current>=30&&(g.current=U,I("Scroll"),k.current("input_wheel",{nx:M.nx,ny:M.ny,deltaX:Math.round(-fe*3),deltaY:Math.round(-R*3)}).catch(()=>{}))}}else{const M=Math.max(i,Math.min(5,W.current*se));h(M),c.current=M;const U=s.current;if(U&&M>1){const ee=U.clientWidth,Q=U.clientHeight,ce=d.current+fe/ee*100,Ne=m.current+R/Q*100,Pe=b(ce,Ne,M);f(Pe.x),p(Pe.y),d.current=Pe.x,m.current=Pe.y}}T.current={x:te,y:ge}}},be=ne=>{var le;if(j.current&&clearTimeout(j.current),E.current=null,ne.touches.length===1&&G.current){const ae=ne.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},w.current={x:ae.clientX,y:ae.clientY},v.current=!0;return}if(ne.touches.length===0){if(G.current){G.current=!1,v.current=!1;return}if(ne.changedTouches.length===1){const ae=ne.changedTouches[0],de=Date.now(),q=de-(((le=x.current)==null?void 0:le.time)||0),se=x.current?ae.clientX-x.current.x:0,te=x.current?ae.clientY-x.current.y:0,ge=Math.sqrt(se*se+te*te);if(A.current==="mouse"){if(q<K||q>J||ge>L){v.current=!1;return}const fe=N.current||F(ae);fe&&(I(`Click: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),l(fe.nx,fe.ny,"left"),k.current("input_click",{...fe}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(q<$||q>z||ge>H){v.current=!1;return}const fe=F(ae);if(!fe)return;de-B.current<300?(I("Double tap"),l(fe.nx,fe.ny,"double"),k.current("input_click",{...fe,clickCount:2}).catch(()=>{}),B.current=0):(I(`Tap: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),l(fe.nx,fe.ny,"left"),k.current("input_click",{...fe}).catch(()=>{}),B.current=de)}}v.current=!1}};return O.addEventListener("touchstart",ie,{passive:!1}),O.addEventListener("touchmove",X,{passive:!1}),O.addEventListener("touchend",be,{passive:!1}),()=>{O.removeEventListener("touchstart",ie),O.removeEventListener("touchmove",X),O.removeEventListener("touchend",be),j.current&&clearTimeout(j.current)}},[t,s,r,i,c,d,m,f,p,h,g,I,l,b]),{cursorPos:S,cursorPosRef:N,handleToggleInputMode:()=>{o(O=>{const F=O==="touch"?"mouse":"touch";return F==="mouse"&&Y(),F})},handleZoomReset:()=>{const O=y?u:1;h(O),c.current=O,f(0),p(0),d.current=0,m.current=0}}}function Ba({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),d=a.useRef(null),m=a.useRef(null),[f,p]=a.useState(null),[h,g]=a.useState(""),[,C]=a.useState(!1),[I,l]=a.useState([]),b=a.useRef(0),[y,u]=a.useState(!1),[S,_]=a.useState(!1),N=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,w]=a.useState(N?"mouse":"touch"),[v,j]=a.useState(1),B=a.useRef(!1),[E,W]=a.useState(1),[T,G]=a.useState(0),[A,k]=a.useState(0);Ps("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:E,panX:T,panY:A,isMenuOpen:y,isImeOpen:S});const K=a.useRef(0),J=a.useRef(E),L=a.useRef(T),$=a.useRef(A);a.useEffect(()=>{J.current=E},[E]),a.useEffect(()=>{L.current=T},[T]),a.useEffect(()=>{$.current=A},[A]),a.useEffect(()=>{var q;(q=c.current)==null||q.focus()},[]);const z=r==="connected",H=n,Y=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!N||B.current||!H)return;const q=m.current,se=d.current;if(!q||!se)return;const te=()=>{const ge=se.clientWidth,fe=se.clientHeight,R=q.naturalWidth,xe=q.naturalHeight;if(!R||!xe||!ge||!fe)return;const M=Math.min(ge/R,fe/xe),ee=Math.max(ge/R,fe/xe)/M;ee>1.01&&(j(ee),W(ee),J.current=ee),B.current=!0};q.complete&&q.naturalWidth?te():q.addEventListener("load",te,{once:!0})},[H,N]);const pe=.5;a.useEffect(()=>{E<=pe&&(G(0),k(0))},[E,pe]);const O=(q,se,te)=>{if(te<=pe)return{x:0,y:0};const ge=(te-1)/(2*te)*100,fe=(te-1)/(2*te)*100;return{x:Math.max(-ge,Math.min(ge,q)),y:Math.max(-fe,Math.min(fe,se))}},F=(q,se)=>{if(!m.current)return null;const te=m.current.getBoundingClientRect();return!te.width||!te.height?null:{nx:Math.max(0,Math.min(1,(q-te.left)/te.width)),ny:Math.max(0,Math.min(1,(se-te.top)/te.height))}},D=(q,se,te)=>{const ge=d.current;if(!ge)return;const fe=ge.getBoundingClientRect(),R=++b.current;l(xe=>[...xe,{id:R,x:q-fe.left,y:se-fe.top,type:te}]),setTimeout(()=>l(xe=>xe.filter(M=>M.id!==R)),600)},me=(q,se,te)=>{const ge=m.current,fe=d.current;if(!ge||!fe)return;const R=ge.getBoundingClientRect(),xe=fe.getBoundingClientRect(),M=ge.naturalWidth||R.width,U=ge.naturalHeight||R.height,ee=M/U,Q=R.width/R.height;let ce,Ne,Pe,De;ee>Q?(ce=R.width,Ne=R.width/ee,Pe=0,De=(R.height-Ne)/2):(Ne=R.height,ce=R.height*ee,Pe=(R.width-ce)/2,De=0);const Re=R.left-xe.left+Pe+ce*q,ot=R.top-xe.top+De+Ne*se,Qe=++b.current;l(ze=>[...ze,{id:Qe,x:Re,y:ot,type:te}]),setTimeout(()=>l(ze=>ze.filter(et=>et.id!==Qe)),600)},ie=async q=>{var te;const se=F(q.clientX,q.clientY);if(se){p(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),D(q.clientX,q.clientY,"left"),(te=c.current)==null||te.focus();try{const ge=await t("input_click",{nx:se.nx,ny:se.ny});ge!=null&&ge.success||s(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){s(`❌ Click error: ${ge.message||ge}`)}}},X=async(q,se,te,ge=0)=>{try{await t("input_key",{type:te?"char":"keyDown",key:q,code:se,text:te?q:void 0,unmodifiedText:te?q:void 0,modifiers:ge})}catch(fe){s(`❌ Key error: ${fe.message||fe}`)}},be=async q=>{if(q.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(q.key)&&q.preventDefault();let te=0;q.altKey&&(te|=1),q.ctrlKey&&(te|=2),q.metaKey&&(te|=4),q.shiftKey&&(te|=8),p(`Key: ${q.key}`),await X(q.key,q.code,q.key.length===1,te)},ne=async q=>{if(q.key==="Enter"){if(q.nativeEvent.isComposing)return;if(h){const se=h;g(""),p(`IME Sent: ${se}`);try{const te=await t("input_type",{text:se});te!=null&&te.success||s(`❌ IME error: ${te==null?void 0:te.error}`)}catch(te){s(`❌ IME error: ${te.message}`)}}else p("Key: Enter"),await X("Enter","Enter",!1)}};a.useEffect(()=>{const q=c.current;if(!q)return;const se=te=>{var ge;if((ge=m.current)!=null&&ge.contains(te.target)){te.preventDefault();const fe=Date.now();if(fe-K.current<40)return;K.current=fe;const R=F(te.clientX,te.clientY);if(!R)return;p(`Scroll: ${Math.round(te.deltaY)}`),t("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(te.deltaX),deltaY:Math.round(te.deltaY)}).catch(()=>{})}};return q.addEventListener("wheel",se,{passive:!1}),()=>q.removeEventListener("wheel",se)},[t]);const{cursorPos:le,handleToggleInputMode:ae,handleZoomReset:de}=lc({containerRef:c,viewportRef:d,imgRef:m,inputMode:x,setInputMode:w,minZoom:pe,zoomRef:J,panXRef:L,panYRef:$,setPanX:G,setPanY:k,setZoom:W,lastWheelTimeRef:K,onAction:t,setLastActionStatus:p,spawnRippleFromNormalized:me,clampPan:O,isMobile:N,mobileFillZoom:v});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:be,onContextMenu:q=>q.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[e.jsxs("div",{ref:d,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[H?e.jsx("img",{ref:m,src:H,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${E}) translate(${T}%, ${A}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:q=>q.preventDefault(),onDragStart:q=>q.preventDefault()}):e.jsx(ic,{waitingLabel:Y,waitingHint:re,transportType:i}),x==="mouse"&&H&&e.jsx(ac,{cursorPos:le,viewportRef:d,imgRef:m}),I.map(q=>{const te={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[q.type];return e.jsxs("div",{style:{position:"absolute",left:q.x,top:q.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${te}, 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(${te}, 0.9)`,boxShadow:`0 0 12px rgba(${te}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},q.id)})]}),e.jsx(oc,{inputMode:x,onToggleInputMode:ae,isImeOpen:S,setIsImeOpen:_,isMenuOpen:y,setIsMenuOpen:u,imeText:h,setImeText:g,handleImeSubmit:ne,isConnActive:z,zoom:E,isMobile:N,mobileFillZoom:v,onZoomOut:()=>W(q=>Math.max(.5,q-.25)),onZoomReset:de,onZoomIn:()=>W(q=>Math.min(5,q+.25)),transportType:i,screenshotUsage:o,lastActionStatus:f}),e.jsx("style",{children:`
|
|
2
|
+
var ci=Object.defineProperty;var li=(t,s,r)=>s in t?ci(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var qe=(t,s,r)=>li(t,typeof s!="symbol"?s+"":s,r);import{r as a,j as e,M as ka,a as Na,b as di,c as ui,u as ds,R as Ge,d as Sa,t as mi,e as pi,D as fi,f as xi,g as hi,h as Xr,i as bi,k as gi,B as yi,l as vi,m as Ot,N as Wr,n as wi}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)}})();const Ca=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}),Ia=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Cn(t){var r,n;let s=0;return"activeChat"in t&&(s+=4),(r=t.childSessions)!=null&&r.length&&(s+=2),t.workspace&&(s+=1),t.machine&&(s+=1),(n=t.agents)!=null&&n.length&&(s+=1),s}function vr(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;return o&&(n.version=o),i&&(n.serverVersion=i),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),n)}function sr(t){return Array.isArray(t)?t.map(sr):!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,sr(r)]))}function ji(t,s){try{return JSON.stringify(sr(t))===JSON.stringify(sr(s))}catch{return!1}}function Ds(t,s,r){return ji(t,s)?(t._lastUpdate=r,typeof s.timestamp=="number"&&(t.timestamp=s.timestamp),t):s}function ki(t,s,r){var m,f,p,h,g,C,I;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return t.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of t){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const y=Cn(d),l=Cn(b);if(y>l){const S=(m=d.chats)!=null&&m.length?d.chats:b.chats,M=vr(b,d,{...b,...d,chats:S,_lastUpdate:n});i.set(d.id,Ds(b,M,n))}else if(y<l){const S={};if(d.status&&d.status!==b.status&&(S.status=d.status),d.cdpConnected!==void 0&&(S.cdpConnected=d.cdpConnected),(f=d.chats)!=null&&f.length&&!((p=b.chats)!=null&&p.length)&&(S.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(S.machineNickname=d.machineNickname),d.version!==void 0&&(S.version=d.version),d.serverVersion!==void 0&&(S.serverVersion=d.serverVersion),d.versionMismatch===!0&&(S.versionMismatch=!0),Object.keys(S).length>0){const M=vr(b,d,{...b,...S,_lastUpdate:b._lastUpdate});i.set(d.id,Ds(b,M,n))}else Ds(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const S=d.timestamp||n,M=b._lastUpdate||b.timestamp||0;if(S>=M){const N=(h=d.chats)!=null&&h.length?d.chats:b.chats,x=vr(b,d,{...b,...d,chats:N,_lastUpdate:n});i.set(d.id,Ds(b,x,n))}else(g=d.chats)!=null&&g.length&&!((C=b.chats)!=null&&C.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(t.map(d=>d.id)),u=new Set;for(const d of t){const b=d.daemonId||((I=d.id)==null?void 0:I.split(":")[0]);b&&u.add(b)}for(const[d,b]of i){const y=b.daemonId||d.split(":")[0];if(!u.has(y))continue;if(o.has(y)&&!c.has(d)){i.delete(d);continue}const l=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&l>1e4||b.transport==="acp"&&!c.has(d)&&l>1e4||b.transport==="cdp-page"&&!c.has(d)&&l>3e4)&&i.delete(d)}for(const[d,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(d);return Array.from(i.values())}function Ni(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 Si({children:t,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,u]=a.useState([]),[m,f]=a.useState(void 0),p=a.useRef(r);a.useEffect(()=>{p.current=r},[r]);const h=a.useCallback((y,l)=>{n(S=>{let M=!1;const N=S.map(x=>x.id!==y||x.chats===l?x:(M=!0,{...x,chats:l}));return M?N:S})},[]),g=a.useCallback((y,l)=>{n(S=>{const M=S.length===0?y:ki(y,S,l);return Ni(S,M)?S:M})},[]),C=a.useCallback(()=>i(!0),[]),I=a.useMemo(()=>({injectEntries:g,markLoaded:C,getIdes:()=>p.current}),[g,C]),d=s,b=a.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:o,toasts:c,setToasts:u,wsStatus:(d==null?void 0:d.wsStatus)??"connected",isConnected:(d==null?void 0:d.isConnected)??!0,connectionStates:(d==null?void 0:d.connectionStates)??{},connectionTransports:(d==null?void 0:d.connectionTransports)??{},showReconnected:(d==null?void 0:d.showReconnected)??!1,retryConnection:d==null?void 0:d.retryConnection,isP2PActive:(d==null?void 0:d.isP2PActive)??!1,p2pStates:(d==null?void 0:d.p2pStates)??{},userRole:d==null?void 0:d.userRole,userName:m,setUserName:f}),[r,h,o,c,d==null?void 0:d.wsStatus,d==null?void 0:d.isConnected,d==null?void 0:d.connectionStates,d==null?void 0:d.connectionTransports,d==null?void 0:d.showReconnected,d==null?void 0:d.retryConnection,d==null?void 0:d.isP2PActive,d==null?void 0:d.p2pStates,d==null?void 0:d.userRole,m]);return e.jsx(Ia.Provider,{value:I,children:e.jsx(Ca.Provider,{value:b,children:t})})}function Yt(){return a.useContext(Ca)}function rr(){return a.useContext(Ia)}function Ma(t){const{baseUrl:s,getToken:r,onUnauthorized:n}=t;function o(u){return u.startsWith("http")?u:`${s}${u.startsWith("/")?"":"/"}${u}`}function i(u){const m=r==null?void 0:r(),f=o(u),p=u.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return m&&p.searchParams.set("token",m),!u.startsWith("http")&&!s?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function c(u,m={}){const f={"Content-Type":"application/json",...m.headers||{}},p=r==null?void 0:r();p&&(f.Authorization=`Bearer ${p}`);const h=o(u),g=new AbortController,C=setTimeout(()=>g.abort(),15e3);try{const I=await fetch(h,{...m,headers:f,signal:g.signal});if(I.status===401)throw n==null||n(),new Error("Unauthorized");if(!I.ok){const d=await I.json().catch(()=>({error:I.statusText}));throw new Error(d.error||`API Error: ${I.status}`)}return I.json()}finally{clearTimeout(C)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:u=>c(`/api/v1/daemons/${u}/status`),sendCommand:(u,m,f={})=>c(`/api/v1/daemons/${u}/command`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),execTerminal:(u,m,f)=>c(`/api/v1/daemons/${u}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:f})}),sendAgentMessage:(u,m,f)=>c(`/api/v1/shortcuts/${u}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:f})}),getAgentStatus:u=>c(`/api/v1/shortcuts/${u}/status`),approveAgent:(u,m,f)=>c(`/api/v1/shortcuts/${u}/approve`,{method:"POST",body:JSON.stringify({agentType:m,action:f?"approve":"reject"})}),getMuxState:u=>c(`/api/v1/mux/${encodeURIComponent(u)}/state`),getMuxSocketInfo:u=>c(`/api/v1/mux/${encodeURIComponent(u)}/socket-info`),controlMux:(u,m,f={})=>c(`/api/v1/mux/${encodeURIComponent(u)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),getMuxEventsUrl:u=>i(`/api/v1/mux/${encodeURIComponent(u)}/events`),getRuntimeEventsUrl:u=>i(`/api/v1/runtime/${encodeURIComponent(u)}/events`),request:c}}const Ci=Ma({baseUrl:"http://localhost:3847"}),Ii=a.createContext(Ci);function Mi({client:t,children:s}){return e.jsx(Ii.Provider,{value:t,children:s})}const _i={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},_a=a.createContext(_i);function Ai({value:t,children:s}){return e.jsx(_a.Provider,{value:t,children:s})}function mt(){return a.useContext(_a)}const Pe={size:18};function Aa({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),e.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Jr({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Bt({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),e.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),e.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),e.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Zr({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Ti({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Pi({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Ta({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),e.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),e.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),e.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Li({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),e.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),e.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),e.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),e.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function cr({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Pa({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("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 Ri({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Lt({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ut({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Qr({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),e.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ei({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function cs({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function us({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Xt({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Is({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("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 La({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function $i({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),e.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),e.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Ra({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Di({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),e.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),e.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function lr({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polyline",{points:"4 17 10 11 4 5"}),e.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Bi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function en({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Ki({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function bt({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ea({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),e.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),e.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),e.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Wi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),e.jsx("path",{d:"M12 2v6"}),e.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Oi({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function zi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),e.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function dr({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"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 Hi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("circle",{cx:"12",cy:"12",r:"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 Ui({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Fi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",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 Vi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),e.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gi({size:t=Pe.size,className:s}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:e.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function qi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Yi({size:t=Pe.size,className:s}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),e.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),e.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function In(t){return!!t&&typeof t=="object"&&"text"in t}function tn(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:In(i)?String(i.text||""):"").join(r):In(t)?o=String(t.text||""):o=String(t||""),n?o.replace(/\s+/g," ").trim():o}function Jt(t){return tn(t,{normalizeWhitespace:!0})}function $a(t){return t?new Date(t).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Xi(t,s,r){return Number(t.receivedAt||r[ns(t,s)]||0)||0}function Ji(t){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(t)}function ns(t,s){const r=t,n=tn(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 Mn=5e3,Zi=a.memo(function({log:s}){return e.jsxs("div",{className:"self-center chat-msg-action",children:[e.jsx(ka,{remarkPlugins:[Na],children:s.text}),e.jsx("span",{className:"action-time",children:$a(s.timestamp)})]})},(t,s)=>t.log===s.log),Qi=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:u}){var M,N,x;const m=(s.role||"").toLowerCase(),f=m==="user"||m==="human",p=s.kind||(m==="tool"?"tool":"standard"),h=tn(s.content,{joiner:`
|
|
4
|
+
`});if(p==="thought"){const w=typeof((M=s.meta)==null?void 0:M.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(Oi,{size:13}),e.jsx("span",{children:w})]}),e.jsx("div",{className:"chat-msg-body",children:h})]})}if(p==="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(p==="terminal"){const w=(N=s.meta)!=null&&N.isRunning?"⏳":"✅",v=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:w}),e.jsx("span",{children:v})]}),e.jsx("pre",{className:"chat-msg-body",children:h})]})}if(p==="system")return e.jsx("div",{className:"self-center chat-msg-system",children:h.slice(0,100)});const g=s.meta,I=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",d=h,b=i&&!f&&!I&&d.length>Mn,y=b&&!c?d.slice(0,Mn):d,l=I,S=!l&&Ji(y);return e.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(d||f)&&e.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[e.jsxs("div",{className:`chat-bubble-header ${d?"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:$a(r)})]}),d&&e.jsx("div",{className:"chat-markdown",children:l?e.jsx("pre",{className:"chat-preformatted",children:y}):S?e.jsx(ka,{remarkPlugins:[Na,di,ui],children:y}):e.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),b&&e.jsx("button",{onClick:u,className:"mt-1.5 text-[11px] font-semibold text-[var(--accent-primary)] p-0 opacity-80",children:c?"Collapse ↑":`Show more (${Math.round(d.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),ec=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:u="",receivedAtMap:m={},emptyState:f,onLoadMore:p,isLoadingMore:h,hasMoreHistory:g,hiddenLiveCount:C=0,loadError:I,scrollToBottomRequestNonce:d},b){var pe;const y=a.useRef(null),l=a.useRef(null),S=a.useRef(null),M=a.useRef(0),N=a.useRef(""),x=a.useRef(!1),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(null),B=a.useRef(!1),[E,W]=a.useState(new Set),T=a.useRef(!1),G=()=>{const O=y.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<200:!0},_=a.useCallback((O="auto")=>{const F=y.current;F&&F.scrollTo({top:F.scrollHeight,behavior:O})},[]),k=a.useCallback(()=>{var ie;const O=y.current,F=(ie=window.getSelection)==null?void 0:ie.call(window);if(!O||!F||F.rangeCount===0||F.isCollapsed){B.current=!1;return}const D=F.anchorNode,me=F.focusNode;B.current=!!(D&&me&&O.contains(D)&&O.contains(me))},[]),K=a.useCallback((O="auto")=>{w.current!=null&&cancelAnimationFrame(w.current),w.current=requestAnimationFrame(()=>{w.current=null,_(O)})},[_]),J=s.length>0?`${s.length}:${(((pe=s[s.length-1])==null?void 0:pe.content)||"").length}`:"0:0";a.useEffect(()=>{const O=!x.current,F=N.current!==u;if(N.current=u,O||F){x.current=!0,T.current=!1,v.current=!0,B.current||K("auto"),M.current=s.length;return}s.length>M.current?!T.current&&!B.current&&K("auto"):G()&&!T.current&&!B.current&&K("auto"),M.current=s.length},[J,u,c,s.length,K]),a.useEffect(()=>{d&&(T.current=!1,v.current=!0,j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{v.current=!1,j.current=null},180),B.current||K("auto"))},[K,d]),a.useEffect(()=>()=>{w.current!=null&&cancelAnimationFrame(w.current),j.current!=null&&window.clearTimeout(j.current)},[]),a.useEffect(()=>{const O=l.current;if(!O)return;const F=()=>{j.current!=null&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{v.current=!1,j.current=null},180)},D=new ResizeObserver(()=>{v.current&&(B.current||(K("auto"),F()))});return D.observe(O),()=>{D.disconnect(),j.current!=null&&(window.clearTimeout(j.current),j.current=null)}},[K,u]),a.useImperativeHandle(b,()=>({scrollToBottom:(O="smooth")=>{_(O)}}),[_]),a.useEffect(()=>{const O=y.current;if(!O)return;let F;const D=()=>{clearTimeout(F),F=setTimeout(()=>{T.current=!G()},50)};return O.addEventListener("scroll",D,{passive:!0}),()=>{O.removeEventListener("scroll",D),clearTimeout(F)}},[]),a.useEffect(()=>(document.addEventListener("selectionchange",k),()=>document.removeEventListener("selectionchange",k)),[k]);const P=a.useRef(0),$=a.useRef(!1);a.useEffect(()=>{const O=y.current;if(!O||!$.current||P.current===0)return;const F=O.scrollHeight-P.current;F>0&&(O.scrollTop=F),P.current=0,$.current=!1},[s.length]);const z=()=>{const O=y.current;O&&(P.current=O.scrollHeight),$.current=!0,p==null||p()},U=a.useMemo(()=>{const O=s.map((ie,X)=>({type:"message",data:ie,index:X,ts:Xi(ie,X,m)}));if(!r||r.length===0)return O;const F=[...r].sort((ie,X)=>ie.timestamp-X.timestamp).map((ie,X)=>({type:"action",data:ie,index:X,ts:ie.timestamp})),D=[];let me=0;for(const ie of O){for(;me<F.length&&ie.ts>0&&F[me].ts<ie.ts;)D.push(F[me++]);D.push(ie)}for(;me<F.length;)D.push(F[me++]);return D},[s,r,m]),Y=C>0||!!g,re=C>0?`↑ Show ${Math.min(C,80)} earlier messages${C>80?` (${C} hidden)`:""}`:I?`↻ ${I}`:"↑ Load older messages";return e.jsx("div",{ref:y,"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..."}),Y&&!h&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{onClick:z,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${I&&C===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:re})}),U.length===0&&!Y&&(f||e.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),U.map(O=>{if(O.type==="action"){const ne=O.data;return e.jsx(Zi,{log:ne},`action-${O.index}`)}const F=O.data,D=O.index,me=ns(F,D),ie=F.receivedAt||m[me],X=`${u}-${me}`,be=E.has(X);return e.jsx(Qi,{message:F,receivedAt:ie,agentName:n,userName:o,isCliMode:i,isTextExpanded:be,onToggleTextExpanded:()=>W(ne=>{const le=new Set(ne);return be?le.delete(X):le.add(X),le})},`msg-${me}`)}),c&&e.jsx("div",{className:"self-start chat-typing-wrapper",children:e.jsxs("div",{className:"typing-indicator",children:[e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("div",{className:"dot"}),e.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),e.jsx("div",{className:"min-h-10",ref:S})]})})}),tc=a.memo(ec,(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),sc="modulepreload",rc=function(t){return"/"+t},_n={},nc=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(m=>{if(m=rc(m),m in _n)return;_n[m]=!0;const f=m.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${p}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":sc,f||(h.as="script"),h.crossOrigin="",h.href=m,u&&h.setAttribute("nonce",u),document.head.appendChild(h),f)return new Promise((g,C)=>{h.addEventListener("load",g),h.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return o.then(c=>{for(const u of c||[])u.status==="rejected"&&i(u.reason);return s().catch(i)})};let An=!1;const Da=a.forwardRef(({onInput:t,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,u]=a.useState(null),m=a.useRef([]),f=a.useRef(!1),p=a.useRef(!1),h=a.useRef(!1),g=()=>{const C=i.current;if(C){f.current&&(C.clear(),f.current=!1);for(const I of m.current)C.write(I);m.current=[],p.current&&(C.fit(),p.current=!1),h.current&&(C.bumpResize(),h.current=!1)}};return a.useImperativeHandle(o,()=>({write:C=>{i.current?i.current.write(C):m.current.push(C)},clear:()=>{i.current?i.current.clear():(m.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.current=[],f.current=!0)},resize:(C,I)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(C,I)},fit:()=>{i.current?i.current.fit():p.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():h.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const C=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(C)},[c]),a.useEffect(()=>{let C=!1;return nc(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(I=>{An||(An=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),C||u(()=>I.GhosttyTerminalView)}).catch(I=>{console.error("[CliTerminal] failed to load terminal renderer",I)}),()=>{C=!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"}})});Da.displayName="CliTerminal";function Bs({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 Tn({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,u=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:u}})})]}):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, ${u}, ${u}cc)`}})}),o&&e.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function ac({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,u=n.naturalHeight||o.height,m=c/u,f=o.width/o.height;let p,h,g,C;m>f?(p=o.width,h=o.width/m,g=0,C=(o.height-h)/2):(h=o.height,p=o.height*m,g=(o.width-p)/2,C=0);const I=o.left-i.left+g+p*t.nx,d=o.top-i.top+C+h*t.ny,b=Math.max(8,Math.min(i.width-8,I)),y=Math.max(8,Math.min(i.height-8,d));return e.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 oc({inputMode:t,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:u,handleImeSubmit:m,isConnActive:f,zoom:p,isMobile:h,mobileFillZoom:g,onZoomOut:C,onZoomReset:I,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:l}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[e.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${t==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[e.jsx("span",{className:"text-sm",children:t==="mouse"?"🖱️":"👆"}),e.jsx("span",{className:`text-[10px] font-bold ${t==="mouse"?"text-blue-400":"text-slate-400"}`,children:t==="mouse"?"Mouse":"Touch"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{onClick:()=>{n(S=>!S),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:S=>S.stopPropagation(),onChange:S=>u(S.target.value),onKeyDown:S=>{m(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),e.jsx("div",{className:"relative",children:e.jsx("div",{onClick:()=>{i(S=>!S),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"})]}),p>1&&e.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*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"}),y&&y.dailyBudgetMinutes>0&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.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:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[e.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",p<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(p*100)}%`]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{onClick:S=>{S.stopPropagation(),C()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),e.jsx("button",{onClick:S=>{S.stopPropagation(),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:S=>{S.stopPropagation(),d()},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 ic({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 cc(){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 Pn(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 Ls(t,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!cc())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,u])=>[c,Pn(u)]))}),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,Pn(s[c])]))}),r.current=s})}function lc({containerRef:t,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:u,panYRef:m,setPanX:f,setPanY:p,setZoom:h,lastWheelTimeRef:g,onAction:C,setLastActionStatus:I,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:l}){const[S,M]=a.useState(null),N=a.useRef(null),x=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(null),B=a.useRef(0),E=a.useRef(null),W=a.useRef(1),T=a.useRef({x:0,y:0}),G=a.useRef(!1),_=a.useRef(n),k=a.useRef(C),K=30,J=550,P=18,$=60,z=400,U=12,Y=()=>{if(N.current)return;const O={nx:.5,ny:.5};N.current=O,M(O)};return a.useEffect(()=>{_.current=n,n==="mouse"&&Y()},[n]),a.useEffect(()=>{k.current=C},[C]),a.useEffect(()=>{const O=t.current;if(!O)return;const F=ne=>{if(!r.current)return null;const le=r.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(ne.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(ne.clientY-le.top)/le.height))}},D=(ne,le)=>{if(!r.current)return{dnx:0,dny:0};const ae=r.current,de=ae.getBoundingClientRect(),q=ae.naturalWidth||de.width,se=ae.naturalHeight||de.height,te=q/se,ge=de.width/de.height;let fe,R;return te>ge?(fe=de.width,R=de.width/te):(R=de.height,fe=de.height*te),{dnx:ne/fe,dny:le/R}},me=(ne,le,ae)=>{if(ae<=1.05)return;const de=-(ne-.5)*100,q=-(le-.5)*100,se=b(de,q,ae);(Math.abs(se.x-u.current)>.1||Math.abs(se.y-m.current)>.1)&&(f(se.x),p(se.y),u.current=se.x,m.current=se.y)},ie=ne=>{const le=s.current;if(le&&ne.target instanceof Node&&le.contains(ne.target))ne.preventDefault();else return;if(ne.touches.length===1){const ae=ne.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},w.current={x:ae.clientX,y:ae.clientY},G.current||(v.current=!1),j.current=setTimeout(()=>{if(!v.current&&!G.current)if(v.current=!0,_.current==="mouse"){const de=N.current||{nx:.5,ny:.5};I("Right Click"),d(de.nx,de.ny,"right"),k.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=F(ae);de&&(I("Right Click"),d(de.nx,de.ny,"right"),k.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(ne.touches.length===2){j.current&&clearTimeout(j.current),v.current=!0,G.current=!0;const ae=ne.touches[1].clientX-ne.touches[0].clientX,de=ne.touches[1].clientY-ne.touches[0].clientY;E.current=Math.sqrt(ae*ae+de*de),W.current=c.current,T.current={x:(ne.touches[0].clientX+ne.touches[1].clientX)/2,y:(ne.touches[0].clientY+ne.touches[1].clientY)/2}}},X=ne=>{const le=s.current;if(le&&ne.target instanceof Node&&le.contains(ne.target)&&ne.preventDefault(),ne.touches.length===1&&w.current){const ae=ne.touches[0],de=ae.clientX-w.current.x,q=ae.clientY-w.current.y;if(!v.current&&x.current){const se=ae.clientX-x.current.x,te=ae.clientY-x.current.y;Math.sqrt(se*se+te*te)>8&&(v.current=!0,j.current&&clearTimeout(j.current))}if(v.current)if(_.current==="mouse"){const se=D(de,q),te=N.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,te.nx+se.dnx)),fe=Math.max(0,Math.min(1,te.ny+se.dny));N.current={nx:ge,ny:fe},M({nx:ge,ny:fe}),I(`Cursor: ${Math.round(ge*100)}%, ${Math.round(fe*100)}%`),me(ge,fe,c.current);const R=Date.now();R-g.current>=30&&(g.current=R,k.current("input_mouseMoved",{nx:ge,ny:fe}).catch(()=>{}))}else if(c.current>1){const se=s.current;if(se){const te=se.clientWidth,ge=se.clientHeight,fe=u.current+de/te*100,R=m.current+q/ge*100,xe=b(fe,R,c.current);f(xe.x),p(xe.y),u.current=xe.x,m.current=xe.y}}else{const se=F(ae);if(se){const te=Date.now();te-g.current>=40&&(g.current=te,I("Scroll"),k.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-q*2.5)}).catch(()=>{}))}}w.current={x:ae.clientX,y:ae.clientY};return}if(ne.touches.length===2&&E.current!==null){const ae=ne.touches[1].clientX-ne.touches[0].clientX,de=ne.touches[1].clientY-ne.touches[0].clientY,se=Math.sqrt(ae*ae+de*de)/E.current,te=(ne.touches[0].clientX+ne.touches[1].clientX)/2,ge=(ne.touches[0].clientY+ne.touches[1].clientY)/2,fe=te-T.current.x,R=ge-T.current.y,xe=Math.abs(se-1)>.03;if(_.current==="mouse"){if(xe){const A=Math.max(i,Math.min(5,W.current*se));h(A),c.current=A}else if(Math.abs(fe)>2||Math.abs(R)>2){const A=N.current||{nx:.5,ny:.5},H=Date.now();H-g.current>=30&&(g.current=H,I("Scroll"),k.current("input_wheel",{nx:A.nx,ny:A.ny,deltaX:Math.round(-fe*3),deltaY:Math.round(-R*3)}).catch(()=>{}))}}else{const A=Math.max(i,Math.min(5,W.current*se));h(A),c.current=A;const H=s.current;if(H&&A>1){const ee=H.clientWidth,Q=H.clientHeight,ce=u.current+fe/ee*100,Ne=m.current+R/Q*100,Le=b(ce,Ne,A);f(Le.x),p(Le.y),u.current=Le.x,m.current=Le.y}}T.current={x:te,y:ge}}},be=ne=>{var le;if(j.current&&clearTimeout(j.current),E.current=null,ne.touches.length===1&&G.current){const ae=ne.touches[0];x.current={x:ae.clientX,y:ae.clientY,time:Date.now()},w.current={x:ae.clientX,y:ae.clientY},v.current=!0;return}if(ne.touches.length===0){if(G.current){G.current=!1,v.current=!1;return}if(ne.changedTouches.length===1){const ae=ne.changedTouches[0],de=Date.now(),q=de-(((le=x.current)==null?void 0:le.time)||0),se=x.current?ae.clientX-x.current.x:0,te=x.current?ae.clientY-x.current.y:0,ge=Math.sqrt(se*se+te*te);if(_.current==="mouse"){if(q<K||q>J||ge>P){v.current=!1;return}const fe=N.current||F(ae);fe&&(I(`Click: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),d(fe.nx,fe.ny,"left"),k.current("input_click",{...fe}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(q<$||q>z||ge>U){v.current=!1;return}const fe=F(ae);if(!fe)return;de-B.current<300?(I("Double tap"),d(fe.nx,fe.ny,"double"),k.current("input_click",{...fe,clickCount:2}).catch(()=>{}),B.current=0):(I(`Tap: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),d(fe.nx,fe.ny,"left"),k.current("input_click",{...fe}).catch(()=>{}),B.current=de)}}v.current=!1}};return O.addEventListener("touchstart",ie,{passive:!1}),O.addEventListener("touchmove",X,{passive:!1}),O.addEventListener("touchend",be,{passive:!1}),()=>{O.removeEventListener("touchstart",ie),O.removeEventListener("touchmove",X),O.removeEventListener("touchend",be),j.current&&clearTimeout(j.current)}},[t,s,r,i,c,u,m,f,p,h,g,I,d,b]),{cursorPos:S,cursorPosRef:N,handleToggleInputMode:()=>{o(O=>{const F=O==="touch"?"mouse":"touch";return F==="mouse"&&Y(),F})},handleZoomReset:()=>{const O=y?l:1;h(O),c.current=O,f(0),p(0),u.current=0,m.current=0}}}function Ba({onAction:t,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),u=a.useRef(null),m=a.useRef(null),[f,p]=a.useState(null),[h,g]=a.useState(""),[,C]=a.useState(!1),[I,d]=a.useState([]),b=a.useRef(0),[y,l]=a.useState(!1),[S,M]=a.useState(!1),N=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,w]=a.useState(N?"mouse":"touch"),[v,j]=a.useState(1),B=a.useRef(!1),[E,W]=a.useState(1),[T,G]=a.useState(0),[_,k]=a.useState(0);Ls("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:E,panX:T,panY:_,isMenuOpen:y,isImeOpen:S});const K=a.useRef(0),J=a.useRef(E),P=a.useRef(T),$=a.useRef(_);a.useEffect(()=>{J.current=E},[E]),a.useEffect(()=>{P.current=T},[T]),a.useEffect(()=>{$.current=_},[_]),a.useEffect(()=>{var q;(q=c.current)==null||q.focus()},[]);const z=r==="connected",U=n,Y=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!N||B.current||!U)return;const q=m.current,se=u.current;if(!q||!se)return;const te=()=>{const ge=se.clientWidth,fe=se.clientHeight,R=q.naturalWidth,xe=q.naturalHeight;if(!R||!xe||!ge||!fe)return;const A=Math.min(ge/R,fe/xe),ee=Math.max(ge/R,fe/xe)/A;ee>1.01&&(j(ee),W(ee),J.current=ee),B.current=!0};q.complete&&q.naturalWidth?te():q.addEventListener("load",te,{once:!0})},[U,N]);const pe=.5;a.useEffect(()=>{E<=pe&&(G(0),k(0))},[E,pe]);const O=(q,se,te)=>{if(te<=pe)return{x:0,y:0};const ge=(te-1)/(2*te)*100,fe=(te-1)/(2*te)*100;return{x:Math.max(-ge,Math.min(ge,q)),y:Math.max(-fe,Math.min(fe,se))}},F=(q,se)=>{if(!m.current)return null;const te=m.current.getBoundingClientRect();return!te.width||!te.height?null:{nx:Math.max(0,Math.min(1,(q-te.left)/te.width)),ny:Math.max(0,Math.min(1,(se-te.top)/te.height))}},D=(q,se,te)=>{const ge=u.current;if(!ge)return;const fe=ge.getBoundingClientRect(),R=++b.current;d(xe=>[...xe,{id:R,x:q-fe.left,y:se-fe.top,type:te}]),setTimeout(()=>d(xe=>xe.filter(A=>A.id!==R)),600)},me=(q,se,te)=>{const ge=m.current,fe=u.current;if(!ge||!fe)return;const R=ge.getBoundingClientRect(),xe=fe.getBoundingClientRect(),A=ge.naturalWidth||R.width,H=ge.naturalHeight||R.height,ee=A/H,Q=R.width/R.height;let ce,Ne,Le,De;ee>Q?(ce=R.width,Ne=R.width/ee,Le=0,De=(R.height-Ne)/2):(Ne=R.height,ce=R.height*ee,Le=(R.width-ce)/2,De=0);const Re=R.left-xe.left+Le+ce*q,ot=R.top-xe.top+De+Ne*se,Qe=++b.current;d(ze=>[...ze,{id:Qe,x:Re,y:ot,type:te}]),setTimeout(()=>d(ze=>ze.filter(et=>et.id!==Qe)),600)},ie=async q=>{var te;const se=F(q.clientX,q.clientY);if(se){p(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),D(q.clientX,q.clientY,"left"),(te=c.current)==null||te.focus();try{const ge=await t("input_click",{nx:se.nx,ny:se.ny});ge!=null&&ge.success||s(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){s(`❌ Click error: ${ge.message||ge}`)}}},X=async(q,se,te,ge=0)=>{try{await t("input_key",{type:te?"char":"keyDown",key:q,code:se,text:te?q:void 0,unmodifiedText:te?q:void 0,modifiers:ge})}catch(fe){s(`❌ Key error: ${fe.message||fe}`)}},be=async q=>{if(q.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(q.key)&&q.preventDefault();let te=0;q.altKey&&(te|=1),q.ctrlKey&&(te|=2),q.metaKey&&(te|=4),q.shiftKey&&(te|=8),p(`Key: ${q.key}`),await X(q.key,q.code,q.key.length===1,te)},ne=async q=>{if(q.key==="Enter"){if(q.nativeEvent.isComposing)return;if(h){const se=h;g(""),p(`IME Sent: ${se}`);try{const te=await t("input_type",{text:se});te!=null&&te.success||s(`❌ IME error: ${te==null?void 0:te.error}`)}catch(te){s(`❌ IME error: ${te.message}`)}}else p("Key: Enter"),await X("Enter","Enter",!1)}};a.useEffect(()=>{const q=c.current;if(!q)return;const se=te=>{var ge;if((ge=m.current)!=null&&ge.contains(te.target)){te.preventDefault();const fe=Date.now();if(fe-K.current<40)return;K.current=fe;const R=F(te.clientX,te.clientY);if(!R)return;p(`Scroll: ${Math.round(te.deltaY)}`),t("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(te.deltaX),deltaY:Math.round(te.deltaY)}).catch(()=>{})}};return q.addEventListener("wheel",se,{passive:!1}),()=>q.removeEventListener("wheel",se)},[t]);const{cursorPos:le,handleToggleInputMode:ae,handleZoomReset:de}=lc({containerRef:c,viewportRef:u,imgRef:m,inputMode:x,setInputMode:w,minZoom:pe,zoomRef:J,panXRef:P,panYRef:$,setPanX:G,setPanY:k,setZoom:W,lastWheelTimeRef:K,onAction:t,setLastActionStatus:p,spawnRippleFromNormalized:me,clampPan:O,isMobile:N,mobileFillZoom:v});return e.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:be,onContextMenu:q=>q.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[e.jsxs("div",{ref:u,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[U?e.jsx("img",{ref:m,src:U,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${E}) translate(${T}%, ${_}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ie,onContextMenu:q=>q.preventDefault(),onDragStart:q=>q.preventDefault()}):e.jsx(ic,{waitingLabel:Y,waitingHint:re,transportType:i}),x==="mouse"&&U&&e.jsx(ac,{cursorPos:le,viewportRef:u,imgRef:m}),I.map(q=>{const te={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[q.type];return e.jsxs("div",{style:{position:"absolute",left:q.x,top:q.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${te}, 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(${te}, 0.9)`,boxShadow:`0 0 12px rgba(${te}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},q.id)})]}),e.jsx(oc,{inputMode:x,onToggleInputMode:ae,isImeOpen:S,setIsImeOpen:M,isMenuOpen:y,setIsMenuOpen:l,imeText:h,setImeText:g,handleImeSubmit:ne,isConnActive:z,zoom:E,isMobile:N,mobileFillZoom:v,onZoomOut:()=>W(q=>Math.max(.5,q-.25)),onZoomReset:de,onZoomIn:()=>W(q=>Math.min(5,q+.25)),transportType:i,screenshotUsage:o,lastActionStatus:f}),e.jsx("style",{children:`
|
|
6
6
|
@keyframes slideUp {
|
|
7
7
|
from { opacity: 0; transform: translateY(6px); }
|
|
8
8
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -25,8 +25,8 @@ var ci=Object.defineProperty;var li=(t,s,r)=>s in t?ci(t,s,{enumerable:!0,config
|
|
|
25
25
|
50% { transform: translateY(-7px); }
|
|
26
26
|
100% { transform: translateY(0px); }
|
|
27
27
|
}
|
|
28
|
-
`})]})}function Ka(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 m=Math.floor(d/60);if(m<24)return`${m}h${r}`;const f=Math.floor(m/24);return f<7?`${f}d${r}`:new Date(t).toLocaleDateString()}const Wa=t=>Ka(t);function dc(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ms(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",o=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Rs(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...dc(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 _s(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 As(t,s,r){const n=_s(t,s),o=ms(t),i=o.isReconnecting,c=o.isConnecting,d=o.isGenerating,m=o.isWaiting,f=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||m,p=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:p,isReconnecting:i,isConnecting:c,isGenerating:d,isWaiting:m,inboxBucket:f?"needs_attention":p?"working":h?"task_complete":"idle"}}function uc(t,s,r){return As(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function mc(t,s,r){return _s(t,r||new Map).surfaceHidden}function Oa({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ms(t).isWaiting||!t.modalButtons)return null;const 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(Xt,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((d,m)=>{const f=c(d).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),g=r===d,C=r!==null;return e.jsx("button",{onClick:()=>i(d),disabled:C,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"bg-white font-extrabold":h?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${C&&!g?"opacity-40":"opacity-100"} ${C?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)"}:void 0,children:g?"⏳ ...":c(d)},m)})})]})]})}const ft=new Map;function Pn({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:d,acpModes:m}){var pe;const{sendCommand:f}=mt(),p=!!(d||m),h=`${t}:${s||n}`,g=ft.get(h),[C,I]=a.useState(!1),[l,b]=a.useState(!1),[y,u]=a.useState((g==null?void 0:g.models)||[]),[S,_]=a.useState((g==null?void 0:g.modes)||[]),N=O=>O?typeof O=="string"?O:typeof O=="object"?O.name||O.id||JSON.stringify(O):String(O):"",[x,w]=a.useState(N(i)),[v,j]=a.useState(N(c)),[B,E]=a.useState(!1),[W,T]=a.useState(!1),G=a.useRef(0),A=O=>O.map(F=>typeof F=="string"?F:(F==null?void 0:F.name)||(F==null?void 0:F.id)||String(F));a.useEffect(()=>{if(d){const O=d.find(F=>F.category==="model");if(O){const F=A(O.options.map(me=>me.value));u(F),O.currentValue&&w(N(O.currentValue));const D=ft.get(h)||{models:[],modes:[]};ft.set(h,{...D,models:F})}}if(m&&m.length>0){const O=A(m.map(D=>D.id));_(O);const F=ft.get(h)||{models:[],modes:[]};ft.set(h,{...F,modes:O})}else if(d){const O=d.find(F=>F.category!=="model");if(O){const F=A(O.options.map(me=>me.value));_(F),O.currentValue&&j(N(O.currentValue));const D=ft.get(h)||{models:[],modes:[]};ft.set(h,{...D,modes:F})}}},[d,m,h]),a.useEffect(()=>{I(!1),b(!1),w(N(i)),j(N(c));const O=ft.get(h);O?(u(O.models),_(O.modes)):(u([]),_([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>G.current&&w(N(i))},[i]),a.useEffect(()=>{c&&Date.now()>G.current&&j(N(c))},[c]);const k=a.useCallback(async(O,F={})=>{const D={...F,...s&&{targetSessionId:s}};return await f(t,O,D)},[t,s,f]),K=async()=>{var O,F;if(y.length>0){I(!C);return}if(p){I(!0);return}E(!0);try{const D=await k("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),me=(D==null?void 0:D.models)||((O=D==null?void 0:D.result)==null?void 0:O.models)||[],ie=A(me);u(ie),D!=null&&D.current&&w(N(D.current)),(F=D==null?void 0:D.result)!=null&&F.current&&w(N(D.result.current));const X=ft.get(h)||{models:[],modes:[]};ft.set(h,{...X,models:ie}),I(!0)}catch{}finally{E(!1)}},J=async()=>{var O,F;if(S.length>0){b(!l);return}if(p){b(!0);return}T(!0);try{const D=await k("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),me=(D==null?void 0:D.modes)||((O=D==null?void 0:D.result)==null?void 0:O.modes)||[],ie=A(me);_(ie),D!=null&&D.current&&j(N(D.current)),(F=D==null?void 0:D.result)!=null&&F.current&&j(N(D.result.current));const X=ft.get(h)||{models:[],modes:[]};ft.set(h,{...X,modes:ie}),b(!0)}catch{}finally{T(!1)}},L=async O=>{I(!1);const F=x;w(O),G.current=Date.now()+5e3;try{const D=p?await k("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:O}):await k("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:O});if((D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change model")}catch(D){console.warn("Model change failed",D),w(F),G.current=0}},$=p&&!(m&&m.length>0)&&(d==null?void 0:d.some(O=>O.category!=="model")),z=$?(pe=d==null?void 0:d.find(O=>O.category!=="model"))==null?void 0:pe.configId:void 0,H=async O=>{b(!1);const F=v;j(O),G.current=Date.now()+5e3;try{let D;if(p&&$&&z?D=await k("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:z,value:O}):p?D=await k("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:O}):D=await k("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:O}),(D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change mode")}catch(D){console.warn("Mode change failed",D),j(F),G.current=0}},re={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",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:re},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:C?`${re}55`:"transparent",border:"1px solid",color:x?"var(--text-primary)":"var(--text-muted)"},onClick:K,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),B?"...":x||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),C&&y.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"}),y.map(O=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:O===x?`${re}18`:"transparent",color:O===x?re:"var(--text-secondary)",fontWeight:O===x?600:400,borderLeft:O===x?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:F=>{F.currentTarget.style.background=`${re}12`},onMouseLeave:F=>{F.currentTarget.style.background=O===x?`${re}18`:"transparent"},onClick:()=>L(O),children:O},O))]})]})]}),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?`${re}55`:"transparent",border:"1px solid",color:v?"var(--text-primary)":"var(--text-muted)"},onClick:J,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:$?"🧠":"⚡"}),W?"...":v||($?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),l&&S.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"}),S.map(O=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:O===v?`${re}18`:"transparent",color:O===v?re:"var(--text-secondary)",fontWeight:O===v?600:400,borderLeft:O===v?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:F=>{F.currentTarget.style.background=`${re}12`},onMouseLeave:F=>{F.currentTarget.style.background=O===v?`${re}18`:"transparent"},onClick:()=>H(O),children:O},O))]})]})]})]})}const Rn=new Map,pc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa",antigravity:"#f97316",windsurf:"#34d399"};function fc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:d,serverMode:m,acpConfigOptions:f,acpModes:p}){const{sendCommand:h}=mt(),g=`${t}:${s||n}`,C=pc[n]||"#94a3b8",[I,l]=a.useState({}),b=a.useRef(0),y={...d?{model:d}:{},...m?{mode:m}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&l({})},[c]);const[u,S]=a.useState(Rn.get(g)||{}),[_,N]=a.useState(null),[x,w]=a.useState(null),v=a.useCallback(async(k,K={})=>{const J={...K,...s&&{targetSessionId:s}};return await h(t,k,J)},[t,s,h]),j=a.useCallback(async(k,K={},J)=>{const L=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const $=await v("invoke_provider_script",{...L,scriptName:k,...K});return($==null?void 0:$.success)===!1&&J?await v(J,{...L,...K}):$}catch($){if(!J)throw $;return await v(J,{...L,...K})}},[v,n,r]);if(!i||i.length===0)return e.jsx(Pn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:m,acpConfigOptions:f,acpModes:p});const B=i.filter(k=>k.placement==="bar").sort((k,K)=>(k.order??50)-(K.order??50));if(B.length===0)return e.jsx(Pn,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:d,serverMode:m,acpConfigOptions:f,acpModes:p});const E=async k=>{var J,L,$;if(_===k.id){N(null);return}if((((J=k.options)==null?void 0:J.map(z=>z.value))||u[k.id]||[]).length>0){N(k.id);return}if(k.dynamic&&k.listScript){w(k.id);try{const z=Ks(k.listScript),H=await j(k.listScript,{},z),re=((H==null?void 0:H.models)||(H==null?void 0:H.modes)||((L=H==null?void 0:H.result)==null?void 0:L.models)||(($=H==null?void 0:H.result)==null?void 0:$.modes)||(H==null?void 0:H.options)||[]).map(pe=>typeof pe=="string"?pe:(pe==null?void 0:pe.name)||(pe==null?void 0:pe.id)||(pe==null?void 0:pe.value)||String(pe));S(pe=>{const O={...pe,[k.id]:re};return Rn.set(g,O),O}),N(k.id)}catch{}finally{w(null)}}},W=async(k,K)=>{N(null),l(J=>({...J,[k.id]:K})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{model:k.id==="model"?K:void 0,mode:k.id==="mode"?K:void 0,value:K},Ks(k.setScript))}catch{}},T=async k=>{var H;const K=((H=k.options)==null?void 0:H.map(Y=>Y.value))||u[k.id]||[];if(K.length===0)return;const J=String(y[k.id]||""),$=(K.indexOf(J)+1)%K.length,z=K[$];if(typeof z=="string"){l(Y=>({...Y,[k.id]:z})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{value:z},Ks(k.setScript))}catch{}}},G=async k=>{const J=!y[k.id];l(L=>({...L,[k.id]:J})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{value:J},Ks(k.setScript))}catch{}},A=async k=>{if(k.invokeScript)try{await j(k.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:C},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),B.map(k=>{var z;const K=String(y[k.id]||""),J=_===k.id,L=x===k.id,$=((z=k.options)==null?void 0:z.map(H=>H.value))||u[k.id]||[];switch(k.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:J?`${C}55`:"transparent",border:"1px solid",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>E(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),L?"...":K||k.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),J&&$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(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:k.label.toUpperCase()}),$.map(H=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:H===K?`${C}18`:"transparent",color:H===K?C:"var(--text-secondary)",fontWeight:H===K?600:400,borderLeft:H===K?`2px solid ${C}`:"2px solid transparent"},onMouseEnter:Y=>{Y.currentTarget.style.background=`${C}12`},onMouseLeave:Y=>{Y.currentTarget.style.background=H===K?`${C}18`:"transparent"},onClick:()=>W(k,H),children:H},H))]})]})]},k.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:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>T(k),title:`Click to cycle: ${$.join(" → ")}`,children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),K||k.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},k.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:K?`${C}44`:"transparent",background:K?`${C}14`:"var(--surface-tertiary)",color:K?C:"var(--text-muted)"},onClick:()=>G(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),k.label]},k.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:()=>A(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),k.resultDisplay==="inline"&&K?`${k.label}: ${K}`:k.label]},k.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:K?"var(--text-primary)":"var(--text-muted)"},children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),K?`${k.label}: ${K}`:k.label]},k.id);default:return null}})]})}function Ks(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const xc=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[d,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const f=()=>{const p=d.trim();!p||n||(m(""),o(p))};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:p=>m(p.target.value),onPaste:p=>{const h=p.clipboardData.getData("text");h&&m(g=>g+h),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),f()}},onBlur:p=>{if(window.innerWidth<768){const h=p.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 hc=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function bc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function rt(t,s){if(bc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":hc.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 za(t){return rt(t)==="generating"}function Oe(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function gc(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 wr(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function ur(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 yc(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 vc(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function wc(t){return yc(t.trim().replace(/\.local$/i,""))}function jc(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function Ua(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&&!vc(c));if(r&&r!=="Unknown")return wc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function dt(t,s={}){return jc(t)||Ua(t,s)}function Ms(t){return t.transport==="pty"}function as(t){return t.transport==="acp"}function En(t,s){return Oe(t)}function $n(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Oe(r||"").trim().toLowerCase();return n===o||n===i||n===c}function kc(t){return rt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Nc(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=rt(n.status);if(!i){s.set(o,{...n,status:c});continue}const d=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(d<0||m<d)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Sc(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Cc(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Sc(s.receivedAt)||0}function Ic(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Or(t){return Math.max(Ic(t),Cc(t.activeChat))}function _c(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 sn(t,s){return _c(Or(t),Or(s),dt(t,{fallbackId:t.id}),dt(s,{fallbackId:s.id}),t.id,s.id)}const We=t=>t.transport==="pty",ls=(t,s)=>We(t)?t.mode||"terminal":"chat",Ha=(t,s)=>We(t)&&ls(t)==="terminal",$e=t=>t.transport==="acp";function Lt(t){return t.streamSource!=="agent-stream"}function Kt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function Fa(t){return t.machineName||""}function nr(t){return Kt(t)}function lt(t){return t.agentType||""}function rn(t){return t.hostIdeType||""}function mr(t){return t.displayPrimary||t.agentName||"Agent"}function nn(t){return[t.displaySecondary,Fa(t)].filter(Boolean)}function Es(t){return t.agentName||Oe(lt(t))}function Ac(t){var s,r;if(!Lt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Oe(rn(t)||lt(t))}function an(t){return Lt(t)?t.sessionId:t.nativeSessionId}function Dn(t){return Lt(t)?"native":t.tabKey}function Mc(t){return t.sessionId}function Tc(t,s){if(s)return Lt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function Lc(t,s){const r=lt(t),n=Lt(t)?s!=null&&s.type?Oe(s.type):Oe(rn(t)||r):Es(t);return{isNativeConversation:Lt(t),isCli:We(t),isAcp:$e(t),isCliTerminal:Ha(t),providerType:r,displayLabel:n,targetEntry:Tc(t,s)}}function Va({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ds(),c=Kt(t),d=Fa(t),m=t.transport==="cdp-page"||t.transport==="cdp-webview",f=t.streamSource==="agent-stream"&&!!t.agentName,p=!f&&(t.transport==="pty"||t.transport==="acp"),h=Es(t),g=Ac(t),C=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const l=an(t);l&&i(`/dashboard?activeTab=${encodeURIComponent(l)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:g,children:[e.jsx(ut,{size:12}),e.jsx("span",{children:g})]}):e.jsxs("span",{className:"conversation-meta-chip",title:g,children:[e.jsx(ut,{size:12}),e.jsx("span",{children:g})]})),f&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Is,{size:12}),e.jsx("span",{children:h})]}),p&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Is,{size:12}),e.jsx("span",{children:h})]}),d&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:d,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:d})]}):e.jsxs("span",{className:"conversation-meta-chip",title:d,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:d})]}))]})}function Bn(t,s){return`${t}:${s}`}function Pc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Ws(t,s){Pc()&&console.debug(`[subscription-manager] ${t}`,s)}class Rc{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,o){var d;const i=Bn(n.topic,n.key),c=this.active.get(i);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),Ws("subscribe",{daemonId:r,topic:n.topic,key:n.key}),(d=s.sendData)==null||d.call(s,r,n)}return()=>{var p;const m=this.active.get(i);if(!m||(m.handlers.delete(o),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};Ws("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(p=s.sendData)==null||p.call(s,r,f)}}publish(s){const r=Bn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,n.handlers.forEach(o=>{o(s)}))}resubscribeAll(s){var r;Ws("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);Ws("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 Dt=new Rc;function Ec(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});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 Os(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)}}function $c(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 ar(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,d=c||t.timestamp||Date.now(),m=t.sessions||[],{topLevel:f,childrenByParent:p}=$c(m),h=Ec(i,n),g=t.machine?{...(o==null?void 0:o.machine)||{},...t.machine}:o==null?void 0:o.machine,C=f.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),I=f.filter(b=>b.kind==="agent"&&b.transport==="pty"),l=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},...g&&{machine:g,platform:g.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:C.some(b=>!!b.cdpConnected)});for(const b of C){const y=h.get(b.id),u=Os(b,y),S=(p.get(b.id)||[]).map(_=>Os(_,h.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:u.parentId,sessionKind:u.kind,transport:u.transport,sessionCapabilities:u.capabilities,type:u.providerType,status:u.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:u.workspace,terminals:0,childSessions:S,agents:S.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:u.activeChat,chats:[],cdpConnected:u.cdpConnected,...u.currentModel!==void 0&&{currentModel:u.currentModel},...u.currentPlan!==void 0&&{currentPlan:u.currentPlan},...u.currentAutoApprove!==void 0&&{currentAutoApprove:u.currentAutoApprove},lastUpdated:u.lastUpdated,unread:u.unread,lastSeenAt:u.lastSeenAt,inboxBucket:u.inboxBucket,surfaceHidden:u.surfaceHidden,...u.controlValues!==void 0&&{controlValues:u.controlValues},...u.providerControls!==void 0&&{providerControls:u.providerControls},timestamp:d})}for(const b of I){const y=h.get(b.id),u=Os(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:u.parentId,sessionKind:u.kind,transport:u.transport,sessionCapabilities:u.capabilities,type:u.providerType,agentType:u.providerType,status:u.status||"running",daemonId:n,instanceId:b.id,cliName:u.providerName||u.providerType,mode:u.mode||(y==null?void 0:y.mode)||"terminal",workspace:u.workspace||"",activeChat:u.activeChat,...u.resume!==void 0&&{resume:u.resume},...u.runtimeKey!==void 0&&{runtimeKey:u.runtimeKey},...u.runtimeDisplayName!==void 0&&{runtimeDisplayName:u.runtimeDisplayName},...u.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:u.runtimeWorkspaceLabel},...u.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:u.runtimeWriteOwner},...u.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:u.runtimeAttachedClients},lastUpdated:u.lastUpdated,unread:u.unread,lastSeenAt:u.lastSeenAt,inboxBucket:u.inboxBucket,surfaceHidden:u.surfaceHidden,...u.controlValues!==void 0&&{controlValues:u.controlValues},...u.providerControls!==void 0&&{providerControls:u.providerControls},timestamp:d,_isCli:!0})}for(const b of l){const y=h.get(b.id),u=Os(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:u.parentId,sessionKind:u.kind,transport:u.transport,sessionCapabilities:u.capabilities,type:u.providerType,agentType:u.providerType,status:u.status||"running",daemonId:n,instanceId:b.id,cliName:u.providerName||u.providerType,mode:"chat",workspace:u.workspace||"",activeChat:u.activeChat,...u.runtimeKey!==void 0&&{runtimeKey:u.runtimeKey},...u.runtimeDisplayName!==void 0&&{runtimeDisplayName:u.runtimeDisplayName},...u.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:u.runtimeWorkspaceLabel},...u.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:u.runtimeWriteOwner},...u.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:u.runtimeAttachedClients},...u.currentModel!==void 0&&{currentModel:u.currentModel},...u.currentPlan!==void 0&&{currentPlan:u.currentPlan},lastUpdated:u.lastUpdated,unread:u.unread,lastSeenAt:u.lastSeenAt,inboxBucket:u.inboxBucket,surfaceHidden:u.surfaceHidden,...u.acpConfigOptions!==void 0&&{acpConfigOptions:u.acpConfigOptions},...u.acpModes!==void 0&&{acpModes:u.acpModes},...u.controlValues!==void 0&&{controlValues:u.controlValues},...u.providerControls!==void 0&&{providerControls:u.providerControls},timestamp:d,_isAcp:!0})}return r}const jr=new Map,kr=new Map,Nr=new Set,js=new Map,Dc=1200;function Bc(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 Kn(t,s){const r=js.get(t);!r||r.size===0||(js.delete(t),r.forEach(n=>n(s)))}function Kc(t,s){return new Promise(r=>{const n=js.get(t)||new Set;js.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&js.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function $s(){const{sendCommand:t,sendData:s}=mt(),{injectEntries:r,getIdes:n}=rr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,d=kr.get(o)||0;if(!(i!=null&&i.force)&&Nr.has(o)&&d>0||!(i!=null&&i.force)&&d>0&&Date.now()-d<c)return;const m=jr.get(o);if(m)return m;const f=(async()=>{if(s&&!Nr.has(o)&&(Nr.add(o),Dt.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},l=>{const b=n(),y=b.find(S=>S.id===o),u=ar(l.status,{daemonId:o,existingDaemon:y,existingEntries:b,timestamp:l.timestamp});u.length>0&&r(u),kr.set(o,Date.now()),Kn(o,!0)}),!(i!=null&&i.force)&&await Kc(o,Dc)))return;const p=await t(o,"get_status_metadata"),h=Bc(p);if(!h)return;const g=n(),C=g.find(l=>l.id===o),I=ar(h,{daemonId:o,existingDaemon:C,existingEntries:g,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),kr.set(o,Date.now()),Kn(o,!0)})().finally(()=>{jr.delete(o)});return jr.set(o,f),f},[n,r,t,s])}function Zt(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function Ga(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=Jt(t.content),i=Jt(s.content);if(!o||o!==i)return!1;const c=Zt(t),d=Zt(s);return c&&d?Math.abs(c-d)<=15e3:!!t._localId!=!!s._localId}function Wn(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),Zt(t)&&(s+=1),s}function Wc(t,s){const r=Wn(t),n=Wn(s);return n!==r?n>r?s:t:Jt(s.content).length>=Jt(t.content).length?s:t}function ks(t){const s=[];for(const r of t){const n=s.findIndex(o=>Ga(o,r));if(n>=0){s.splice(n,1,Wc(s[n],r));continue}s.push(r)}return s}function On(t){return[...t].sort((s,r)=>{const n=Zt(s),o=Zt(r);return n&&o&&n!==o?n-o:0})}function zn(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${Jt(t==null?void 0:t.content).slice(0,100)}`}function Un(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=>Ga(i,n));return o>=0?(r.splice(o,1),!1):!0})}function Oc(t,s){const r=new Set(s.map(n=>zn(n)));return t.filter(n=>!r.has(zn(n)))}function zc(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Uc(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 Hn(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 qa(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return Uc([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function Hc(t){return{knownMessageCount:t.length,lastMessageSignature:qa(t[t.length-1])}}function Fc(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return ks([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return ks([...t.slice(0,n),...r])}case"full":default:return r}}const Vc=60,Fn=60;function zr({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:d,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:p=!0}){var F,D,me,ie;const h=a.useRef(new Map),g=a.useRef(new Map),C=a.useRef(new Map),{sendCommand:I,sendData:l}=mt(),b=$s();Ps("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const y=Ge.useMemo(()=>ms(t),[t.status,t.connectionState]),u=a.useRef(new Map),S=a.useCallback(X=>(u.current.has(X)||u.current.set(X,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:Vc}),u.current.get(X)),[]),_=a.useCallback((X,be)=>{const ne=S(X);u.current.set(X,{...ne,...be}),N(le=>le+1)},[S]),[,N]=a.useState(0),x=t.tabKey,w=S(x),v=w.messages,j=w.hasMore,B=w.error,E=g.current.get(x),W=t.messages.filter(X=>!!(X!=null&&X._localId)),T=E?ks([...E,...W]):t.messages,G=Math.max(0,T.length-w.visibleLiveCount),A=mr(t),k=nr(t),K=t.sessionId||"",J=t.providerSessionId||K,L=a.useMemo(()=>Lc(t,s),[t,s]),[$,z]=a.useState(!1);a.useEffect(()=>{const X=L.targetEntry;k&&(!X||X.providerControls===void 0||X.controlValues===void 0||L.isAcp&&(X.acpConfigOptions===void 0||X.acpModes===void 0))&&b(k,{minFreshMs:3e4}).catch(()=>{})},[k,L.isAcp,(F=L.targetEntry)==null?void 0:F.providerControls,(D=L.targetEntry)==null?void 0:D.controlValues,(me=L.targetEntry)==null?void 0:me.acpConfigOptions,(ie=L.targetEntry)==null?void 0:ie.acpModes,b]),a.useEffect(()=>{if(!k||!K||!l)return;const X=g.current.get(x)||[],be=C.current.get(x),ne=be&&be.knownMessageCount?be:Hc(X),le=`daemon:${k}:session:${K}`;return Dt.subscribe({sendData:l},k,{type:"subscribe",topic:"session.chat_tail",key:le,params:{targetSessionId:K,historySessionId:J,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:Fn}}},de=>{const q=g.current.get(x)||[],se=Fc(q,de),te=Math.max(se.length,Number(de.totalMessages||0));C.current.set(x,{knownMessageCount:te,lastMessageSignature:typeof de.lastMessageSignature=="string"?de.lastMessageSignature:qa(se[se.length-1])}),Hn(q)!==Hn(se)&&(g.current.set(x,se),N(fe=>fe+1))})},[k,J,l,K,x]);const H=a.useCallback(async()=>{if($)return;const X=t.tabKey,be=S(X);if(T.length>be.visibleLiveCount){_(X,{visibleLiveCount:Math.min(T.length,be.visibleLiveCount+Fn),error:null});return}z(!0),_(X,{error:null});try{const ne=nr(t);if(!ne){_(X,{hasMore:!1});return}const le=lt(t),ae=await I(ne,"chat_history",{agentType:le,offset:be.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),de=zc(ae),q=de.messages||[];if(q.length>0){const se=S(X);_(X,{messages:[...q,...se.messages],offset:se.offset+q.length,hasMore:!!de.hasMore})}else _(X,{hasMore:!!de.hasMore})}catch(ne){const le=(ne==null?void 0:ne.message)||"";le.includes("P2P not available")||le.includes("channel not open")||le.includes("P2P not connected")||le.includes("timeout")?_(X,{error:"Connection not ready — tap to retry"}):_(X,{hasMore:!1,error:"Failed to load history"})}finally{z(!1)}},[$,t,T.length,I,S,_]),{allMessages:Y,receivedAtMap:re}=a.useMemo(()=>{const X=G>0?T.slice(-w.visibleLiveCount):T;if(v.length===0){const ae=On(ks(X)),de={};return ae.forEach((q,se)=>{const te=`${t.tabKey}:${ns(q,se)}`;let ge=Zt(q)||h.current.get(te)||0;ge||(ge=Date.now(),h.current.set(te,ge)),de[ns(q,se)]=ge}),{allMessages:ae,receivedAtMap:de}}const be=Oc(v,X),ne=On(ks([...be,...X])),le={};return ne.forEach((ae,de)=>{const q=`${t.tabKey}:${ns(ae,de)}`;let se=Zt(ae)||h.current.get(q)||0;se||(se=Date.now(),h.current.set(q,se)),le[ns(ae,de)]=se}),{allMessages:ne,receivedAtMap:le}},[t.tabKey,G,v,T,w.visibleLiveCount]),pe=a.useMemo(()=>c.filter(X=>X.routeId===t.tabKey).sort((X,be)=>X.timestamp-be.timestamp),[c,t.tabKey]),O=a.useMemo(()=>{if(T.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((y.isGenerating||t.status==="streaming")&&z(!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(Is,{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(cs,{size:14})," Open ",A," Panel"]})}),e.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(t.status==="panel_hidden")return e.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"text-3xl opacity-60",children:e.jsx(Pa,{size:28})}),e.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),e.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(cs,{size:14})," Open ",A," 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"&&!$)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,$,T.length,A,y.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&e.jsx(Va,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(tc,{messages:Y,actionLogs:pe,agentName:Es(t)||A||"Agent",userName:d,isCliMode:L.isCli||L.isAcp,isWorking:y.isGenerating,contextKey:t.tabKey,receivedAtMap:re,onLoadMore:H,isLoadingMore:$,hasMoreHistory:j,hiddenLiveCount:G,loadError:B??void 0,emptyState:O,scrollToBottomRequestNonce:f}),p&&!L.isCliTerminal&&(()=>{var X,be,ne,le,ae,de;return e.jsx(fc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:L.providerType,displayLabel:L.displayLabel,controls:(X=L.targetEntry)==null?void 0:X.providerControls,controlValues:(be=L.targetEntry)==null?void 0:be.controlValues,serverModel:((ne=L.targetEntry)==null?void 0:ne.currentModel)||void 0,serverMode:((le=L.targetEntry)==null?void 0:le.currentPlan)||void 0,acpConfigOptions:L.isAcp?(ae=L.targetEntry)==null?void 0:ae.acpConfigOptions:void 0,acpModes:L.isAcp?(de=L.targetEntry)==null?void 0:de.acpModes:void 0})})(),!L.isCliTerminal&&e.jsx(xc,{contextKey:t.tabKey,panelLabel:A,isSending:n,onSend:r,isActive:p})]})}let Ya=Yt;function Xa(){return Ya()}class Gc{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let Ja=new Gc;class qc{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 Fe=new qc;function Yc(t){t.dashboardWS&&(Ja=t.dashboardWS),t.connectionManager&&(Fe=t.connectionManager),t.useDaemonsHook&&(Ya=t.useDaemonsHook)}function Ve(t){return mr(t)}function Qt(t){return nn(t).join(" · ")}function Za(t){const s=[...t.messages].reverse().find(n=>!(n!=null&&n._localId))||t.messages[t.messages.length-1],r=Jt(s==null?void 0:s.content);return r||(t.title?t.title:Qt(t)||"No messages yet")}function Qa(t,s){const{isReconnecting:r,isConnecting:n}=ms(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Xc(t,s){const r=["Chat",...nn(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function os(t){return Qa(t)||Qt(t)}function Jc(t){return`${Ve(t)} · ${Za(t)}`}function Zc(t){const s=rn(t)||lt(t);return`${Ve(t)} — ${Oe(s)}`}function Qc(t){return Es(t)||"CLI"}function eo(t){return t.title||Es(t)||t.routeId}function el(t){return t?`Remote · ${Ve(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}=Yt(),d=a.useRef(null),{sendCommand:m,sendData:f}=mt(),[p,h]=a.useState(""),[g,C]=a.useState(!1),[I,l]=a.useState(1),b=a.useRef(!1),y=a.useRef(0),u=a.useRef(!1),S=a.useRef(""),_=a.useRef(null),N=a.useRef(!1),x=a.useRef(null),w=t.tabKey,v=t.sessionId||"",j=t.daemonId||(($=t.routeId)==null?void 0:$.split(":")[0])||t.routeId||"",B=c.find(z=>z.id===j&&z.type==="adhdev-daemon"),E=(B==null?void 0:B.terminalSizingMode)==="fit"?"fit":"measured",W=.6,T=1.15,G=()=>{if(typeof window>"u")return 1;const z=window.innerWidth||0;return z<=360?.68:z<=390?.74:z<=430?.82:z<=480?.9:1},A=()=>{var z,H;y.current=0,u.current=!1,S.current="",_.current=null,N.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),C(!1),(H=(z=r.current)==null?void 0:z.reset)==null||H.call(z)},k=()=>{var z,H;y.current=0,u.current=!1,S.current="",_.current=null,N.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),C(!0),(H=(z=r.current)==null?void 0:z.reset)==null||H.call(z)},K=()=>{var H;if(x.current=null,!i)return;const z=S.current;z&&(S.current="",(H=r.current)==null||H.write(z))},J=z=>{z&&(S.current+=z,i&&x.current===null&&(x.current=requestAnimationFrame(K)))},L=(z,H=0,Y,re)=>{var pe,O,F,D,me;H>0&&y.current>=H||H===0&&u.current||(y.current=H,C(!0),typeof Y=="number"&&typeof re=="number"&&Y>0&&re>0&&((O=(pe=r.current)==null?void 0:pe.resize)==null||O.call(pe,Y,re)),(D=(F=r.current)==null?void 0:F.reset)==null||D.call(F),z&&((me=r.current)==null||me.write(z)))};return a.useEffect(()=>{A()},[v]),a.useEffect(()=>{var H;if(!v)return;const z=((H=Fe.onRuntimeEvent)==null?void 0:H.call(Fe,v,Y=>{if(!(!Y||Y.sessionId!==v)){if(Y.type==="runtime_snapshot"){if(!i){_.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"){u.current=!0,typeof Y.seq=="number"&&(y.current=Math.max(y.current,Y.seq)),g||C(!0),typeof Y.data=="string"&&J(Y.data);return}if(Y.type==="session_cleared"){if(!i){N.current=!0,S.current="",_.current=null;return}k()}}}))||(()=>{});return()=>{z()}},[j,v,r,i,g]),a.useEffect(()=>{var H,Y,re;if(!v)return;j&&((H=Fe.getState)==null?void 0:H.call(Fe,j))==="connected"&&(C(!0),(Y=Fe.requestRuntimeSnapshot)==null||Y.call(Fe,j,v).catch(()=>{}));const z=(re=Fe.onStateChange)==null?void 0:re.call(Fe,(pe,O)=>{var F;pe!==j||O!=="connected"||(C(!0),(F=Fe.requestRuntimeSnapshot)==null||F.call(Fe,j,v).catch(()=>{}))});return()=>{z==null||z()}},[j,v,r]),a.useEffect(()=>{s&&A()},[s,w,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const z=()=>{b.current||l(G())};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{var H;if(!i){(H=d.current)==null||H.blur();return}N.current&&(N.current=!1,k());const z=_.current;z&&(_.current=null,L(z.text,z.seq,z.cols,z.rows)),S.current&&x.current===null&&(x.current=requestAnimationFrame(K)),requestAnimationFrame(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})},[i]),a.useEffect(()=>()=>{x.current!==null&&(cancelAnimationFrame(x.current),x.current=null)},[]),a.useEffect(()=>{const z=H=>{var re;const Y=H.detail;Y!=null&&Y.sessionId&&Y.sessionId!==v||g&&((re=r.current)==null||re.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",z),()=>{window.removeEventListener("adhdev:fit-cli-terminal",z)}},[g,v,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,l(z=>Math.max(W,Number((z-.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,l(z=>Math.min(T,Number((z+.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(Da,{ref:r,readOnly:!g||!i,sizingMode:E,onInput:z=>{g&&(f!=null&&f(j,{type:"pty_input",targetSessionId:v,data:z})||m(j,"pty_input",{targetSessionId:v,data:z}).catch(console.error))}})})}),!g&&e.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),e.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:e.jsxs("div",{className:"flex gap-2.5 items-center",children:[e.jsx("div",{className:"flex-1 relative",children:e.jsx("input",{ref:d,type:"text",placeholder:`Send message to ${Ve(t)}...`,value:p,disabled:!g||!i||o,onChange:z=>h(z.target.value),onPaste:z=>{const H=z.clipboardData.getData("text");H&&h(Y=>Y+H),z.preventDefault()},onKeyDown:z=>{if(z.key!=="Enter")return;if(z.nativeEvent.isComposing){z.preventDefault();return}z.preventDefault();const H=p.trim();!g||!H||o||(h(""),n(H))},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 z=p.trim();!g||!z||o||(h(""),n(z))},disabled:!g||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.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:p.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function sl({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 rl({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",m=()=>{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:m,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 on({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(lr,{size:n}):e.jsx(Pt,{size:n})})}function Vn({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=nn(t);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:mr(t)}),(r||o.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,o.join(" · ")]})]})}function nl({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:d,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:p,onHideConversation:h,hiddenConversations:g=[],onShowConversation:C,onShowAllHidden:I,inboxOpen:l,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:u,onOpenNewSession:S}){const{ides:_,p2pStates:N={}}=Yt(),x=!!t&&We(t)&&!$e(t),w=!!t&&$e(t),v=m||(t?Ha(t)?"terminal":"chat":null),[j,B]=a.useState(!1),E=a.useRef(null),W=a.useRef(null),T=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",G=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",A=_.filter(D=>D.type==="adhdev-daemon"),k=a.useMemo(()=>Rs(_),[_]),K=Object.values(N),J=K.filter(D=>D==="connected").length,L=K.filter(D=>D==="connecting"||D==="new"||D==="checking").length,z=r!=="connected"||A.length===0?null:L>0&&J===0?"P2P connecting...":J>0&&s===0?"Waiting for IDE...":null,H=a.useMemo(()=>o.filter(D=>!mc(D,o,k)),[o,k]),Y=a.useMemo(()=>H.filter(D=>As(D,k).requiresAction),[H,k]),re=a.useMemo(()=>H.filter(D=>{const me=(t==null?void 0:t.tabKey)===D.tabKey;return As(D,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}).unread}),[t,H,k]),pe=a.useMemo(()=>[...Y,...re].slice(0,9),[Y,re]),O=Y.length+re.length;a.useEffect(()=>{if(!l)return;const D=me=>{var ie;(ie=E.current)!=null&&ie.contains(me.target)||b(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[l,b]),a.useEffect(()=>{if(!y)return;const D=me=>{var ie;(ie=W.current)!=null&&ie.contains(me.target)||u(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[y,u]),a.useEffect(()=>{if(!y&&!l)return;const D=me=>{if(!me.altKey)return;const ie=me.code.match(/^Digit([1-9])$/);if(!ie)return;const X=Number(ie[1])-1,be=y?g[X]:void 0,ne=l?pe[X]:void 0,le=be||ne;if(le){if(me.preventDefault(),me.stopPropagation(),be){C==null||C(be),u(!1);return}p==null||p(le),b(!1)}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[g,y,l,pe,u,b,p,C]);const F=D=>{if(!D)return;const me=o.find(ie=>ie.tabKey===D);me&&(h==null||h(me))};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(Pt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Ve(t):"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:T,boxShadow:G}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:T,boxShadow:G}}),z&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",z]}),S&&e.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(Ki,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(x||w||!$e(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:Qt(t)||Ve(t),children:Ve(t)}),(x||w)&&d&&e.jsxs(e.Fragment,{children:[x&&f&&v&&e.jsx(on,{mode:v,onChange:f,compact:!0}),e.jsx("button",{onClick:()=>d(t),className:"btn btn-secondary btn-sm",title:w?"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(bt,{size:14})})]}),!$e(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(Qr,{size:14})}),!x&&!$e(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(ut,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[e.jsxs("div",{className:`dashboard-header-hidden${j?" is-drop-target":""}`,ref:W,onDragEnter:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),B(!0))},onDragOver:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),D.dataTransfer.dropEffect="move",B(!0))},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||B(!1)},onDrop:D=>{const me=D.dataTransfer.getData("text/tab-key");D.preventDefault(),B(!1),F(me)},children:[e.jsxs("button",{type:"button",onClick:()=>u(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx($i,{size:16}),g.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:g.length})]}),y&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),g.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),u(!1)},children:"Restore all"})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Ve(t)})]}),g.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:g.map(D=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{C==null||C(D),u(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Ve(D)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[g.indexOf(D)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",g.indexOf(D)+1]}):null,Qt(D)]})]},D.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>b(!l),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(dr,{size:16}),O>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:O})]}),l&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Y.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Y.map(D=>e.jsx(Vn,{conversation:D,isAttention:!0,shortcutIndex:pe.indexOf(D)>=0?pe.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.tabKey))]}),re.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),re.map(D=>e.jsx(Vn,{conversation:D,shortcutIndex:pe.indexOf(D)>=0?pe.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.tabKey))]}),O===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function al(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:m,onSwitchSession:f,onRefreshHistory:p,onResumeSavedSession:h}){var y;const g=s.find(u=>u.id===t.routeId),C=(g==null?void 0:g.chats)||[],I=(y=g==null?void 0:g.activeChat)==null?void 0:y.id,l=We(t)&&!$e(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:l?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Zc(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(bt,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!l&&e.jsx("button",{onClick:m,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"}),l?e.jsx(e.Fragment,{children:o.map(u=>{const S=t.providerSessionId===u.providerSessionId,_=S||!u.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{_||!h||h(u)},disabled:_,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${S?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${_?"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 ${S?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:u.title||"Untitled Session"}),e.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:u.providerSessionId})]}),e.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:al(u.lastMessageAt)})]}),e.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:u.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:[u.workspace||"Workspace unknown",u.currentModel?` · ${u.currentModel}`:"",u.messageCount>0?` · ${u.messageCount} msgs`:""]}),e.jsx("div",{className:"shrink-0",children:S?"ACTIVE":u.canResume?c===u.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},u.id)})}):C.map(u=>e.jsxs("div",{onClick:()=>{f(t.routeId,u.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${I===u.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===u.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:u.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:[u.id.substring(0,12),"..."]}),I===u.id&&e.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},u.id)),(l&&!i&&o.length===0||!l&&C.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(zi,{size:32})}),e.jsx("div",{className:"text-[13px]",children:l?"No saved sessions found yet.":"No recent chat sessions found."})]}),l&&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:p,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(us,{size:13})," ",l?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Sa.createPortal(b,document.body)}const Gn={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 to({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=Gn[n.type]||Gn.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(bt,{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 ol=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function il(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function cl(t){return t.sessionId||t.instanceId||t.agentType}function Sr(t,s){return t||s}function qn(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 so(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=dt(r,{fallbackId:r.id}));return s}function ro(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 ln(t,s,r={}){return ll(t,s,ro(t,r))}function ll(t,s,r={}){var g,C,I,l,b,y;const n=[],o=r.machineName,i=r.connectionState,c=il(t),d=Oe(t.type),m=Array.isArray(t.childSessions)?t.childSessions.map(u=>{var S,_;return{sessionId:u.id,instanceId:u.id,providerSessionId:u.providerSessionId,transport:u.transport,agentType:u.providerType,agentName:u.providerName||Oe(u.providerType),status:u.status,title:u.title,messages:((S=u.activeChat)==null?void 0:S.messages)||[],activeModal:((_=u.activeChat)==null?void 0:_.activeModal)||void 0,unread:u.unread,lastSeenAt:u.lastSeenAt,lastUpdated:u.lastUpdated,inboxBucket:u.inboxBucket,surfaceHidden:u.surfaceHidden}}):[],f=ol(t),p=t.activeChat||{title:""},h=p.title&&String(p.title).trim()?String(p.title).trim():"";if(f){const u=t.sessionId||t.instanceId,S=En(t.type),_=(g=t.activeChat)==null?void 0:g.activeModal,N=_&&Array.isArray(_.buttons)&&_.buttons.length>0,x=rt((C=t.activeChat)==null?void 0:C.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||rt((b=(l=t.agents)==null?void 0:l[0])==null?void 0:b.status)||"idle",w=t.activeChat||{title:"",messages:[]};let v=w.title&&String(w.title).trim()?String(w.title).trim():"";const j=(y=t.activeChat)==null?void 0:y.id,B=t.chats;if(j&&Array.isArray(B)&&B.length>0){const k=B.find(K=>K.id===j||K.id&&String(K.id)===String(j));k!=null&&k.title&&String(k.title).trim()&&(v=String(k.title).trim())}const E=(We(t)||$e(t),t.type),W=(We(t)||$e(t))&&$n(v,S,E)?"":v,T=w.messages||[],G=qn(s,[t.id,u]),A=Un(T,G);n.push({routeId:t.id,sessionId:u,providerSessionId:t.providerSessionId,nativeSessionId:u,transport:t.transport,daemonId:t.daemonId||void 0,mode:We(t)?t.mode||"terminal":"chat",agentName:S,agentType:E,status:x,title:W,messages:[...T,...A],resume:t.resume,hostIdeType:!We(t)&&!$e(t)?t.type:void 0,workspaceName:c,displayPrimary:c||W||(We(t)?t.mode==="chat"?S:"Terminal":S),displaySecondary:d,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,modalButtons:N?_.buttons:void 0,modalMessage:N?_.message:void 0,streamSource:"native",tabKey:Sr(u,t.id),machineName:o,connectionState:i})}if(f&&(We(t)||$e(t)))return n;for(const u of m){const S=u.activeModal&&Array.isArray(u.activeModal.buttons)&&u.activeModal.buttons.length>0,_=kc(u),N=cl(u),x=`${t.id}:${N}`,w=u.title&&String(u.title).trim()||"",v=$n(w,u.agentName,u.agentType)?"":w,j=u.messages||[],B=qn(s,[x,u.sessionId,u.instanceId]),E=Un(j,B);(u.transport==="cdp-webview"||u.sessionId||u.providerSessionId||j.length>0||E.length>0||S||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(_))&&n.push({routeId:t.id,sessionId:u.sessionId||u.instanceId,providerSessionId:u.providerSessionId,nativeSessionId:t.sessionId||t.instanceId,transport:u.transport||"cdp-webview",daemonId:t.daemonId||void 0,mode:"chat",agentName:u.agentName,agentType:u.agentType,status:_,title:v,messages:[...j,...E],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||v||d,displaySecondary:`${d} · ${u.agentName}`,cdpConnected:t.cdpConnected,lastUpdated:u.lastUpdated||t.lastUpdated,modalButtons:S?u.activeModal.buttons:void 0,modalMessage:S?u.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Sr(u.sessionId||u.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:En(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:Sr(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function dl(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=dl(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const no=[{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:"🏄"}],ao=[{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:"🧩"}],oo=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"}],ml=no,pl=ao,fl=oo,io="adhdev_notification_prefs",Yn={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function xl(){try{const t=localStorage.getItem(io);if(t){const s=JSON.parse(t);return{...Yn,...s}}}catch{}return{...Yn}}function hl(t){try{localStorage.setItem(io,JSON.stringify(t))}catch{}}let Tt=xl(),Js=[];function bl(){Js.forEach(t=>t())}function gl(t){Tt={...Tt,...t},hl(Tt),bl()}function yl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return Js.push(r),()=>{Js=Js.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{gl(r)},[]);return[{...Tt},s]}function Ns(t){if(!Tt.globalEnabled)return!1;switch(t){case"disconnect":return Tt.disconnectAlert;case"completion":return Tt.completionAlert;case"approval":return Tt.approvalAlert;case"browser":return Tt.browserNotifications;default:return!0}}const vl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function wl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function co(){return"Notification"in window&&Notification.permission==="granted"}let zt=null;async function jl(){if(zt!==null)return zt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return zt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(zt=!!await t.pushManager.getSubscription(),zt):(zt=!1,!1)}catch{return zt=!1,!1}}function Ur(t,s,r){if(co())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 kl(t,s={}){const r={...vl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{jl().then(d=>{i.current=d})},[]);const c=a.useCallback((d,m,f)=>{const p=Date.now();p-o.current<r.throttleMs||(o.current=p,Ur(d,m,f))},[r.throttleMs]);a.useEffect(()=>{var d;if(!(!r.enabled||!co())&&Ns("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of t)n.current.set(m.id,rt(m.status,{activeModal:m.activeModal}));return}for(const m of t){const f=n.current.get(m.id),p=rt(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&Ns("approval")&&p==="waiting_approval"&&f!=="waiting_approval"){const g=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,g.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ns("completion")&&za(f)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&f!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Nl=/^(run|approve|accept|yes|allow|always)/,Sl=/^(run|approve|accept|yes|allow|always|proceed|save)/,Cl=/^(reject|deny|delete|remove|abort|cancel|no)/;function dn(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Il(t){const s=dn(t).toLowerCase();return Nl.test(s)?"primary":Cl.test(s)?"danger":"default"}function _l(t){return Sl.test(dn(t).toLowerCase())?"approve":"reject"}function Al(t){return t.map((s,r)=>({label:dn(s),variant:Il(s),action:_l(s),button:s,buttonIndex:r}))}function Ml(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
29
|
-
${n}`}function Tl(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Ll(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 Pl{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const 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,l;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 m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(m==null?void 0:m.type)||"";let p=Oe(f);const h=this.resolveOwningDaemon(s);if(h){const b=dt(h,{fallbackId:h.id});b&&(p=!f||f==="adhdev-daemon"?b:`${b}/${p}`)}let g="",C="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";g=`✅ ${p} agent task completed${b}`,C="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(g=`⚡ ${p} approval needed`,C="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:Ml(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(l=s.modalButtons)!=null&&l.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const y=this.resolveActionFn,u=Al(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{y(b,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Tl(p,s.modalMessage,g),_=Date.now();this.emitToast({id:_,message:S,type:C,timestamp:_,targetKey:n||b,actions:u,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${p} agent is taking a long time${b}`,C="warning",Ns("browser")&&!document.hasFocus()&&Ur(`⚠️ ${p} — 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",y=s.requestId,u=s.orgId;if(g=`👁️ ${b} wants to view your session`,C="warning",y&&u&&this.viewRequestRespondFn){const S=Date.now(),_=Ll(u,y,this.viewRequestRespondFn,(N,x)=>console.error(`[EventManager] ${N} view request failed:`,x));this.emitToast({id:S,message:g,type:C,timestamp:S,actions:_,duration:3e4}),g=""}Ns("browser")&&!document.hasFocus()&&Ur("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",C="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,C="warning");if(g){const b=Date.now();this.emitToast({id:b,message:g,type:C,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new Pl;function es(...t){return mi(pi(t))}function Rl({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:es("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 lo({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(Rl,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",i,c),children:d})})]})}function wt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:es("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",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 uo({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:es("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 El={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"},$l={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dl({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:es("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",El[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:$l[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 Bl={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"},Kl={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Wl({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:es("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Bl[t],r),children:[e.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Kl[t])}),n]})}function Ol(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Hr(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function Zs(t){return t==="system"?Ol():t}function zl(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Zs(Hr()))}function un(){const[t,s]=a.useState(Hr),[r,n]=a.useState(()=>Zs(Hr()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),d=m=>{t==="system"&&n(m.matches?"light":"dark")};return c.addEventListener("change",d),()=>c.removeEventListener("change",d)},[t]);const o=a.useCallback(c=>{s(c),n(Zs(c));try{localStorage.setItem("theme",c)}catch{}},[]),i=a.useCallback(()=>{s(c=>{const d=c==="dark"?"light":c==="light"?"system":"dark";n(Zs(d));try{localStorage.setItem("theme",d)}catch{}return d})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Xn={dark:"Dark",light:"Light",system:"System"};function Ul({collapsed:t}){const{preference:s,cycleTheme:r}=un(),n=s==="dark"?e.jsx(Hi,{size:16}):s==="light"?e.jsx(Ui,{size:16}):e.jsx(Fi,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Xn[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:Xn[s]})]})}function Ht({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 Hl({onPrefChange:t}){const[s,r]=yl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dr,{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(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{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(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vi,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gi,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Is,{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 Fl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Cr(t,s){return t instanceof Error?t.message:s}function Vl({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(uo,{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(ql,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Jn({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 Sa.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 Gl(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...ml,...pl,...fl].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 ql({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var T,G;const[i,c]=a.useState("idle"),[d,m]=a.useState(""),[f,p]=a.useState(null),[h,g]=a.useState("idle"),[C,I]=a.useState(""),l=t.version||null,b=((T=t.machine)==null?void 0:T.platform)||((G=t.system)==null?void 0:G.platform)||"",y=dt(t,{fallbackId:t.id}),u=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",S=s.filter(A=>A.daemonId===t.id&&A.transport==="cdp-page"),_=s.filter(A=>A.daemonId===t.id&&A.transport==="pty"),N=s.filter(A=>A.daemonId===t.id&&A.transport==="acp"),x=t.p2p,w=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const A=Fl(await r(t.id,"daemon_upgrade",{}));A.alreadyLatest?(c("done"),m(`Already on v${A.version||"latest"}.`)):A.upgraded||A.success?(c("done"),m(`Upgrade to v${A.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(A.error||"Upgrade failed"))}catch(A){c("error"),m(Cr(A,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){g("loading");try{await n(t.id),g("done"),I("Machine disconnected.")}catch(A){g("error"),I(Cr(A,"Failed to disconnect"))}}},j=async()=>{if(p(null),!!o){g("loading");try{await o(t.id),g("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(A){g("error"),I(Cr(A,"Failed to revoke token"))}}},B="0.8.37",E=!l||l!==B,W=S.length+_.length+N.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:u}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),l&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${E?"":"bg-bg-secondary"}`,style:E?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",l,!E&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&E&&e.jsx("button",{onClick:w,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`↑ Update${` to v${B}`}`}),n&&e.jsx("button",{onClick:()=>p("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:()=>p("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(Wl,{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&&W>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(A=>{const k=Gl(A.type),K=A.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:k.icon}),e.jsx("span",{children:k.name}),K!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},A.id)}),_.map(A=>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:A.cliName||"CLI"})]},A.id)),N.map(A=>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:A.cliName||"ACP"})]},A.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(d||C)&&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:C||d})]}),f==="disconnect"&&e.jsx(Jn,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
28
|
+
`})]})}function Ka(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 u=Math.floor(c/60);if(u<60)return`${u}m${r}`;const m=Math.floor(u/60);if(m<24)return`${m}h${r}`;const f=Math.floor(m/24);return f<7?`${f}d${r}`:new Date(t).toLocaleDateString()}const Wa=t=>Ka(t);function dc(t){return{unread:!!t.unread,lastSeenAt:t.lastSeenAt||0,lastUpdated:t.lastUpdated||0,inboxBucket:t.inboxBucket||"idle",surfaceHidden:!!t.surfaceHidden}}function ms(t){const s=t.connectionState==="failed"||t.connectionState==="closed",r=t.connectionState==="connecting"||t.connectionState==="new",n=t.status==="generating",o=t.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Rs(t){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...dc(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 Ms(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 _s(t,s,r){const n=Ms(t,s),o=ms(t),i=o.isReconnecting,c=o.isConnecting,u=o.isGenerating,m=o.isWaiting,f=n.inboxBucket==="needs_attention"||t.status==="needs_attention"||t.status==="waiting_for_user_input"||m,p=n.inboxBucket==="working"||u,h=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:h,requiresAction:f,isWorking:p,isReconnecting:i,isConnecting:c,isGenerating:u,isWaiting:m,inboxBucket:f?"needs_attention":p?"working":h?"task_complete":"idle"}}function uc(t,s,r){return _s(t,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function mc(t,s,r){return Ms(t,r||new Map).surfaceHidden}function Oa({activeConv:t,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[t.modalMessage,t.status,t.connectionState]),!ms(t).isWaiting||!t.modalButtons)return null;const i=u=>{r||(n(u),s(u))},c=u=>u.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(Xt,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:t.modalButtons.map((u,m)=>{const f=c(u).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(f),h=/^(reject|deny|delete|remove|abort)/.test(f),g=r===u,C=r!==null;return e.jsx("button",{onClick:()=>i(u),disabled:C,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"bg-white font-extrabold":h?"bg-red-500/30 text-white font-semibold":"bg-white/15 text-white font-semibold"} ${C&&!g?"opacity-40":"opacity-100"} ${C?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)"}:void 0,children:g?"⏳ ...":c(u)},m)})})]})]})}const ft=new Map;function Ln({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:i,serverMode:c,acpConfigOptions:u,acpModes:m}){var pe;const{sendCommand:f}=mt(),p=!!(u||m),h=`${t}:${s||n}`,g=ft.get(h),[C,I]=a.useState(!1),[d,b]=a.useState(!1),[y,l]=a.useState((g==null?void 0:g.models)||[]),[S,M]=a.useState((g==null?void 0:g.modes)||[]),N=O=>O?typeof O=="string"?O:typeof O=="object"?O.name||O.id||JSON.stringify(O):String(O):"",[x,w]=a.useState(N(i)),[v,j]=a.useState(N(c)),[B,E]=a.useState(!1),[W,T]=a.useState(!1),G=a.useRef(0),_=O=>O.map(F=>typeof F=="string"?F:(F==null?void 0:F.name)||(F==null?void 0:F.id)||String(F));a.useEffect(()=>{if(u){const O=u.find(F=>F.category==="model");if(O){const F=_(O.options.map(me=>me.value));l(F),O.currentValue&&w(N(O.currentValue));const D=ft.get(h)||{models:[],modes:[]};ft.set(h,{...D,models:F})}}if(m&&m.length>0){const O=_(m.map(D=>D.id));M(O);const F=ft.get(h)||{models:[],modes:[]};ft.set(h,{...F,modes:O})}else if(u){const O=u.find(F=>F.category!=="model");if(O){const F=_(O.options.map(me=>me.value));M(F),O.currentValue&&j(N(O.currentValue));const D=ft.get(h)||{models:[],modes:[]};ft.set(h,{...D,modes:F})}}},[u,m,h]),a.useEffect(()=>{I(!1),b(!1),w(N(i)),j(N(c));const O=ft.get(h);O?(l(O.models),M(O.modes)):(l([]),M([]))},[t,n,s]),a.useEffect(()=>{i&&Date.now()>G.current&&w(N(i))},[i]),a.useEffect(()=>{c&&Date.now()>G.current&&j(N(c))},[c]);const k=a.useCallback(async(O,F={})=>{const D={...F,...s&&{targetSessionId:s}};return await f(t,O,D)},[t,s,f]),K=async()=>{var O,F;if(y.length>0){I(!C);return}if(p){I(!0);return}E(!0);try{const D=await k("list_extension_models",s?{}:{agentType:n,...r?{ideType:r}:{}}),me=(D==null?void 0:D.models)||((O=D==null?void 0:D.result)==null?void 0:O.models)||[],ie=_(me);l(ie),D!=null&&D.current&&w(N(D.current)),(F=D==null?void 0:D.result)!=null&&F.current&&w(N(D.result.current));const X=ft.get(h)||{models:[],modes:[]};ft.set(h,{...X,models:ie}),I(!0)}catch{}finally{E(!1)}},J=async()=>{var O,F;if(S.length>0){b(!d);return}if(p){b(!0);return}T(!0);try{const D=await k("list_extension_modes",s?{}:{agentType:n,...r?{ideType:r}:{}}),me=(D==null?void 0:D.modes)||((O=D==null?void 0:D.result)==null?void 0:O.modes)||[],ie=_(me);M(ie),D!=null&&D.current&&j(N(D.current)),(F=D==null?void 0:D.result)!=null&&F.current&&j(N(D.result.current));const X=ft.get(h)||{models:[],modes:[]};ft.set(h,{...X,modes:ie}),b(!0)}catch{}finally{T(!1)}},P=async O=>{I(!1);const F=x;w(O),G.current=Date.now()+5e3;try{const D=p?await k("change_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:O}):await k("set_extension_model",{...s?{}:{agentType:n,...r?{ideType:r}:{}},model:O});if((D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change model")}catch(D){console.warn("Model change failed",D),w(F),G.current=0}},$=p&&!(m&&m.length>0)&&(u==null?void 0:u.some(O=>O.category!=="model")),z=$?(pe=u==null?void 0:u.find(O=>O.category!=="model"))==null?void 0:pe.configId:void 0,U=async O=>{b(!1);const F=v;j(O),G.current=Date.now()+5e3;try{let D;if(p&&$&&z?D=await k("set_thought_level",{...s?{}:{agentType:n,...r?{ideType:r}:{}},configId:z,value:O}):p?D=await k("set_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:O}):D=await k("set_extension_mode",{...s?{}:{agentType:n,...r?{ideType:r}:{}},mode:O}),(D==null?void 0:D.success)===!1)throw new Error((D==null?void 0:D.error)||"Could not change mode")}catch(D){console.warn("Mode change failed",D),j(F),G.current=0}},re={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:re},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:C?`${re}55`:"transparent",border:"1px solid",color:x?"var(--text-primary)":"var(--text-muted)"},onClick:K,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:"🤖"}),B?"...":x||"Model",e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),C&&y.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"}),y.map(O=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:O===x?`${re}18`:"transparent",color:O===x?re:"var(--text-secondary)",fontWeight:O===x?600:400,borderLeft:O===x?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:F=>{F.currentTarget.style.background=`${re}12`},onMouseLeave:F=>{F.currentTarget.style.background=O===x?`${re}18`:"transparent"},onClick:()=>P(O),children:O},O))]})]})]}),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:d?`${re}55`:"transparent",border:"1px solid",color:v?"var(--text-primary)":"var(--text-muted)"},onClick:J,children:[e.jsx("span",{className:"text-[9px] opacity-60",children:$?"🧠":"⚡"}),W?"...":v||($?"Thinking":"Mode"),e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),d&&S.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"}),S.map(O=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:O===v?`${re}18`:"transparent",color:O===v?re:"var(--text-secondary)",fontWeight:O===v?600:400,borderLeft:O===v?`2px solid ${re}`:"2px solid transparent"},onMouseEnter:F=>{F.currentTarget.style.background=`${re}12`},onMouseLeave:F=>{F.currentTarget.style.background=O===v?`${re}18`:"transparent"},onClick:()=>U(O),children:O},O))]})]})]})]})}const Rn=new Map,pc={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function fc({routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c,serverModel:u,serverMode:m,acpConfigOptions:f,acpModes:p}){const{sendCommand:h}=mt(),g=`${t}:${s||n}`,C=pc[n]||"#94a3b8",[I,d]=a.useState({}),b=a.useRef(0),y={...u?{model:u}:{},...m?{mode:m}:{},...c||{},...Date.now()<b.current?I:{}};a.useEffect(()=>{c&&Date.now()>b.current&&d({})},[c]);const[l,S]=a.useState(Rn.get(g)||{}),[M,N]=a.useState(null),[x,w]=a.useState(null),v=a.useCallback(async(k,K={})=>{const J={...K,...s&&{targetSessionId:s}};return await h(t,k,J)},[t,s,h]),j=a.useCallback(async(k,K={},J)=>{const P=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};try{const $=await v("invoke_provider_script",{...P,scriptName:k,...K});return($==null?void 0:$.success)===!1&&J?await v(J,{...P,...K}):$}catch($){if(!J)throw $;return await v(J,{...P,...K})}},[v,n,r]);if(!i||i.length===0)return e.jsx(Ln,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:u,serverMode:m,acpConfigOptions:f,acpModes:p});const B=i.filter(k=>k.placement==="bar").sort((k,K)=>(k.order??50)-(K.order??50));if(B.length===0)return e.jsx(Ln,{routeId:t,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,serverModel:u,serverMode:m,acpConfigOptions:f,acpModes:p});const E=async k=>{var J,P,$;if(M===k.id){N(null);return}if((((J=k.options)==null?void 0:J.map(z=>z.value))||l[k.id]||[]).length>0){N(k.id);return}if(k.dynamic&&k.listScript){w(k.id);try{const z=Ks(k.listScript),U=await j(k.listScript,{},z),re=((U==null?void 0:U.models)||(U==null?void 0:U.modes)||((P=U==null?void 0:U.result)==null?void 0:P.models)||(($=U==null?void 0:U.result)==null?void 0:$.modes)||(U==null?void 0:U.options)||[]).map(pe=>typeof pe=="string"?pe:(pe==null?void 0:pe.name)||(pe==null?void 0:pe.id)||(pe==null?void 0:pe.value)||String(pe));S(pe=>{const O={...pe,[k.id]:re};return Rn.set(g,O),O}),N(k.id)}catch{}finally{w(null)}}},W=async(k,K)=>{N(null),d(J=>({...J,[k.id]:K})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{model:k.id==="model"?K:void 0,mode:k.id==="mode"?K:void 0,value:K},Ks(k.setScript))}catch{}},T=async k=>{var U;const K=((U=k.options)==null?void 0:U.map(Y=>Y.value))||l[k.id]||[];if(K.length===0)return;const J=String(y[k.id]||""),$=(K.indexOf(J)+1)%K.length,z=K[$];if(typeof z=="string"){d(Y=>({...Y,[k.id]:z})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{value:z},Ks(k.setScript))}catch{}}},G=async k=>{const J=!y[k.id];d(P=>({...P,[k.id]:J})),b.current=Date.now()+5e3;try{if(!k.setScript)return;await j(k.setScript,{value:J},Ks(k.setScript))}catch{}},_=async k=>{if(k.invokeScript)try{await j(k.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:C},children:o}),e.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),B.map(k=>{var z;const K=String(y[k.id]||""),J=M===k.id,P=x===k.id,$=((z=k.options)==null?void 0:z.map(U=>U.value))||l[k.id]||[];switch(k.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:J?`${C}55`:"transparent",border:"1px solid",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>E(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),P?"...":K||k.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),J&&$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(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:k.label.toUpperCase()}),$.map(U=>e.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:U===K?`${C}18`:"transparent",color:U===K?C:"var(--text-secondary)",fontWeight:U===K?600:400,borderLeft:U===K?`2px solid ${C}`:"2px solid transparent"},onMouseEnter:Y=>{Y.currentTarget.style.background=`${C}12`},onMouseLeave:Y=>{Y.currentTarget.style.background=U===K?`${C}18`:"transparent"},onClick:()=>W(k,U),children:U},U))]})]})]},k.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:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>T(k),title:`Click to cycle: ${$.join(" → ")}`,children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),K||k.label,e.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},k.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:K?`${C}44`:"transparent",background:K?`${C}14`:"var(--surface-tertiary)",color:K?C:"var(--text-muted)"},onClick:()=>G(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),k.label]},k.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:()=>_(k),children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),k.resultDisplay==="inline"&&K?`${k.label}: ${K}`:k.label]},k.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:K?"var(--text-primary)":"var(--text-muted)"},children:[k.icon&&e.jsx("span",{className:"text-[9px] opacity-60",children:k.icon}),K?`${k.label}: ${K}`:k.label]},k.id);default:return null}})]})}function Ks(t){return{setModel:"set_extension_model",setMode:"set_extension_mode",listModels:"list_extension_models",listModes:"list_extension_modes",setThinkingLevel:"set_thought_level"}[t]}const xc=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[u,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var p;i&&((p=c.current)==null||p.focus())},[s,i]);const f=()=>{const p=u.trim();!p||n||(m(""),o(p))};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:u,onChange:p=>m(p.target.value),onPaste:p=>{const h=p.clipboardData.getData("text");h&&m(g=>g+h),p.preventDefault()},onKeyDown:p=>{if(p.key==="Enter"){if(p.nativeEvent.isComposing){p.preventDefault();return}p.preventDefault(),f()}},onBlur:p=>{if(window.innerWidth<768){const h=p.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:!u.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.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:u.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})});var hc=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function bc(t){var s;return(((s=t==null?void 0:t.buttons)==null?void 0:s.length)??0)>0}function rt(t,s){if(bc(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(t||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":hc.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 za(t){return rt(t)==="generating"}function Oe(t){return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():"IDE"}function gc(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 wr(t){return t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function ur(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 yc(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 vc(t){const s=t.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function wc(t){return yc(t.trim().replace(/\.local$/i,""))}function jc(t){const s=t.machineNickname??t.nickname;return typeof s!="string"?null:s.trim()||null}function Ha(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&&!vc(c));if(r&&r!=="Unknown")return wc(r);const n=s.fallbackId||t.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function dt(t,s={}){return jc(t)||Ha(t,s)}function As(t){return t.transport==="pty"}function as(t){return t.transport==="acp"}function En(t,s){return Oe(t)}function $n(t,s,r){const n=(t||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=Oe(r||"").trim().toLowerCase();return n===o||n===i||n===c}function kc(t){return rt(t==null?void 0:t.status,{activeModal:t==null?void 0:t.activeModal})}function Nc(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=rt(n.status);if(!i){s.set(o,{...n,status:c});continue}const u=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(u<0||m<u)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Sc(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const s=Date.parse(t);if(Number.isFinite(s))return s}return 0}function Cc(t){var r,n;const s=(n=(r=t==null?void 0:t.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Sc(s.receivedAt)||0}function Ic(t){return(t.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Or(t){return Math.max(Ic(t),Cc(t.activeChat))}function Mc(t,s,r,n,o,i){const c=s-t;if(c!==0)return c;const u=r.localeCompare(n);return u!==0?u:o.localeCompare(i)}function sn(t,s){return Mc(Or(t),Or(s),dt(t,{fallbackId:t.id}),dt(s,{fallbackId:s.id}),t.id,s.id)}const We=t=>t.transport==="pty",ls=(t,s)=>We(t)?t.mode||"terminal":"chat",Ua=(t,s)=>We(t)&&ls(t)==="terminal",$e=t=>t.transport==="acp";function Pt(t){return t.streamSource!=="agent-stream"}function Kt(t){var s;return t.daemonId||((s=t.routeId)==null?void 0:s.split(":")[0])||t.routeId||""}function Fa(t){return t.machineName||""}function nr(t){return Kt(t)}function lt(t){return t.agentType||""}function rn(t){return t.hostIdeType||""}function mr(t){return t.displayPrimary||t.agentName||"Agent"}function nn(t){return[t.displaySecondary,Fa(t)].filter(Boolean)}function Es(t){return t.agentName||Oe(lt(t))}function _c(t){var s,r;if(!Pt(t)){const n=(r=(s=t.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return Oe(rn(t)||lt(t))}function an(t){return Pt(t)?t.sessionId:t.nativeSessionId}function Dn(t){return Pt(t)?"native":t.tabKey}function Ac(t){return t.sessionId}function Tc(t,s){if(s)return Pt(t)||!s.childSessions?s:s.childSessions.find(r=>r.id===t.sessionId||r.providerType===t.agentType)||s}function Pc(t,s){const r=lt(t),n=Pt(t)?s!=null&&s.type?Oe(s.type):Oe(rn(t)||r):Es(t);return{isNativeConversation:Pt(t),isCli:We(t),isAcp:$e(t),isCliTerminal:Ua(t),providerType:r,displayLabel:n,targetEntry:Tc(t,s)}}function Va({conversation:t,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=ds(),c=Kt(t),u=Fa(t),m=t.transport==="cdp-page"||t.transport==="cdp-webview",f=t.streamSource==="agent-stream"&&!!t.agentName,p=!f&&(t.transport==="pty"||t.transport==="acp"),h=Es(t),g=_c(t),C=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),I=a.useCallback(()=>{if(r){r();return}const d=an(t);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[t,i,r]);return e.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:I,title:g,children:[e.jsx(ut,{size:12}),e.jsx("span",{children:g})]}):e.jsxs("span",{className:"conversation-meta-chip",title:g,children:[e.jsx(ut,{size:12}),e.jsx("span",{children:g})]})),f&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Is,{size:12}),e.jsx("span",{children:h})]}),p&&e.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[e.jsx(Is,{size:12}),e.jsx("span",{children:h})]}),u&&(o?e.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:u,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:u})]}):e.jsxs("span",{className:"conversation-meta-chip",title:u,children:[e.jsx(Bt,{size:12}),e.jsx("span",{children:u})]}))]})}function Bn(t,s){return`${t}:${s}`}function Lc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Ws(t,s){Lc()&&console.debug(`[subscription-manager] ${t}`,s)}class Rc{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,o){var u;const i=Bn(n.topic,n.key),c=this.active.get(i);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),Ws("subscribe",{daemonId:r,topic:n.topic,key:n.key}),(u=s.sendData)==null||u.call(s,r,n)}return()=>{var p;const m=this.active.get(i);if(!m||(m.handlers.delete(o),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};Ws("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(p=s.sendData)==null||p.call(s,r,f)}}publish(s){const r=Bn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,n.handlers.forEach(o=>{o(s)}))}resubscribeAll(s){var r;Ws("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);Ws("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 Dt=new Rc;function Ec(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 Os(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),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 $c(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 ar(t,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,u=c||t.timestamp||Date.now(),m=t.sessions||[],{topLevel:f,childrenByParent:p}=$c(m),h=Ec(i,n),g=t.machine?{...(o==null?void 0:o.machine)||{},...t.machine}:o==null?void 0:o.machine,C=f.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),I=f.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=f.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...o||{},id:n,type:"adhdev-daemon",status:"online",timestamp:u,...t.version&&{version:t.version},...g&&{machine:g,platform:g.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:C.some(b=>!!b.cdpConnected)});for(const b of C){const y=h.get(b.id),l=Os(b,y),S=(p.get(b.id)||[]).map(M=>Os(M,h.get(M.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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:S,agents:S.map(M=>({id:M.id,name:M.providerName||M.providerType,type:M.providerType,status:M.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:u})}for(const b of I){const y=h.get(b.id),l=Os(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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||(y==null?void 0:y.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:u,_isCli:!0})}for(const b of d){const y=h.get(b.id),l=Os(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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:u,_isAcp:!0})}return r}const jr=new Map,kr=new Map,Nr=new Set,js=new Map,Dc=1200;function Bc(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 Kn(t,s){const r=js.get(t);!r||r.size===0||(js.delete(t),r.forEach(n=>n(s)))}function Kc(t,s){return new Promise(r=>{const n=js.get(t)||new Set;js.set(t,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&js.delete(t),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function $s(){const{sendCommand:t,sendData:s}=mt(),{injectEntries:r,getIdes:n}=rr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,u=kr.get(o)||0;if(!(i!=null&&i.force)&&Nr.has(o)&&u>0||!(i!=null&&i.force)&&u>0&&Date.now()-u<c)return;const m=jr.get(o);if(m)return m;const f=(async()=>{if(s&&!Nr.has(o)&&(Nr.add(o),Dt.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(S=>S.id===o),l=ar(d.status,{daemonId:o,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});l.length>0&&r(l),kr.set(o,Date.now()),Kn(o,!0)}),!(i!=null&&i.force)&&await Kc(o,Dc)))return;const p=await t(o,"get_status_metadata"),h=Bc(p);if(!h)return;const g=n(),C=g.find(d=>d.id===o),I=ar(h,{daemonId:o,existingDaemon:C,existingEntries:g,timestamp:h.timestamp||Date.now()});I.length>0&&r(I,{authoritativeDaemonIds:[o]}),kr.set(o,Date.now()),Kn(o,!0)})().finally(()=>{jr.delete(o)});return jr.set(o,f),f},[n,r,t,s])}function Zt(t){const s=Number((t==null?void 0:t.receivedAt)||(t==null?void 0:t.timestamp)||0);return Number.isFinite(s)?s:0}function Ga(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=Jt(t.content),i=Jt(s.content);if(!o||o!==i)return!1;const c=Zt(t),u=Zt(s);return c&&u?Math.abs(c-u)<=15e3:!!t._localId!=!!s._localId}function Wn(t){let s=0;return t!=null&&t._localId||(s+=4),t!=null&&t.id&&(s+=3),t!=null&&t._turnKey&&(s+=2),Zt(t)&&(s+=1),s}function Wc(t,s){const r=Wn(t),n=Wn(s);return n!==r?n>r?s:t:Jt(s.content).length>=Jt(t.content).length?s:t}function ks(t){const s=[];for(const r of t){const n=s.findIndex(o=>Ga(o,r));if(n>=0){s.splice(n,1,Wc(s[n],r));continue}s.push(r)}return s}function On(t){return[...t].sort((s,r)=>{const n=Zt(s),o=Zt(r);return n&&o&&n!==o?n-o:0})}function zn(t){return`${String((t==null?void 0:t.role)||"").toLowerCase()}:${Jt(t==null?void 0:t.content).slice(0,100)}`}function Hn(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=>Ga(i,n));return o>=0?(r.splice(o,1),!1):!0})}function Oc(t,s){const r=new Set(s.map(n=>zn(n)));return t.filter(n=>!r.has(zn(n)))}function zc(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Hc(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 Un(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 qa(t){if(!t)return"";let s="";try{s=JSON.stringify(t.content??"")}catch{s=String(t.content??"")}return Hc([String(t.id||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),s])}function Uc(t){return{knownMessageCount:t.length,lastMessageSignature:qa(t[t.length-1])}}function Fc(t,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return t;case"append":return ks([...t,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??t.length),t.length));return ks([...t.slice(0,n),...r])}case"full":default:return r}}const Vc=60,Fn=60;function zr({activeConv:t,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:p=!0}){var F,D,me,ie;const h=a.useRef(new Map),g=a.useRef(new Map),C=a.useRef(new Map),{sendCommand:I,sendData:d}=mt(),b=$s();Ls("ChatPane",{tabKey:t.tabKey,messageCount:t.messages.length,actionLogCount:c.length,isSendingChat:n});const y=Ge.useMemo(()=>ms(t),[t.status,t.connectionState]),l=a.useRef(new Map),S=a.useCallback(X=>(l.current.has(X)||l.current.set(X,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:Vc}),l.current.get(X)),[]),M=a.useCallback((X,be)=>{const ne=S(X);l.current.set(X,{...ne,...be}),N(le=>le+1)},[S]),[,N]=a.useState(0),x=t.tabKey,w=S(x),v=w.messages,j=w.hasMore,B=w.error,E=g.current.get(x),W=t.messages.filter(X=>!!(X!=null&&X._localId)),T=E?ks([...E,...W]):t.messages,G=Math.max(0,T.length-w.visibleLiveCount),_=mr(t),k=nr(t),K=t.sessionId||"",J=t.providerSessionId||K,P=a.useMemo(()=>Pc(t,s),[t,s]),[$,z]=a.useState(!1);a.useEffect(()=>{const X=P.targetEntry;k&&(!X||X.providerControls===void 0||X.controlValues===void 0||P.isAcp&&(X.acpConfigOptions===void 0||X.acpModes===void 0))&&b(k,{minFreshMs:3e4}).catch(()=>{})},[k,P.isAcp,(F=P.targetEntry)==null?void 0:F.providerControls,(D=P.targetEntry)==null?void 0:D.controlValues,(me=P.targetEntry)==null?void 0:me.acpConfigOptions,(ie=P.targetEntry)==null?void 0:ie.acpModes,b]),a.useEffect(()=>{if(!k||!K||!d)return;const X=g.current.get(x)||[],be=C.current.get(x),ne=be&&be.knownMessageCount?be:Uc(X),le=`daemon:${k}:session:${K}`;return Dt.subscribe({sendData:d},k,{type:"subscribe",topic:"session.chat_tail",key:le,params:{targetSessionId:K,historySessionId:J,knownMessageCount:ne.knownMessageCount,lastMessageSignature:ne.lastMessageSignature,...ne.knownMessageCount?{}:{tailLimit:Fn}}},de=>{const q=g.current.get(x)||[],se=Fc(q,de),te=Math.max(se.length,Number(de.totalMessages||0));C.current.set(x,{knownMessageCount:te,lastMessageSignature:typeof de.lastMessageSignature=="string"?de.lastMessageSignature:qa(se[se.length-1])}),Un(q)!==Un(se)&&(g.current.set(x,se),N(fe=>fe+1))})},[k,J,d,K,x]);const U=a.useCallback(async()=>{if($)return;const X=t.tabKey,be=S(X);if(T.length>be.visibleLiveCount){M(X,{visibleLiveCount:Math.min(T.length,be.visibleLiveCount+Fn),error:null});return}z(!0),M(X,{error:null});try{const ne=nr(t);if(!ne){M(X,{hasMore:!1});return}const le=lt(t),ae=await I(ne,"chat_history",{agentType:le,offset:be.offset,limit:30,targetSessionId:t.sessionId,historySessionId:t.providerSessionId||t.sessionId}),de=zc(ae),q=de.messages||[];if(q.length>0){const se=S(X);M(X,{messages:[...q,...se.messages],offset:se.offset+q.length,hasMore:!!de.hasMore})}else M(X,{hasMore:!!de.hasMore})}catch(ne){const le=(ne==null?void 0:ne.message)||"";le.includes("P2P not available")||le.includes("channel not open")||le.includes("P2P not connected")||le.includes("timeout")?M(X,{error:"Connection not ready — tap to retry"}):M(X,{hasMore:!1,error:"Failed to load history"})}finally{z(!1)}},[$,t,T.length,I,S,M]),{allMessages:Y,receivedAtMap:re}=a.useMemo(()=>{const X=G>0?T.slice(-w.visibleLiveCount):T;if(v.length===0){const ae=On(ks(X)),de={};return ae.forEach((q,se)=>{const te=`${t.tabKey}:${ns(q,se)}`;let ge=Zt(q)||h.current.get(te)||0;ge||(ge=Date.now(),h.current.set(te,ge)),de[ns(q,se)]=ge}),{allMessages:ae,receivedAtMap:de}}const be=Oc(v,X),ne=On(ks([...be,...X])),le={};return ne.forEach((ae,de)=>{const q=`${t.tabKey}:${ns(ae,de)}`;let se=Zt(ae)||h.current.get(q)||0;se||(se=Date.now(),h.current.set(q,se)),le[ns(ae,de)]=se}),{allMessages:ne,receivedAtMap:le}},[t.tabKey,G,v,T,w.visibleLiveCount]),pe=a.useMemo(()=>c.filter(X=>X.routeId===t.tabKey).sort((X,be)=>X.timestamp-be.timestamp),[c,t.tabKey]),O=a.useMemo(()=>{if(T.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((y.isGenerating||t.status==="streaming")&&z(!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(Is,{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(cs,{size:14})," Open ",_," 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(La,{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(cs,{size:14})," Open ",_," 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"&&!$)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,$,T.length,_,y.isGenerating]);return e.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&e.jsx(Va,{conversation:t,className:"chat-pane-meta-row"}),e.jsx(tc,{messages:Y,actionLogs:pe,agentName:Es(t)||_||"Agent",userName:u,isCliMode:P.isCli||P.isAcp,isWorking:y.isGenerating,contextKey:t.tabKey,receivedAtMap:re,onLoadMore:U,isLoadingMore:$,hasMoreHistory:j,hiddenLiveCount:G,loadError:B??void 0,emptyState:O,scrollToBottomRequestNonce:f}),p&&!P.isCliTerminal&&(()=>{var X,be,ne,le,ae,de;return e.jsx(fc,{routeId:t.routeId,sessionId:t.sessionId,hostIdeType:t.hostIdeType,providerType:P.providerType,displayLabel:P.displayLabel,controls:(X=P.targetEntry)==null?void 0:X.providerControls,controlValues:(be=P.targetEntry)==null?void 0:be.controlValues,serverModel:((ne=P.targetEntry)==null?void 0:ne.currentModel)||void 0,serverMode:((le=P.targetEntry)==null?void 0:le.currentPlan)||void 0,acpConfigOptions:P.isAcp?(ae=P.targetEntry)==null?void 0:ae.acpConfigOptions:void 0,acpModes:P.isAcp?(de=P.targetEntry)==null?void 0:de.acpModes:void 0})})(),!P.isCliTerminal&&e.jsx(xc,{contextKey:t.tabKey,panelLabel:_,isSending:n,onSend:r,isActive:p})]})}let Ya=Yt;function Xa(){return Ya()}class Gc{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(o=>o(...r))}}let Ja=new Gc;class qc{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 Fe=new qc;function Yc(t){t.dashboardWS&&(Ja=t.dashboardWS),t.connectionManager&&(Fe=t.connectionManager),t.useDaemonsHook&&(Ya=t.useDaemonsHook)}function Ve(t){return mr(t)}function Qt(t){return nn(t).join(" · ")}function Za(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=Jt(s==null?void 0:s.content);return r||(t.title?t.title:Qt(t)||"No messages yet")}function Qa(t,s){const{isReconnecting:r,isConnecting:n}=ms(t);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Xc(t,s){const r=["Chat",...nn(t)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function os(t){return Qa(t)||Qt(t)}function Jc(t){return`${Ve(t)} · ${Za(t)}`}function Zc(t){const s=rn(t)||lt(t);return`${Ve(t)} — ${Oe(s)}`}function Qc(t){return Es(t)||"CLI"}function eo(t){return t.title||Es(t)||t.routeId}function el(t){return t?`Remote · ${Ve(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}=Yt(),u=a.useRef(null),{sendCommand:m,sendData:f}=mt(),[p,h]=a.useState(""),[g,C]=a.useState(!1),[I,d]=a.useState(1),b=a.useRef(!1),y=a.useRef(0),l=a.useRef(!1),S=a.useRef(""),M=a.useRef(null),N=a.useRef(!1),x=a.useRef(null),w=t.tabKey,v=t.sessionId||"",j=t.daemonId||(($=t.routeId)==null?void 0:$.split(":")[0])||t.routeId||"",B=c.find(z=>z.id===j&&z.type==="adhdev-daemon"),E=(B==null?void 0:B.terminalSizingMode)==="fit"?"fit":"measured",W=.6,T=1.15,G=()=>{if(typeof window>"u")return 1;const z=window.innerWidth||0;return z<=360?.68:z<=390?.74:z<=430?.82:z<=480?.9:1},_=()=>{var z,U;y.current=0,l.current=!1,S.current="",M.current=null,N.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),C(!1),(U=(z=r.current)==null?void 0:z.reset)==null||U.call(z)},k=()=>{var z,U;y.current=0,l.current=!1,S.current="",M.current=null,N.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),C(!0),(U=(z=r.current)==null?void 0:z.reset)==null||U.call(z)},K=()=>{var U;if(x.current=null,!i)return;const z=S.current;z&&(S.current="",(U=r.current)==null||U.write(z))},J=z=>{z&&(S.current+=z,i&&x.current===null&&(x.current=requestAnimationFrame(K)))},P=(z,U=0,Y,re)=>{var pe,O,F,D,me;U>0&&y.current>=U||U===0&&l.current||(y.current=U,C(!0),typeof Y=="number"&&typeof re=="number"&&Y>0&&re>0&&((O=(pe=r.current)==null?void 0:pe.resize)==null||O.call(pe,Y,re)),(D=(F=r.current)==null?void 0:F.reset)==null||D.call(F),z&&((me=r.current)==null||me.write(z)))};return a.useEffect(()=>{_()},[v]),a.useEffect(()=>{var U;if(!v)return;const z=((U=Fe.onRuntimeEvent)==null?void 0:U.call(Fe,v,Y=>{if(!(!Y||Y.sessionId!==v)){if(Y.type==="runtime_snapshot"){if(!i){M.current={text:Y.text||"",seq:Y.seq||0,cols:Y.cols,rows:Y.rows};return}P(Y.text||"",Y.seq||0,Y.cols,Y.rows);return}if(Y.type==="session_output"){l.current=!0,typeof Y.seq=="number"&&(y.current=Math.max(y.current,Y.seq)),g||C(!0),typeof Y.data=="string"&&J(Y.data);return}if(Y.type==="session_cleared"){if(!i){N.current=!0,S.current="",M.current=null;return}k()}}}))||(()=>{});return()=>{z()}},[j,v,r,i,g]),a.useEffect(()=>{var U,Y,re;if(!v)return;j&&((U=Fe.getState)==null?void 0:U.call(Fe,j))==="connected"&&(C(!0),(Y=Fe.requestRuntimeSnapshot)==null||Y.call(Fe,j,v).catch(()=>{}));const z=(re=Fe.onStateChange)==null?void 0:re.call(Fe,(pe,O)=>{var F;pe!==j||O!=="connected"||(C(!0),(F=Fe.requestRuntimeSnapshot)==null||F.call(Fe,j,v).catch(()=>{}))});return()=>{z==null||z()}},[j,v,r]),a.useEffect(()=>{s&&_()},[s,w,r]),a.useEffect(()=>{h("")},[t.tabKey]),a.useEffect(()=>{const z=()=>{b.current||d(G())};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{var U;if(!i){(U=u.current)==null||U.blur();return}N.current&&(N.current=!1,k());const z=M.current;z&&(M.current=null,P(z.text,z.seq,z.cols,z.rows)),S.current&&x.current===null&&(x.current=requestAnimationFrame(K)),requestAnimationFrame(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})},[i]),a.useEffect(()=>()=>{x.current!==null&&(cancelAnimationFrame(x.current),x.current=null)},[]),a.useEffect(()=>{const z=U=>{var re;const Y=U.detail;Y!=null&&Y.sessionId&&Y.sessionId!==v||g&&((re=r.current)==null||re.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",z),()=>{window.removeEventListener("adhdev:fit-cli-terminal",z)}},[g,v,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,d(z=>Math.max(W,Number((z-.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,d(z=>Math.min(T,Number((z+.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(Da,{ref:r,readOnly:!g||!i,sizingMode:E,onInput:z=>{g&&(f!=null&&f(j,{type:"pty_input",targetSessionId:v,data:z})||m(j,"pty_input",{targetSessionId:v,data:z}).catch(console.error))}})})}),!g&&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:u,type:"text",placeholder:`Send message to ${Ve(t)}...`,value:p,disabled:!g||!i||o,onChange:z=>h(z.target.value),onPaste:z=>{const U=z.clipboardData.getData("text");U&&h(Y=>Y+U),z.preventDefault()},onKeyDown:z=>{if(z.key!=="Enter")return;if(z.nativeEvent.isComposing){z.preventDefault();return}z.preventDefault();const U=p.trim();!g||!U||o||(h(""),n(U))},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 z=p.trim();!g||!z||o||(h(""),n(z))},disabled:!g||!i||!p.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.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:p.trim()?"text-white":"text-text-muted",children:e.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function sl({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)"},u={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:u[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 rl({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 u=(r==null?void 0:r.trim())||"This machine",m=()=>{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:[u," 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:m,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 on({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(lr,{size:n}):e.jsx(Lt,{size:n})})}function Vn({conversation:t,isAttention:s,shortcutIndex:r,onClick:n}){const o=nn(t);return e.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:mr(t)}),(r||o.length>0)&&e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,o.join(" · ")]})]})}function nl({activeConv:t,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:u,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:p,onHideConversation:h,hiddenConversations:g=[],onShowConversation:C,onShowAllHidden:I,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:l,onOpenNewSession:S}){const{ides:M,p2pStates:N={}}=Yt(),x=!!t&&We(t)&&!$e(t),w=!!t&&$e(t),v=m||(t?Ua(t)?"terminal":"chat":null),[j,B]=a.useState(!1),E=a.useRef(null),W=a.useRef(null),T=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",G=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",_=M.filter(D=>D.type==="adhdev-daemon"),k=a.useMemo(()=>Rs(M),[M]),K=Object.values(N),J=K.filter(D=>D==="connected").length,P=K.filter(D=>D==="connecting"||D==="new"||D==="checking").length,z=r!=="connected"||_.length===0?null:P>0&&J===0?"P2P connecting...":J>0&&s===0?"Waiting for IDE...":null,U=a.useMemo(()=>o.filter(D=>!mc(D,o,k)),[o,k]),Y=a.useMemo(()=>U.filter(D=>_s(D,k).requiresAction),[U,k]),re=a.useMemo(()=>U.filter(D=>{const me=(t==null?void 0:t.tabKey)===D.tabKey;return _s(D,k,{hideOpenTaskCompleteUnread:!0,isOpenConversation:me}).unread}),[t,U,k]),pe=a.useMemo(()=>[...Y,...re].slice(0,9),[Y,re]),O=Y.length+re.length;a.useEffect(()=>{if(!d)return;const D=me=>{var ie;(ie=E.current)!=null&&ie.contains(me.target)||b(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[d,b]),a.useEffect(()=>{if(!y)return;const D=me=>{var ie;(ie=W.current)!=null&&ie.contains(me.target)||l(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[y,l]),a.useEffect(()=>{if(!y&&!d)return;const D=me=>{if(!me.altKey)return;const ie=me.code.match(/^Digit([1-9])$/);if(!ie)return;const X=Number(ie[1])-1,be=y?g[X]:void 0,ne=d?pe[X]:void 0,le=be||ne;if(le){if(me.preventDefault(),me.stopPropagation(),be){C==null||C(be),l(!1);return}p==null||p(le),b(!1)}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[g,y,d,pe,l,b,p,C]);const F=D=>{if(!D)return;const me=o.find(ie=>ie.tabKey===D);me&&(h==null||h(me))};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(Lt,{size:18}),e.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),e.jsx("span",{className:"header-title-mobile",children:t?Ve(t):"Dashboard"}),e.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:e.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:T,boxShadow:G}})})]}),e.jsxs("div",{className:"header-subtitle flex items-center",children:[e.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:T,boxShadow:G}}),z&&e.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",z]}),S&&e.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:"Start a new session","aria-label":"Start a new session",children:e.jsx(Ki,{size:14})})]})]})})}),e.jsxs("div",{className:"flex gap-2 items-center",children:[t&&(x||w||!$e(t))&&e.jsxs("div",{className:"dashboard-header-actions-group",children:[e.jsx("span",{className:"dashboard-header-action-target",title:Qt(t)||Ve(t),children:Ve(t)}),(x||w)&&u&&e.jsxs(e.Fragment,{children:[x&&f&&v&&e.jsx(on,{mode:v,onChange:f,compact:!0}),e.jsx("button",{onClick:()=>u(t),className:"btn btn-secondary btn-sm",title:w?"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(bt,{size:14})})]}),!$e(t)&&e.jsx("button",{onClick:()=>i(t),className:"btn btn-secondary btn-sm",title:"Chat History",children:e.jsx(Qr,{size:14})}),!x&&!$e(t)&&e.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:e.jsx(ut,{size:14})})]}),e.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[e.jsxs("div",{className:`dashboard-header-hidden${j?" is-drop-target":""}`,ref:W,onDragEnter:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),B(!0))},onDragOver:D=>{D.dataTransfer.types.includes("text/tab-key")&&(D.preventDefault(),D.dataTransfer.dropEffect="move",B(!0))},onDragLeave:D=>{D.currentTarget.contains(D.relatedTarget)||B(!1)},onDrop:D=>{const me=D.dataTransfer.getData("text/tab-key");D.preventDefault(),B(!1),F(me)},children:[e.jsxs("button",{type:"button",onClick:()=>l(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:"Hidden tabs. Drag a tab here to hide it.",children:[e.jsx($i,{size:16}),g.length>0&&e.jsx("span",{className:"dashboard-header-hidden-badge",children:g.length})]}),y&&e.jsxs("div",{className:"dashboard-header-hidden-popover",children:[e.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),g.length>0&&I&&e.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{I(),l(!1)},children:"Restore all"})]}),t&&h&&e.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(t),children:[e.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),e.jsx("span",{className:"dashboard-header-hidden-current-title",children:Ve(t)})]}),g.length>0?e.jsx("div",{className:"dashboard-header-hidden-list",children:g.map(D=>e.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{C==null||C(D),l(!1)},children:[e.jsx("span",{className:"dashboard-header-inbox-item-title",children:Ve(D)}),e.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[g.indexOf(D)<9?e.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",g.indexOf(D)+1]}):null,Qt(D)]})]},D.tabKey))}):e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),e.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[e.jsx(dr,{size:16}),O>0&&e.jsx("span",{className:"dashboard-header-inbox-badge",children:O})]}),d&&e.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Y.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Y.map(D=>e.jsx(Vn,{conversation:D,isAttention:!0,shortcutIndex:pe.indexOf(D)>=0?pe.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.tabKey))]}),re.length>0&&e.jsxs("div",{className:"dashboard-header-inbox-section",children:[e.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),re.map(D=>e.jsx(Vn,{conversation:D,shortcutIndex:pe.indexOf(D)>=0?pe.indexOf(D)+1:void 0,onClick:()=>{p==null||p(D),b(!1)}},D.tabKey))]}),O===0&&e.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function al(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:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:p,onResumeSavedSession:h}){var y;const g=s.find(l=>l.id===t.routeId),C=(g==null?void 0:g.chats)||[],I=(y=g==null?void 0:g.activeChat)==null?void 0:y.id,d=We(t)&&!$e(t),b=e.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[e.jsx("div",{onClick:u,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:d?"Saved Sessions":"Chat History"}),e.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Zc(t)})]}),e.jsx("button",{onClick:u,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(bt,{size:16})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!d&&e.jsx("button",{onClick:m,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"}),d?e.jsx(e.Fragment,{children:o.map(l=>{const S=t.providerSessionId===l.providerSessionId,M=S||!l.canResume||!!c;return e.jsxs("button",{type:"button",onClick:()=>{M||!h||h(l)},disabled:M,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${S?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${M?"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 ${S?"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:al(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:S?"ACTIVE":l.canResume?c===l.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},l.id)})}):C.map(l=>e.jsxs("div",{onClick:()=>{f(t.routeId,l.id),u()},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)),(d&&!i&&o.length===0||!d&&C.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(zi,{size:32})}),e.jsx("div",{className:"text-[13px]",children:d?"No saved sessions found yet.":"No recent chat sessions found."})]}),d&&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:p,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(us,{size:13})," ",d?"Refresh Sessions":"Refresh History"]})})})]})]});return typeof document>"u"?b:Sa.createPortal(b,document.body)}const Gn={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 to({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=Gn[n.type]||Gn.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(bt,{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:u=>{u.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const ol=t=>t.transport==="pty"||t.transport==="acp"||t.transport==="cdp-page"?!0:t.daemonId!==t.id;function il(t){const s=t.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function cl(t){return t.sessionId||t.instanceId||t.agentType}function Sr(t,s){return t||s}function qn(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 so(t=[]){const s={};for(const r of t)r.type==="adhdev-daemon"&&(s[r.id]=dt(r,{fallbackId:r.id}));return s}function ro(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 ln(t,s,r={}){return ll(t,s,ro(t,r))}function ll(t,s,r={}){var g,C,I,d,b,y;const n=[],o=r.machineName,i=r.connectionState,c=il(t),u=Oe(t.type),m=Array.isArray(t.childSessions)?t.childSessions.map(l=>{var S,M;return{sessionId:l.id,instanceId:l.id,providerSessionId:l.providerSessionId,transport:l.transport,agentType:l.providerType,agentName:l.providerName||Oe(l.providerType),status:l.status,title:l.title,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,messages:((S=l.activeChat)==null?void 0:S.messages)||[],activeModal:((M=l.activeChat)==null?void 0:M.activeModal)||void 0,unread:l.unread,lastSeenAt:l.lastSeenAt,lastUpdated:l.lastUpdated,inboxBucket:l.inboxBucket,surfaceHidden:l.surfaceHidden}}):[],f=ol(t),p=t.activeChat||{title:""},h=p.title&&String(p.title).trim()?String(p.title).trim():"";if(f){const l=t.sessionId||t.instanceId,S=En(t.type),M=(g=t.activeChat)==null?void 0:g.activeModal,N=M&&Array.isArray(M.buttons)&&M.buttons.length>0,x=rt((C=t.activeChat)==null?void 0:C.status,{activeModal:(I=t.activeChat)==null?void 0:I.activeModal})||rt((b=(d=t.agents)==null?void 0:d[0])==null?void 0:b.status)||"idle",w=t.activeChat||{title:"",messages:[]};let v=w.title&&String(w.title).trim()?String(w.title).trim():"";const j=(y=t.activeChat)==null?void 0:y.id,B=t.chats;if(j&&Array.isArray(B)&&B.length>0){const k=B.find(K=>K.id===j||K.id&&String(K.id)===String(j));k!=null&&k.title&&String(k.title).trim()&&(v=String(k.title).trim())}const E=(We(t)||$e(t),t.type),W=(We(t)||$e(t))&&$n(v,S,E)?"":v,T=w.messages||[],G=qn(s,[t.id,l]),_=Hn(T,G);n.push({routeId:t.id,sessionId:l,providerSessionId:t.providerSessionId,nativeSessionId:l,transport:t.transport,daemonId:t.daemonId||void 0,mode:We(t)?t.mode||"terminal":"chat",agentName:S,agentType:E,status:x,title:W,messages:[...T,..._],resume:t.resume,hostIdeType:!We(t)&&!$e(t)?t.type:void 0,workspaceName:c,displayPrimary:c||W||(We(t)?t.mode==="chat"?S:"Terminal":S),displaySecondary:u,cdpConnected:t.cdpConnected,lastMessagePreview:t.lastMessagePreview,lastMessageRole:t.lastMessageRole,lastMessageAt:t.lastMessageAt,lastMessageHash:t.lastMessageHash,lastUpdated:t.lastUpdated,modalButtons:N?M.buttons:void 0,modalMessage:N?M.message:void 0,streamSource:"native",tabKey:Sr(l,t.id),machineName:o,connectionState:i})}if(f&&(We(t)||$e(t)))return n;for(const l of m){const S=l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.length>0,M=kc(l),N=cl(l),x=`${t.id}:${N}`,w=l.title&&String(l.title).trim()||"",v=$n(w,l.agentName,l.agentType)?"":w,j=l.messages||[],B=qn(s,[x,l.sessionId,l.instanceId]),E=Hn(j,B);(l.transport==="cdp-webview"||l.sessionId||l.providerSessionId||j.length>0||E.length>0||S||v||!["idle","panel_hidden","disconnected","not_monitored"].includes(M))&&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:M,title:v,messages:[...j,...E],hostIdeType:t.type,workspaceName:c,displayPrimary:c||h||v||u,displaySecondary:`${u} · ${l.agentName}`,cdpConnected:t.cdpConnected,lastMessagePreview:l.lastMessagePreview,lastMessageRole:l.lastMessageRole,lastMessageAt:l.lastMessageAt,lastMessageHash:l.lastMessageHash,lastUpdated:l.lastUpdated||t.lastUpdated,modalButtons:S?l.activeModal.buttons:void 0,modalMessage:S?l.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Sr(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:En(t.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:t.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:t.cdpConnected,lastUpdated:t.lastUpdated,streamSource:"native",tabKey:Sr(t.sessionId||t.instanceId,t.id),connectionState:i}),n}function dl(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=dl(t);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const no=[{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:"🏄"}],ao=[{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:"🧩"}],oo=[{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:"🟠"}],ml=no,pl=ao,fl=oo,io="adhdev_notification_prefs",Yn={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function xl(){try{const t=localStorage.getItem(io);if(t){const s=JSON.parse(t);return{...Yn,...s}}}catch{}return{...Yn}}function hl(t){try{localStorage.setItem(io,JSON.stringify(t))}catch{}}let Tt=xl(),Js=[];function bl(){Js.forEach(t=>t())}function gl(t){Tt={...Tt,...t},hl(Tt),bl()}function yl(){const[,t]=a.useState(0);a.useEffect(()=>{const r=()=>t(n=>n+1);return Js.push(r),()=>{Js=Js.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{gl(r)},[]);return[{...Tt},s]}function Ns(t){if(!Tt.globalEnabled)return!1;switch(t){case"disconnect":return Tt.disconnectAlert;case"completion":return Tt.completionAlert;case"approval":return Tt.approvalAlert;case"browser":return Tt.browserNotifications;default:return!0}}const vl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function wl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function co(){return"Notification"in window&&Notification.permission==="granted"}let zt=null;async function jl(){if(zt!==null)return zt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return zt=!1,!1;const t=await navigator.serviceWorker.getRegistration();return t?(zt=!!await t.pushManager.getSubscription(),zt):(zt=!1,!1)}catch{return zt=!1,!1}}function Hr(t,s,r){if(co())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 kl(t,s={}){const r={...vl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{jl().then(u=>{i.current=u})},[]);const c=a.useCallback((u,m,f)=>{const p=Date.now();p-o.current<r.throttleMs||(o.current=p,Hr(u,m,f))},[r.throttleMs]);a.useEffect(()=>{var u;if(!(!r.enabled||!co())&&Ns("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of t)n.current.set(m.id,rt(m.status,{activeModal:m.activeModal}));return}for(const m of t){const f=n.current.get(m.id),p=rt(m.status,{activeModal:m.activeModal}),h=m.name||m.id;if(r.onApproval&&Ns("approval")&&p==="waiting_approval"&&f!=="waiting_approval"){const g=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,g.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ns("completion")&&za(f)&&p==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&f!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[t,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Nl=/^(run|approve|accept|yes|allow|always)/,Sl=/^(run|approve|accept|yes|allow|always|proceed|save)/,Cl=/^(reject|deny|delete|remove|abort|cancel|no)/;function dn(t){return t.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Il(t){const s=dn(t).toLowerCase();return Nl.test(s)?"primary":Cl.test(s)?"danger":"default"}function Ml(t){return Sl.test(dn(t).toLowerCase())?"approve":"reject"}function _l(t){return t.map((s,r)=>({label:dn(s),variant:Il(s),action:Ml(s),button:s,buttonIndex:r}))}function Al(t,s){const r=t||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
29
|
+
${n}`}function Tl(t,s,r){return s?`⚡ ${t}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Pl(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 Ll{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const 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,d;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),u=`${i}:${s.event}:${c}`;if(this.isDuplicate(u))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(m==null?void 0:m.type)||"";let p=Oe(f);const h=this.resolveOwningDaemon(s);if(h){const b=dt(h,{fallbackId:h.id});b&&(p=!f||f==="adhdev-daemon"?b:`${b}/${p}`)}let g="",C="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";g=`✅ ${p} agent task completed${b}`,C="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(g=`⚡ ${p} approval needed`,C="warning",n&&!((I=s.modalButtons)!=null&&I.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:Al(s.modalMessage,s.modalButtons),_localId:`sys_approval_${o}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const y=this.resolveActionFn,l=_l(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{y(b,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Tl(p,s.modalMessage,g),M=Date.now();this.emitToast({id:M,message:S,type:C,timestamp:M,targetKey:n||b,actions:l,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${p} agent is taking a long time${b}`,C="warning",Ns("browser")&&!document.hasFocus()&&Hr(`⚠️ ${p} — 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",y=s.requestId,l=s.orgId;if(g=`👁️ ${b} wants to view your session`,C="warning",y&&l&&this.viewRequestRespondFn){const S=Date.now(),M=Pl(l,y,this.viewRequestRespondFn,(N,x)=>console.error(`[EventManager] ${N} view request failed:`,x));this.emitToast({id:S,message:g,type:C,timestamp:S,actions:M,duration:3e4}),g=""}Ns("browser")&&!document.hasFocus()&&Hr("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",C="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,C="warning");if(g){const b=Date.now();this.emitToast({id:b,message:g,type:C,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new Ll;function es(...t){return mi(pi(t))}function Rl({icon:t,title:s,subtitle:r,badge:n,actions:o,className:i}){return e.jsxs("div",{className:es("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 lo({icon:t,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:u}){return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Rl,{icon:t,title:s,subtitle:r,badge:n,actions:o}),e.jsx("div",{className:"page-content",children:e.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",i,c),children:u})})]})}function wt({title:t,icon:s,description:r,accentColor:n,className:o,children:i}){return e.jsxs("div",{className:es("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",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 uo({icon:t,title:s,description:r,action:n,className:o}){return e.jsxs("div",{className:es("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 El={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"},$l={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dl({variant:t,children:s,onDismiss:r,className:n}){return e.jsxs("div",{className:es("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",El[t],n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:$l[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 Bl={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"},Kl={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Wl({status:t,label:s,className:r}){const n=s||t;return e.jsxs("span",{className:es("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Bl[t],r),children:[e.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Kl[t])}),n]})}function Ol(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ur(){try{const t=localStorage.getItem("theme");if(t==="dark"||t==="light"||t==="system")return t}catch{}return"system"}function Zs(t){return t==="system"?Ol():t}function zl(){typeof document>"u"||document.documentElement.setAttribute("data-theme",Zs(Ur()))}function un(){const[t,s]=a.useState(Ur),[r,n]=a.useState(()=>Zs(Ur()));a.useEffect(()=>{document.documentElement.setAttribute("data-theme",r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),u=m=>{t==="system"&&n(m.matches?"light":"dark")};return c.addEventListener("change",u),()=>c.removeEventListener("change",u)},[t]);const o=a.useCallback(c=>{s(c),n(Zs(c));try{localStorage.setItem("theme",c)}catch{}},[]),i=a.useCallback(()=>{s(c=>{const u=c==="dark"?"light":c==="light"?"system":"dark";n(Zs(u));try{localStorage.setItem("theme",u)}catch{}return u})},[]);return{theme:r,preference:t,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Xn={dark:"Dark",light:"Light",system:"System"};function Hl({collapsed:t}){const{preference:s,cycleTheme:r}=un(),n=s==="dark"?e.jsx(Ui,{size:16}):s==="light"?e.jsx(Hi,{size:16}):e.jsx(Fi,{size:16});return e.jsxs("div",{className:`nav-item cursor-pointer ${t?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Xn[s]} (click to cycle)`,children:[e.jsx("span",{className:"nav-icon",children:n}),!t&&e.jsx("span",{className:"text-xs",children:Xn[s]})]})}function Ut({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 Ul({onPrefChange:t}){const[s,r]=yl(),n=(o,i)=>{r({[o]:i}),t==null||t(o,i)};return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(dr,{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(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{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(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vi,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),e.jsx(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gi,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),e.jsx(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Is,{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 Fl(t){return!t||typeof t!="object"?{}:"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function Cr(t,s){return t instanceof Error?t.message:s}function Vl({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(uo,{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(ql,{ide:c,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function Jn({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 Sa.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:u=>u.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 Gl(t){const s=t.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...ml,...pl,...fl].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 ql({ide:t,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var T,G;const[i,c]=a.useState("idle"),[u,m]=a.useState(""),[f,p]=a.useState(null),[h,g]=a.useState("idle"),[C,I]=a.useState(""),d=t.version||null,b=((T=t.machine)==null?void 0:T.platform)||((G=t.system)==null?void 0:G.platform)||"",y=dt(t,{fallbackId:t.id}),l=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",S=s.filter(_=>_.daemonId===t.id&&_.transport==="cdp-page"),M=s.filter(_=>_.daemonId===t.id&&_.transport==="pty"),N=s.filter(_=>_.daemonId===t.id&&_.transport==="acp"),x=t.p2p,w=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const _=Fl(await r(t.id,"daemon_upgrade",{}));_.alreadyLatest?(c("done"),m(`Already on v${_.version||"latest"}.`)):_.upgraded||_.success?(c("done"),m(`Upgrade to v${_.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(_.error||"Upgrade failed"))}catch(_){c("error"),m(Cr(_,"Connection lost during upgrade"))}}},v=async()=>{if(p(null),!!n){g("loading");try{await n(t.id),g("done"),I("Machine disconnected.")}catch(_){g("error"),I(Cr(_,"Failed to disconnect"))}}},j=async()=>{if(p(null),!!o){g("loading");try{await o(t.id),g("done"),I('Token revoked. Machine must restart "adhdev-standalone" to reconnect.')}catch(_){g("error"),I(Cr(_,"Failed to revoke token"))}}},B="0.8.39",E=!d||d!==B,W=S.length+M.length+N.length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:l}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y}),e.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[e.jsxs("span",{children:[t.id.substring(0,12),"…"]}),d&&e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${E?"":"bg-bg-secondary"}`,style:E?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!E&&" ✓"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&E&&e.jsx("button",{onClick:w,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:i==="upgrading"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`↑ Update${` to v${B}`}`}),n&&e.jsx("button",{onClick:()=>p("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:()=>p("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(Wl,{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&&W>0&&e.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(_=>{const k=Gl(_.type),K=_.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:k.icon}),e.jsx("span",{children:k.name}),K!==void 0&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},_.id)}),M.map(_=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"⌨️"}),e.jsx("span",{children:_.cliName||"CLI"})]},_.id)),N.map(_=>e.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[e.jsx("span",{children:"🔗"}),e.jsx("span",{children:_.cliName||"ACP"})]},_.id))]}):e.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(u||C)&&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:C||u})]}),f==="disconnect"&&e.jsx(Jn,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
30
30
|
|
|
31
31
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
32
32
|
|
|
@@ -37,22 +37,22 @@ This will:
|
|
|
37
37
|
• Delete the machine registration
|
|
38
38
|
• Require restarting "adhdev-standalone" on that machine
|
|
39
39
|
|
|
40
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>p(null)})]})}const Yl=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Xl(){const{preference:t,setPreference:s}=un();return e.jsx("div",{className:"flex gap-2",children:Yl.map(r=>e.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function Jl(t){const s=t.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Zl(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Ir(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Zn(t){const{r:s,g:r,b:n}=Zl(t);return .2126*Ir(s)+.7152*Ir(r)+.0722*Ir(n)}function Qn(t,s){const r=Zn(t),n=Zn(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function mo(t){const s=Jl(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return Qn(s,r)>=Qn(s,n)?r:n}const Fr={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},Vr={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},Ql=[{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"}}}],po="adhdev-chat-theme",fo="adhdev-chat-theme-custom";function Qs(){if(typeof window>"u")return"ember";try{return localStorage.getItem(po)||"ember"}catch{return"ember"}}function jt(t){try{const s=localStorage.getItem(fo);if(s){const r=JSON.parse(s);return{...t==="dark"?Fr:Vr,...r[t]}}}catch{}return t==="dark"?Fr:Vr}function zs(t,s){try{localStorage.setItem(fo,JSON.stringify({dark:t,light:s}))}catch{}}function xt(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 or(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 ed={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ss(t,s){var o;const r=(o=ed[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",or(r,24)),n.style.setProperty("--accent-on-primary",mo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${or(r,18)})`),n.style.setProperty("--border-accent",xt(r,.35)),n.style.setProperty("--nav-active-bg",xt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${xt(r,.06)}`)}function Ft(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",xt(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",xt(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",xt(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",xt(t.borderSubtle,.5)),s.style.setProperty("--border-default",xt(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",or(t.accentColor,30)),s.style.setProperty("--accent-on-primary",mo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${or(t.accentColor,40)})`),s.style.setProperty("--border-accent",xt(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",xt(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${xt(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 ${xt(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 mn(){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 td(t){try{localStorage.setItem(po,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(jt(s))}else mn(),Ss(t,Vt()?"dark":"light")}function sd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=Qs();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(jt(s))}else mn(),Ss(t,Vt()?"dark":"light")}function Vt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function st({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),e.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function bs({title:t,children:s}){return e.jsxs("div",{style:{marginBottom:14},children:[e.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:t}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function rd({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>jt(r));a.useEffect(()=>{o(jt(r))},[r]);const i=a.useCallback((c,d)=>{o(m=>{const f={...m,[c]:d},h=jt(r==="dark"?"light":"dark");return r==="dark"?zs(f,h):zs(h,f),Ft(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(bs,{title:"App Background",children:[e.jsx(st,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(st,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(st,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(bs,{title:"App Text",children:[e.jsx(st,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(st,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(st,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(bs,{title:"Borders & Accent",children:[e.jsx(st,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(st,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(st,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(bs,{title:"Chat Bubbles",children:[e.jsx(st,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(st,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(st,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(st,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(bs,{title:"Chat Layout",children:[e.jsx(st,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(st,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(st,{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?Fr:Vr,m=jt(t?"light":"dark");t?zs(c,m):zs(m,c),o(c),Ft(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 nd(){const[t,s]=a.useState(Qs),[r,n]=a.useState(!0),[o,i]=a.useState(()=>jt("dark"));a.useEffect(()=>{n(Vt());const m=new MutationObserver(()=>{const h=Vt();n(h);const g=Qs();g==="custom"?Ft(jt(h?"dark":"light")):Ss(g,h?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const h=Vt();n(h);const g=Qs();g==="custom"?Ft(jt(h?"dark":"light")):Ss(g,h?"dark":"light")};return f.addEventListener("change",p),()=>{m.disconnect(),f.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ft(jt(r?"dark":"light")):(mn(),Ss(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(jt(r?"dark":"light"))},[r]);const c=m=>{s(m),td(m)},d=[...Ql,{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(m=>{const f=t===m.id,p=r?m.preview.dark:m.preview.light,h=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(m.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:p.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.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:p.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:p.assistantBubble,border:p.assistantBorder,color:p.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:m.id==="custom"?"🎨 Custom":m.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),t==="custom"&&e.jsx(rd,{dark:r,onColorsChange:m=>i(m)})]})}const xo="adhdev_mobileDashboardMode_v1";function ho(){try{return localStorage.getItem(xo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ad(t){try{localStorage.setItem(xo,t)}catch{}}function od(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(ho()==="chat")},[]),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{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),ad(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function id(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 cd(t,s){const{sendData:r}=mt(),{injectEntries:n,getIdes:o}=rr(),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(m=>Dt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const p=o().find(g=>g.id===m),h=id(p,m,f);n([h])}));return()=>{d.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function bo(t,s){const{sendData:r}=mt(),[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);const d=Dt.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}:{}}},m=>{o(m.diagnostics),c(!1)});return()=>{d()}},[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 ld(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function go(t){const{sendData:s}=mt(),[r,n]=a.useState({});return a.useEffect(()=>{const o=ld(t);if(!o||!t.sessionId||!s){n({});return}const i=Dt.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})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const yo="adhdev_hiddenTabs";function dd(){try{const t=localStorage.getItem(yo);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ss(t){try{localStorage.setItem(yo,JSON.stringify([...t]))}catch{}}function ud(){const[t,s]=a.useState(dd),r=a.useCallback(f=>{s(p=>{const h=new Set(p);return h.has(f)?h.delete(f):h.add(f),ss(h),h})},[]),n=a.useCallback(f=>{s(p=>{if(p.has(f))return p;const h=new Set(p);return h.add(f),ss(h),h})},[]),o=a.useCallback(f=>{s(p=>{if(!p.has(f))return p;const h=new Set(p);return h.delete(f),ss(h),h})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const p=new Set;return ss(p),p})},[]),c=a.useCallback((f,p)=>{s(h=>{const g=new Set(h);for(const C of p)g.add(C);return ss(g),g})},[]),d=a.useCallback((f,p)=>{s(h=>{const g=new Set(h);for(const C of p)g.delete(C);return ss(g),g})},[]),m=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:d,isHidden:m}}function md({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{wl()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:eo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return kl(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(d=>{const m=Date.now(),f={};for(const[p,h]of Object.entries(d))m-h<5e3&&(f[p]=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 m=d.filter(f=>f.timestamp>c).slice(-100);return m.length===d.length?d:m})},6e4);return()=>clearInterval(i)},[n]),null}function pd(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 Gt(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return pd(s==null?void 0:s.receivedAt)||0}function Gr(t,s=0){return Gt(t)||t.lastUpdated||s||0}function vo(t){return Gt(t)||t.lastUpdated||0}function wo(t,s,r=vo){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 qr(t){var r;const s=rt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function fd(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!qr(t)&&!t.title.trim()}function xd(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(qr(r))-Number(qr(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:wo(s,r)})[0]||null}function Rt(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=xd(o);return n?i&&fd(n)?i:n:i||r[0]||null}function hd(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 Us(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 bd(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 gd(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 yd(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 vd(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function wd(t){const s=vd(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=Jt(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function jd({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),d=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const x=hd(t);return Us(i.current,x)?i.current:(i.current=x,x)},[t]),p=a.useMemo(()=>so(t),[t]),h=a.useRef(new Map),g=a.useRef(new Map),C=a.useMemo(()=>{const x=new Map,w=[];for(const E of f){const{connectionState:W="new",machineName:T}=ro(E,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),G=gd(E,r),A=h.current.get(E.id);if(A&&A.ide===E&&A.connectionState===W&&A.machineName===T&&yd(A.localRefs,G)){x.set(E.id,A),w.push(...A.conversations);continue}const k=ln(E,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),K={ide:E,connectionState:W,machineName:T,localRefs:G,conversations:k};x.set(E.id,K),w.push(...k)}h.current=x;const v=new Map,j=E=>{const W=wd(E),T=g.current.get(E.tabKey);if(T&&T.signature===W)return v.set(E.tabKey,T),T.timestamp;const G={signature:W,timestamp:vo(E)||(T==null?void 0:T.timestamp)||0};return v.set(E.tabKey,G),G.timestamp},B=[...w].sort((E,W)=>wo(E,W,j));return g.current=v,B},[f,r,s,p]),I=a.useMemo(()=>{const x=bd(C,n);return Us(c.current,x)?c.current:(c.current=x,x)},[C,n]),l=a.useMemo(()=>{const x=new Map,w=Array.from(new Set(I.map(v=>v.routeId)));for(const v of w){const j=Rt(I,v);j&&x.set(v,j)}return x},[I]),b=a.useMemo(()=>{const x=new Map;for(const w of I)if(w.sessionId&&x.set(w.sessionId,w),w.streamSource==="native"&&w.sessionId){const v=l.get(w.routeId);v&&x.set(w.sessionId,v)}return x},[I,l]),y=a.useMemo(()=>{const x=new Map;for(const w of I)w.sessionId&&x.set(w.sessionId,w),x.set(w.routeId,l.get(w.routeId)||w),x.set(w.tabKey,w);return x},[I,l]),u=a.useCallback(x=>{if(x)return b.get(x)},[b]),S=a.useCallback(x=>{if(x)return y.get(x)},[y]),_=a.useMemo(()=>{const x=I.filter(w=>!o.has(w.tabKey));return Us(d.current,x)?d.current:(d.current=x,x)},[I,o]),N=a.useMemo(()=>{const x=_.map(w=>w.tabKey);return Us(m.current,x)?m.current:(m.current=x,x)},[_]);return{chatIdes:f,conversations:I,visibleConversations:_,visibleTabKeys:N,resolveConversationBySessionId:u,resolveConversationByTarget:S}}function kd({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 m=new URLSearchParams(d);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Nd({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{nt.setIdes(t)},[t]),a.useEffect(()=>{nt.setResolveAction((i,c,d)=>{s(i,c,d).catch(()=>{})})},[s]),a.useEffect(()=>{const i=nt.onToast(m=>{r(p=>p.some(g=>g.message===m.message&&m.timestamp-g.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const f=m.duration||5e3;setTimeout(()=>r(p=>p.filter(h=>h.id!==m.id)),f)}),c=nt.onSystemMessage((m,f)=>{var C,I;const p=o(m),h=(C=f._localId)==null?void 0:C.startsWith("sys_approval_"),g=!!(p&&(p.status==="waiting_approval"||(I=p.modalButtons)!=null&&I.length||p.modalMessage));h&&g||n(l=>({...l,[m]:[...l[m]||[],f]}))}),d=nt.onClearSystemMessage((m,f)=>{n(p=>{var h;return(h=p[m])!=null&&h.length?{...p,[m]:p[m].filter(g=>{var C;return!(g.role==="system"&&((C=g._localId)!=null&&C.startsWith(f)))})}:p})});return()=>{i(),c(),d()}},[r,n]),a.useEffect(()=>{const i=Ja.on("status_event",c=>{nt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=d=>{var b;const m=d.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const f=m.targetSessionId||m.targetKey||m.daemonId,p=o(f),h=(p==null?void 0:p.routeId)||m.daemonId;if(!h)return;const g=Number(m.buttonIndex),C=m.button||((b=p==null?void 0:p.modalButtons)==null?void 0:b[g])||"Approve",I=String(C).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),l=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:l?"approve":"reject",button:C,...Number.isFinite(g)&&{buttonIndex:g},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};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 Sd="adhdev_dashboardLayout_v1",Cd="adhdev_dashboardDockview_v1",gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function jo(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function ko(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function No(t){return`${Sd}:${t}`}function Id(t){const s=No(t);return jo(s,null)}function _d(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=No(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function So(t){return`${Cd}:${t}`}function Ad(t){const s=So(t);return jo(s,null)}function Md(t,s){try{const r=So(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Td(){return{groupAssignments:[...gs.groupAssignments],focusedGroup:gs.focusedGroup,groupActiveTabIds:{...gs.groupActiveTabIds},groupTabOrders:{...gs.groupTabOrders},groupSizes:[...gs.groupSizes]}}function Ld(){const[t]=a.useState(()=>ko(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[d,m]=a.useState({}),[f,p]=a.useState([]),[h,g]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,I]=a.useState(!1),l=a.useCallback(()=>{if(C)return;const b=Id(t)??Td();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),p(b.groupSizes),I(!0)},[C,t]);return a.useEffect(()=>{C&&_d(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:d,groupSizes:f})},[C,t,s,n,i,d,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=u=>g(u.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:d,setGroupTabOrders:m,groupSizes:f,setGroupSizes:p,isMobile:h,hasHydratedStoredLayout:C,hydrateStoredLayout:l}}function Pd(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 Rd({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:d,setSearchParams:m,historyModalOpen:f,activeConv:p,isRefreshingHistory:h,ides:g,handleRefreshHistory:C}){const I=a.useRef(!1),l=a.useRef(!1),b=a.useRef(null),y=a.useRef(!1);a.useEffect(()=>{if(!t||I.current||s.length===0)return;if(!o){i();return}const u=r(t);if(!u)return;const S=n.get(u.tabKey)??0;c(_=>({..._,[S]:u.tabKey})),d(S),I.current=!0,l.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(_=>{const N=new URLSearchParams(_);return N.delete("activeTab"),N},{replace:!0})},[t,s,r,n,o,i,c,d,m]),a.useEffect(()=>{if(!(l.current||o)&&s.length!==0){if(!t){i(),l.current=!0;return}if(I.current){l.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(l.current||o)&&(i(),l.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!f){y.current=!1;return}if(!p||y.current||h)return;const u=g.find(S=>S.id===p.routeId);u&&(!u.chats||u.chats.length===0||Pd(u.chats,p))&&(y.current=!0,C())},[f,p,h,g,C]),a.useEffect(()=>{if(!p)return;let u=null,S=0,_=-1,N=0;const x=()=>{u=null;const w=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(w.length===0){S<18&&(S+=1,u=requestAnimationFrame(x));return}let v=0;for(const j of w)j.scrollTop=j.scrollHeight,v+=j.scrollHeight;v===_?N+=1:(N=0,_=v),S+=1,!(N>=2||S>=18)&&(u=requestAnimationFrame(x))};return u=requestAnimationFrame(x),()=>{u!=null&&cancelAnimationFrame(u)}},[p==null?void 0:p.tabKey])}function Ed({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:d}){const[m,f]=a.useState(null),[p,h]=a.useState(null),g=a.useMemo(()=>{if(t||!n)return null;const y=d(n);return y&&!We(y)&&!$e(y)?y:null},[t,n,d]),C=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const u=m!=null&&m.tabKey?i.find(S=>S.tabKey===m.tabKey):o?i.find(S=>S.tabKey===o):null;return(u==null?void 0:u.routeId)===y?u:Rt(i,y)},[i,m,o]),I=a.useMemo(()=>{if(C)return c.find(y=>y.id===C.routeId)},[c,C]);a.useEffect(()=>{g&&(f({routeId:g.routeId,tabKey:Dn(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const l=a.useCallback(y=>{y&&(f({routeId:y.routeId,tabKey:Dn(y)}),h(y))},[]),b=a.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:I,remoteDialogActiveConv:p,setRemoteDialogActiveConv:h,openRemoteDialog:l,closeRemoteDialog:b}}function is(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:We(t)||$e(t)?{agentType:lt(t)}:t.streamSource==="agent-stream"?{agentType:lt(t)}:s}function Ts(t){return t?nr(t):""}function ys(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function _r(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 ea({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[d,m]=a.useState(!1),[f,p]=a.useState(!1),h=a.useCallback(async l=>{try{await t("standalone","launch_ide",{ideType:l,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),g=a.useCallback(async(l,b)=>{try{const y=l||(s==null?void 0:s.daemonId)||"",u=await t(y,"switch_chat",{id:b,sessionId:b,...is(s)}),S=u==null?void 0:u.result;if((u==null?void 0:u.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?ys(o,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?ys(o,`⚠️ Switch error: ${S}`):ys(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),ys(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,t,o]),C=a.useCallback(async()=>{if(!(!s||d)){m(!0);try{const l=Ts(s);await t(l,"new_chat",{...is(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(l){console.error("New chat failed",l)}finally{m(!1)}}},[s,d,t,c,i]),I=a.useCallback(async()=>{var l,b;if(!(!s||f)){p(!0);try{const y=Ts(s),u=async()=>t(y,"list_chats",{forceExpand:!0,...is(s)});let S=await u(),_=(S==null?void 0:S.chats)||((l=S==null?void 0:S.result)==null?void 0:l.chats);_r(_,s)&&(await new Promise(N=>setTimeout(N,450)),S=await u(),_=(S==null?void 0:S.chats)||((b=S==null?void 0:S.result)==null?void 0:b.chats)),S!=null&&S.success&&Array.isArray(_)&&(n(s.routeId,_),_r(_,s)&&!_r(r,s)&&ys(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,f,t,n,o]);return{isCreatingChat:d,isRefreshingHistory:f,handleLaunchIde:h,handleSwitchSession:g,handleNewChat:C,handleRefreshHistory:I}}function $d(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 Dd(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function ta(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 Hs(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,d]of t)!r.has(c)||d<=0||n.includes(d)||n.push(d);n.sort((c,d)=>c-d);const 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 m=o[d];typeof m=="number"&&m>0&&i.set(c,m)}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 Bd(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 Kd(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 ra(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 na(t){return Array(t).fill(100/t)}function Wd({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:d,visibleConversations:m,visibleTabKeys:f}){const p=a.useRef(null),h=a.useMemo(()=>Hs(t,f),[t,f]),g=h.assignments,C=a.useMemo(()=>d?1:h.groupCount,[h.groupCount,d]),I=C>1,l=a.useCallback((N,x)=>{s(w=>{const v=new Map(Hs(w,f).assignments);return x===0?v.delete(N):v.set(N,x),v}),n(w=>({...w,[x]:N})),r(x)},[s,f,n,r]),b=a.useCallback(N=>{s(x=>{const w=Hs(x,f).assignments,v=new Map;for(const[j,B]of w)B!==N&&(B>N?v.set(j,B-1):v.set(j,B));return v}),c(x=>{if(x.length<=1)return[];const w=[...x];w.splice(N,1);const v=w.reduce((j,B)=>j+B,0);return v>0?w.map(j=>j/v*100):[]}),r(0)},[s,f,c,r]),y=a.useCallback((N,x)=>{x.preventDefault();const w=p.current;if(!w)return;const v=x.clientX,j=w.offsetWidth,B=i.length===C?[...i]:na(C),E=T=>{const A=(T.clientX-v)/j*100,k=[...B];k[N]=Math.max(15,B[N]+A),k[N+1]=Math.max(15,B[N+1]-A),c(k)},W=()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",W),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",E),document.addEventListener("mouseup",W)},[i,C,c]),u=a.useCallback((N,x,w)=>{if(C>=4)return;const v=w==="left"?x:x+1;s(j=>{const B=Hs(j,f).assignments,E=new Map;for(const W of m){const T=B.get(W.tabKey)??0,G=T>=v?T+1:T;G>0&&E.set(W.tabKey,G)}return v>0&&E.set(N,v),E}),c(j=>{const B=j.length===C?[...j]:na(C),E=B[x]??100/C,W=Math.max(15,E/2),T=Math.max(15,E/2),G=[...B];G[x]=W,G.splice(v,0,T);const A=G.reduce((k,K)=>k+K,0);return G.map(k=>k/A*100)}),n(j=>{const B=ra(j,v);return B[v]=N,B}),o(j=>{const B=ra(j,v);return B[v]=[N],B}),r(v)},[C,s,f,m,c,n,o,r]);a.useEffect(()=>{$d(t,g)||s(g)},[t,g,s]),a.useEffect(()=>{const{mapping:N,usedGroups:x}=h;n(w=>{const v=sa(w,N);return ta(w,v)?w:v}),o(w=>{const v=sa(w,N);return ta(w,v)?w:v}),r(w=>{const v=d?0:Bd(w,x,N);return w===v?w:v}),c(w=>{const v=d?[]:Kd(w,x,h.groupCount);return Dd(w,v)?w:v})},[h,d,n,o,r,c]);const S=a.useMemo(()=>{const N=Array.from({length:C},()=>[]);for(const x of m){const w=g.get(x.tabKey)??0,v=Math.min(w,C-1);N[v].push(x)}return N},[m,g,C]),_=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:g,numGroups:C,isSplitMode:I,groupedConvs:S,moveTabToGroup:l,closeGroup:b,handleResizeStart:y,splitTabRelative:u,clearAllSplits:_}}function Od({ides:t,sendDaemonCommand:s}){const r="0.8.37",n=a.useMemo(()=>t.filter(f=>{if(f.type!=="adhdev-daemon")return!1;const p=f.version||f.daemonVersion||null;return!p||!r?!1:p!==r}),[r,t]),[o,i]=a.useState(!1),[c,d]=a.useState({}),m=a.useCallback(async f=>{var p,h;d(g=>({...g,[f]:"upgrading"}));try{const g=await s(f,"daemon_upgrade",{});(p=g==null?void 0:g.result)!=null&&p.upgraded||(h=g==null?void 0:g.result)!=null&&h.success?d(C=>({...C,[f]:"done"})):d(C=>({...C,[f]:"error"}))}catch{d(g=>({...g,[f]:"error"}))}},[s]);return{versionMismatchDaemons:n,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:i,upgradingDaemons:c,handleBannerUpgrade:m}}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 oa(t){const s=pn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ia(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 pr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[d,m]=a.useState(!1),f=a.useRef(!1),p=a.useRef(null),h=a.useCallback(async l=>{if(!s)return;const b=l.trim();if(!b||f.current)return;const y=s.tabKey,u=Date.now(),S=p.current;if(S&&S.tabKey===y&&S.message===b&&u-S.timestamp<2e3)return;f.current=!0,m(!0),p.current={tabKey:y,message:b,timestamp:u};const _=`${u}-${Math.random().toString(36).slice(2,8)}`,N={role:"user",content:b,timestamp:u,_localId:_},x=!(We(s)||$e(s));x&&r(w=>({...w,[y]:[...w[y]||[],N]}));try{const w=Ts(s);if(!w)return;const v=await t(w,"send_chat",{message:b,...is(s)}),j=aa(v);if(x&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r(B=>({...B,[y]:(B[y]||[]).filter(E=>E._localId!==_)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const B=Date.now()-6e4;r(E=>{const W=E[y];if(!W)return E;const T=W.filter(G=>G.timestamp>B);return T.length===W.length?E:{...E,[y]:T}})},6e4)}catch(w){const v=pn(w);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",w),x&&r(j=>({...j,[y]:(j[y]||[]).filter(B=>B._localId!==_)}))}finally{f.current=!1,m(!1)}},[s,t,r]),g=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(l){console.error("Relaunch failed",l)}},[s,t]),C=a.useCallback(async l=>{if(s)try{const y=(s.modalButtons||[]).indexOf(l),u=l.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(u),_=Ts(s);if(!_)return;const N=await t(_,"resolve_action",{button:l,action:S?"approve":"reject",...y>=0&&{buttonIndex:y},...is(s)}),x=aa(N);x.success||n(w=>[...w,{routeId:s.tabKey,text:ia(l,x==null?void 0:x.error),timestamp:Date.now()}])}catch(b){oa(b)||console.error("[ModalButton] Error:",b),n(y=>[...y,{routeId:s.tabKey,text:oa(b)?ia(l,b):`❌ **${l}** 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(l){console.error("Focus agent failed",l)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:d,isFocusingAgent:i,handleSendChat:h,handleRelaunch:g,handleModalButton:C,handleFocusAgent:I}}const fn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:d,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:l=!0}){const b=go(s),y=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(Oa,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.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(Xt,{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,y.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:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(zr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:l})})]}):e.jsx(zr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:l})]})},(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 zd({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:d,onBack:m,onOpenNativeConversation:f,onOpenMachine:p,onOpenHistory:h,onOpenRemote:g,onHideConversation:C,onStopCli:I,cliViewMode:l,onSetCliViewMode:b,handleSendChat:y,handleFocusAgent:u,handleModalButton:S,handleRelaunch:_}){const N=a.useRef(null),x=We(t)&&!s,w=x&&l==="terminal",v=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 ${v} 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:m,type:"button","aria-label":"Back",children:e.jsx(Jr,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ve(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(Va,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>p(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[x&&l&&e.jsx(on,{mode:l,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(bt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(Qr,{size:14})}),!s&&!x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(t),type:"button",children:e.jsx(ut,{size:14})}),C&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(t),type:"button",title:"Close chat",children:e.jsx(bt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(fn,{activeConv:t,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:N,handleModalButton:S,handleRelaunch:_,handleSendChat:y,isSendingChat:c,handleFocusAgent:u,isFocusingAgent:d,actionLogs:o,userName:i})})]})}const Ar={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Ud(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Co(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(Ud())},[]);const d=a.useCallback(()=>{navigator.clipboard.writeText(Ar[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:Ar[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:Ar[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 Io({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:ut},{key:"chats",label:"Chats",icon:Pt}];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 Fs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function rs({children:t,className:s=""}){return e.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:t})}function vs({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 Vs({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:m,isConnecting:f}=ms(t.conversation),p=Ve(t.conversation),h=Qt(t.conversation),g=Qa(t.conversation,{requiresAction:s==="needs_attention"}),C=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",l=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",u=c?"text-text-muted opacity-80":"text-text-muted",S="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] ${C}`,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(p)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${l}`,children:p}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${u}`,children:Wa(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${S} 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…"})]}):g==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:S,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,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 ca({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 Hd({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:d,onOpenConversation:m,onShowConversation:f,onShowAllHidden:p,onOpenNewSession:h,onOpenMachine:g,onOpenSettings:C,onSectionChange:I,wsStatus:l="connected",isStandalone:b=!1}){const y=l==="disconnected"||l==="reconnecting"||l==="offline"||l==="auth_failed",u=c.length>0,S=s.length>0||r.length>0||n.length>0||o.length>0,_=t==="machines"?"Machines":"Chats",N=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 ${N}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),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(dr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:C,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(cr,{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:y?e.jsx(vs,{icon:e.jsx(ca,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:l==="offline"?"Your device appears to be offline. Waiting for network…":l==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(vs,{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(Co,{})})}):e.jsx(rs,{children:c.map((w,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(w.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(w.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:w.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:w.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[w.unread," new"]}):w.total>0?`${w.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:w.subtitle}),w.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[w.total," chat",w.total!==1?"s":"",w.unread>0?` · ${w.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},w.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(Fs,{title:"Needs attention",className:"mb-0"}),e.jsx(rs,{children:s.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"needs_attention",getAvatarText:d,onOpenConversation:m})},w.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(Fs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(rs,{children:r.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"task_complete",getAvatarText:d,onOpenConversation:m})},w.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(Fs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(rs,{children:n.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"working",getAvatarText:d,onOpenConversation:m})},w.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(Fs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(rs,{children:o.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"earlier",getAvatarText:d,onOpenConversation:m})},w.conversation.tabKey))}):S?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?e.jsx(vs,{icon:e.jsx(ca,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):u?e.jsx(vs,{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(Pt,{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(vs,{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:p,children:"Restore all"})]}),e.jsx(rs,{className:"bg-bg-secondary/25",children:i.map((w,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(w),type:"button",children:[e.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:d(Ve(w))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Ve(w)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:Qt(w)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},w.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(Io,{section:t,onSectionChange:I})]})}function Fd(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 fr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Fd(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 Vd(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 xr(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=(m,f)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${f}`:m==="/"||m==="\\"?`${i}${f}`:`${m.replace(/[\\/]+$/,"")}${i}${f}`,d=Array.isArray(n==null?void 0:n.files)?n.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:c(o,m.name)})).sort((m,f)=>m.name.localeCompare(f.name)):[];return{path:o,directories:d}}function hr({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:d,onNavigate:m,onConfirm:f}){const[p,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const g=Vd(r),C=p.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(bt,{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:()=>{!g||o||m(g)},disabled:!g||o,children:[e.jsx(Jr,{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:p,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!C||o||(I.preventDefault(),m(C))},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:()=>{!C||o||m(C)},disabled:!C||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:()=>m(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(cs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children: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(C||r),disabled:!C&&!r||o,children:c})]})]})})}function xn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:d=!1,showArgsInput:m,argsValue:f,onArgsChange:p,showModelInput:h,modelValue:g,onModelChange:C,historyProviderNode:I,onConfirm:l,onCancel:b}){const y=n==null?void 0:n.find(u=>u.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(bt,{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:u=>i(u.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(u=>e.jsx("option",{value:u.key,children:u.label},u.key))}),(y==null?void 0:y.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),I,r.map(u=>e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:u.label}),e.jsx("div",{className:"text-sm text-text-primary break-all",children:u.value})]},`${u.label}:${u.value}`)),h&&C&&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:g||"",onChange:u=>C(u.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})]}),m&&p&&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:u=>p(u.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:l,disabled:d,children:[e.jsx(en,{size:14}),d?"Launching…":c]})]})]})})}function la(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function qt(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 m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${la(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",d=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!d&&i.push({key:`custom:${c}`,label:la(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(f=>f.key===m))return{options:i,selectedKey:m}}return d?{options:i,selectedKey:`saved:${d.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Mr(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function Gd({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var xe,M,U,ee;const c=$s(),[d,m]=a.useState(!1),f=(((xe=t.detectedIdes)==null?void 0:xe.length)||0)>0,p=a.useMemo(()=>(t.workspaces||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[t]),h=t.defaultWorkspaceId||null,[g,C]=a.useState(h||((M=p[0])==null?void 0:M.id)||""),[I,l]=a.useState(""),[b,y]=a.useState(""),[u,S]=a.useState([]),[_,N]=a.useState(!1),[x,w]=a.useState(""),[v,j]=a.useState(!1),[B,E]=a.useState(Mr(f,s.length,r.length)),W=a.useRef(null),[T,G]=a.useState(null),A=a.useRef("__home__"),[k,K]=a.useState("__home__"),[J,L]=a.useState(""),[$,z]=a.useState(""),[H,Y]=a.useState(""),[re,pe]=a.useState([]),[O,F]=a.useState(!1),[D,me]=a.useState(!1),ie=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const X=g==="__custom__"?I.trim():((U=p.find(Q=>Q.id===g))==null?void 0:U.path)||"",be=g==="__custom__"&&!!X&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ne=g!=="__custom__"&&((ee=p.find(Q=>Q.id===g))==null?void 0:ee.path)||"",le=a.useCallback(async Q=>{N(!0),w("");try{const ce=await o(Q);y(ce.path),l(ce.path),S(ce.directories)}catch(ce){w(ce instanceof Error?ce.message:"Could not load folder")}finally{N(!1)}},[o]),ae=a.useCallback(()=>{var ce,Ne;C("__custom__"),j(!0);const Q=fr(t.platform,[I.trim(),ne,(ce=p.find(Pe=>Pe.id===h))==null?void 0:ce.path,(Ne=p[0])==null?void 0:Ne.path]);le(Q)},[I,h,le,ne,t.platform,p]),de=a.useCallback(Q=>{if(Q!=null&&Q.workspaceId){C(Q.workspaceId),l("");return}if(Q!=null&&Q.workspacePath){C("__custom__"),l(Q.workspacePath);return}C(""),l("")},[]),q=a.useCallback(Q=>{if(C(Q),Q==="__custom__"){ae();return}l("")},[ae]),se=a.useCallback(Q=>{C("__custom__"),l(Q)},[]),te=a.useCallback((Q,ce)=>{W.current=ce,A.current=Q.selectedWorkspaceKey||"__home__",K(Q.selectedWorkspaceKey||"__home__"),L(Q.initialArgs||""),z(Q.initialModel||""),Y(""),pe([]),G(Q),Q.providerType&&i&&(F(!0),i(Q.providerType).then(Ne=>pe(Ne||[])).catch(Ne=>console.warn("Failed to load saved sessions",Ne)).finally(()=>F(!1)))},[i]),ge=a.useCallback(()=>{W.current&&(me(!0),W.current().finally(()=>{W.current=null,me(!1),G(null)}))},[]),fe=a.useCallback(()=>{W.current=null,G(null)},[]),R=a.useCallback(Q=>{A.current=Q,K(Q)},[]);return a.useEffect(()=>{var Q;ie.current!==t.id&&(ie.current=t.id,C(h||((Q=p[0])==null?void 0:Q.id)||"__custom__"),l(""),y(""),S([]),w(""),j(!1),E(Mr(f,s.length,r.length)))},[r.length,s.length,h,f,t.id,p]),a.useEffect(()=>{var Q;g!=="__custom__"&&(g&&p.some(ce=>ce.id===g)||C(h||((Q=p[0])==null?void 0:Q.id)||"__custom__"))},[h,g,p]),a.useEffect(()=>{B==="ide"&&f||B==="cli"&&s.length>0||B==="acp"&&r.length>0||E(Mr(f,s.length,r.length))},[B,r.length,s.length,f]),{showAllRecent:d,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:p,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:u,browseBusy:_,browseError:x,browseDialogOpen:v,activeLauncherKind:B,launchConfirm:T,launchConfirmWorkspaceKeyRef:A,launchConfirmWorkspaceKey:k,launchConfirmArgs:J,launchConfirmModel:$,launchConfirmResumeId:H,launchConfirmSavedSessions:re,launchConfirmSessionsLoading:O,launchConfirmBusy:D,resolvedWorkspacePath:X,canCreateMissingWorkspace:be,openBrowseDialog:ae,loadBrowsePath:le,handleWorkspaceChoiceChange:q,chooseCustomWorkspacePath:se,setCustomWorkspacePath:l,setBrowseDialogOpen:j,setActiveLauncherKind:E,openLaunchConfirm:te,handleConfirmLaunch:ge,closeLaunchConfirm:fe,setWorkspaceSelectionFromOption:de,setLaunchConfirmWorkspaceKeyAndSync:R,setLaunchConfirmArgs:L,setLaunchConfirmModel:z,setLaunchConfirmResumeId:Y}}function qd({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:d,isStandalone:m,section:f,showBottomNav:p,onBack:h,onSectionChange:g,onOpenConversation:C,onOpenRecent:I,onOpenMachineDetails:l,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:u,onBrowseDirectory:S,onLaunchWorkspaceProvider:_,onListSavedSessions:N}){const x=k=>k==="ide"?"IDE":k==="cli"?"CLI":"ACP",w=r.slice(0,4),v=s.slice(0,3),j=Gd({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:d,onBrowseDirectory:S,onListSavedSessions:N}),B=a.useMemo(()=>w.map(k=>({key:`recent-launch:${k.id}`,primary:k.label,secondary:`${x(k.kind)}${k.subtitle?` · ${k.subtitle}`:""}`,onClick:()=>{const{options:K,selectedKey:J}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:k.workspace});j.openLaunchConfirm({title:`Launch ${k.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:K,selectedWorkspaceKey:J,details:[{label:"Mode",value:x(k.kind)},...k.providerType?[{label:"Provider",value:k.providerType}]:[]]},async()=>{const L=K.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),await I({...k,workspace:(L==null?void 0:L.workspacePath)??null})})}})),[j,I,w]),E=a.useMemo(()=>v.map(k=>({key:`recent-chat:${k.conversation.tabKey}`,primary:Ve(k.conversation),secondary:Xc(k.conversation,{timestampLabel:k.timestamp?Wa(k.timestamp):null}),unread:k.unread,onClick:()=>C(k.conversation)})),[C,v]),W=j.showAllRecent?B:B.slice(0,4),T=B.length>0,G=E.length>0,A=m?"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 ${A} 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(Jr,{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:dt(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:[G&&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:E.map(k=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${k.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:k.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:k.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))})]}),T&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:W.map(k=>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:k.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:k.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))}),B.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(k=>!k),children:j.showAllRecent?"Show fewer":`Show ${B.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:k=>j.handleWorkspaceChoiceChange(k.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(k=>e.jsxs("option",{value:k.id,children:[k.id===j.defaultWorkspaceId?"⭐ ":"",ur(k.path,k.label)||k.path]},k.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(cs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children: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&&u(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(k=>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:K,selectedKey:J}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${k.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:K,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:k.name}]},async()=>{const L=K.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(L),y(k.type,{workspacePath:(L==null?void 0:L.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:k.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},k.type)):(j.activeLauncherKind==="cli"?n:o).map(k=>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 K=j.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:L}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${k.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${K.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:L,details:[{label:"Mode",value:K.toUpperCase()},{label:"Provider",value:k.displayName}],showArgsInput:!0,showModelInput:K==="acp",initialArgs:"",initialModel:"",providerType:k.type},async()=>{const $=J.find(z=>z.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),_(K,k.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:[k.icon?`${k.icon} `:"",k.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},k.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:()=>u(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:l,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(hr,{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:k=>{j.loadBrowsePath(k)},onConfirm:k=>{j.chooseCustomWorkspacePath(k),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(xn,{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:k=>j.setLaunchConfirmResumeId(k.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(k=>e.jsxs("option",{value:k.providerSessionId,disabled:!k.canResume,children:[k.title||k.providerSessionId," ",k.canResume?"":"(workspace missing)"]},k.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),p&&e.jsx(Io,{section:f,onSectionChange:g})]})}function _o(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 Yd(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,m,f;const o=Ms(n)?"cli":as(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Ms(n)?n.cliName||n.type:as(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:as(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(m=(d=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function Xd(t,s){const r=new Map;for(const n of s){const o=Kt(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,g)=>g.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,d=Or(n),m=o.filter(h=>h.unread||h.requiresAction).length,f=_o(n),p=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:dt(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:d,preview:c?Jc(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 Gs(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 Jd({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:d,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:C,setSelectedTabKey:I,setScreen:l,setSelectedMachineId:b,setSection:y,setMachineBackTarget:u,resetMachineAction:S}){const _=a.useRef(null),N=a.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const w=_s(x,c),v=Math.max(Date.now(),Gt(x),w.lastUpdated||0);Gs("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:Ve(x),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:Gt(x),readAt:v}),d(Kt(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,seenAt:v}).then(j=>{Gs("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:j})}).catch(j=>{Gs("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,d]);return a.useEffect(()=>{var w;if(!n){l("inbox"),I(((w=t[0])==null?void 0:w.tabKey)||null),_.current=null;return}if(i!=="chat"){_.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;_.current!==x&&(_.current=x,N(n))},[t,N,i,n,l,I]),a.useEffect(()=>{if(!m)return;const x=t.find(w=>w.tabKey===m);x&&(I(x.tabKey),l("chat"),f==null||f())},[t,f,m,l,I]),a.useEffect(()=>{if(!p)return;const x=s.find(w=>w.id===p);x&&(b(x.id),S(),y("machines"),u("inbox"),l("machine"),h==null||h())},[s,h,p,S,u,l,y,b]),a.useEffect(()=>{g&&(y(g),l("inbox"),C==null||C())},[C,g,l,y]),a.useEffect(()=>{const x=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);x.length!==0&&Gs("inbox_state",{screen:i,selectedTabKey:o,items:x.map(w=>{const v=_s(w.conversation,c);return{liveState:v,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:Ve(w.conversation),serverBucket:v.inboxBucket,computedBucket:w.inboxBucket,serverUnread:v.unread,computedUnread:w.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:Gt(w.conversation)}})})},[r,c,i,o]),{markConversationRead:N}}function Zd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function da(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qd(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function eu({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,d]=a.useState(""),[m,f]=a.useState(null),p=a.useCallback(()=>{i("idle"),d(""),f(null)},[]),h=a.useCallback(async(u,S,_)=>{var N;try{i("loading"),d(`Launching ${S}…`);const x={ideType:S,enableCdp:!0};(N=_==null?void 0:_.workspacePath)!=null&&N.trim()&&(x.workspace=_.workspacePath.trim()),await t(u,"launch_ide",x),i("done"),d(`${S} launch requested`)}catch(x){i("error"),d(x instanceof Error?x.message:"Launch IDE failed"),console.error("Launch IDE failed",x)}},[t]),g=a.useCallback(async(u,S,_)=>{if(S.trim())try{i("loading"),d(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const N=await t(u,"workspace_add",{path:S.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(N!=null&&N.success){i("done"),d(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((N==null?void 0:N.error)||"Could not save workspace")}catch(N){i("error"),d(N instanceof Error?N.message:"Could not save workspace")}},[t]),C=a.useCallback(async u=>{var S,_,N,x,w,v;try{i("loading"),d("Starting daemon upgrade…");const j=await t(u,"daemon_upgrade",{});if((S=j==null?void 0:j.result)!=null&&S.alreadyLatest){i("done"),d(`Already on v${((_=j==null?void 0:j.result)==null?void 0:_.version)||"latest"}.`);return}if((N=j==null?void 0:j.result)!=null&&N.upgraded||(x=j==null?void 0:j.result)!=null&&x.success){i("done"),d(`Upgrade to v${((w=j==null?void 0:j.result)==null?void 0:w.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((v=j==null?void 0:j.result)==null?void 0:v.error)||"Upgrade failed")}catch(j){i("error"),d(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(u,S,_,N)=>{var v,j,B;const x=Date.now(),w={machineId:u,kind:S,providerType:_,workspaceId:(N==null?void 0:N.workspaceId)||null,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:x};try{i("loading"),d(`Launching ${_}…`),f(w);const E={cliType:_};(v=N==null?void 0:N.workspacePath)!=null&&v.trim()?E.dir=N.workspacePath.trim():N!=null&&N.workspaceId&&(E.workspaceId=N.workspaceId),N!=null&&N.resumeSessionId&&(E.resumeSessionId=N.resumeSessionId),(j=N==null?void 0:N.args)!=null&&j.trim()&&(E.cliArgs=N.args.trim().split(/\s+/).filter(Boolean)),(B=N==null?void 0:N.model)!=null&&B.trim()&&(E.initialModel=N.model.trim());const W=await t(u,"launch_cli",E),T=(W==null?void 0:W.result)||W,G=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(W!=null&&W.success&&G){f(null),i("done"),d(`${_} launched`),s(`/dashboard?activeTab=${encodeURIComponent(G)}`);return}if(W!=null&&W.success){i("loading"),d(`${_} launch requested — waiting for session…`);return}f(null),i("error"),d((W==null?void 0:W.error)||(T==null?void 0:T.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(E){if(Qd(E)){i("loading"),d(`${_} launch requested — waiting for session…`);return}f(null),i("error"),d(E instanceof Error?E.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,t]),l=a.useCallback(async(u,S)=>{try{const _=await t(u,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),N=(_==null?void 0:_.result)??_;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[t]),b=a.useCallback(async(u,S)=>xr(t,u,S),[t]);a.useEffect(()=>{var N;if(!m)return;const u=da(m.workspacePath),S=r.find(x=>{var W,T,G,A;if(!x||x.type==="adhdev-daemon"||Zd(x.daemonId||x.id)!==m.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==m.kind||String(x.agentType||x.type||"")!==m.providerType)return!1;const B=String(x.providerSessionId||"");if(m.resumeSessionId&&B)return B===m.resumeSessionId;if(u){const k=da(x.workspace||x.runtimeWorkspaceLabel);return k?k===u:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((A=(G=(T=(W=x.activeChat)==null?void 0:W.messages)==null?void 0:T.at)==null?void 0:G.call(T,-1))==null?void 0:A.timestamp)||0)>=m.startedAt-5e3});if(!S)return;const _=typeof S.sessionId=="string"&&S.sessionId?S.sessionId:typeof S.instanceId=="string"&&S.instanceId?S.instanceId:(N=n.find(x=>x.routeId===S.id))==null?void 0:N.sessionId;_&&(f(null),i("done"),d(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(_)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const u=window.setTimeout(()=>{f(S=>!S||S.startedAt!==m.startedAt?S:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(u)},[m]);const y=a.useCallback(async(u,S)=>{if(S.kind==="ide"&&S.providerType){await h(u,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await I(u,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:I,handleListSavedSessions:l,handleBrowseDirectory:b,handleOpenRecent:y}}function tu({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:d,setSection:m,setMachineBackTarget:f}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=a.useCallback(y=>{const u=t.find(S=>S.routeId===y.routeId&&S.streamSource==="native");u&&(i(u.tabKey),c("chat"),n(u))},[t,n,c,i]),g=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),C=a.useCallback((y,u="inbox")=>{d(y),o(),m("machines"),f(u),c("machine")},[o,f,c,m,d]),I=a.useCallback(y=>{const u=Kt(y);u&&C(u,"chat")},[C]),l=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:h,backFromConversation:g,openMachine:C,openConversationMachine:I,backFromMachine:l,changeMachineSection:b}}function su(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function ru(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 nu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,onOpenHistory:l,onOpenRemote:b,onStopCli:y,wsStatus:u,isConnected:S,onShowHiddenConversation:_,onShowAllHiddenConversations:N,onHideConversation:x,onOpenNewSession:w}){const[v,j]=a.useState(()=>{var M;return((M=t[0])==null?void 0:M.tabKey)||null}),[B,E]=a.useState(()=>t[0]?"chat":"inbox"),[W,T]=a.useState("chats"),[G,A]=a.useState(null),[k,K]=a.useState("inbox"),J=ds(),L="0.8.37",$=a.useMemo(()=>t.find(M=>M.tabKey===v)||t[0]||null,[t,v]),z=a.useMemo(()=>$?r.find(M=>M.id===$.routeId):void 0,[r,$]),H=a.useMemo(()=>!$||$e($)||!We($)?null:ls($),[$]),Y=a.useMemo(()=>r.filter(M=>M.type==="adhdev-daemon").sort(sn),[r]),re=a.useMemo(()=>Y.find(M=>M.id===G)||null,[Y,G]),pe=a.useMemo(()=>Rs(r),[r]),O=pr({sendDaemonCommand:o,activeConv:$||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),F=eu({sendDaemonCommand:o,navigate:J,ides:r,conversations:t}),D=a.useMemo(()=>t.map(M=>{const U=B==="chat"&&($==null?void 0:$.tabKey)===M.tabKey,ee=As(M,pe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:U}),Q=Gt(M),ce=Za(M);return{conversation:M,timestamp:Q,preview:ce,unread:ee.unread,requiresAction:ee.requiresAction,isWorking:ee.isWorking,inboxBucket:ee.inboxBucket}}),[t,pe,B,$]),{markConversationRead:me}=Jd({conversations:t,machineEntries:Y,items:D,selectedConversation:$,selectedTabKey:v,screen:B,liveSessionInboxState:pe,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:E,setSelectedMachineId:A,setSection:T,setMachineBackTarget:K,resetMachineAction:F.resetMachineAction}),ie=tu({conversations:t,selectedConversation:$,machineBackTarget:k,markConversationRead:me,resetMachineAction:F.resetMachineAction,setSelectedTabKey:j,setScreen:E,setSelectedMachineId:A,setSection:T,setMachineBackTarget:K}),X=a.useMemo(()=>D.filter(M=>M.requiresAction),[D]),be=a.useMemo(()=>D.filter(M=>M.unread&&!M.requiresAction),[D]),ne=a.useMemo(()=>D.filter(M=>!M.unread&&!M.requiresAction&&M.isWorking),[D]),le=a.useMemo(()=>D.filter(M=>!M.unread&&!M.requiresAction&&!M.isWorking),[D]),ae=a.useMemo(()=>re?D.filter(M=>Kt(M.conversation)===re.id):[],[D,re]),de=a.useMemo(()=>Yd(re,r),[r,re]),q=(re==null?void 0:re.version)||null,se=!!re&&!!q&&!0&&q!==L,te=a.useMemo(()=>(re==null?void 0:re.availableProviders)||[],[re]),ge=a.useMemo(()=>te.filter(M=>M.category==="cli"&&M.installed!==!1).map(M=>({type:M.type,displayName:M.displayName||M.type,icon:M.icon})),[te]),fe=a.useMemo(()=>te.filter(M=>M.category==="acp"&&M.installed!==!1).map(M=>({type:M.type,displayName:M.displayName||M.type,icon:M.icon})),[te]),R=a.useMemo(()=>Xd(Y,D),[D,Y]),xe=a.useCallback(async M=>{re&&await F.handleOpenRecent(re.id,M)},[F,re]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&$?e.jsx(zd,{selectedConversation:$,isAcp:$e($),isStandalone:d,selectedIdeEntry:z,actionLogs:n,userName:m,isSendingChat:O.isSendingChat,isFocusingAgent:O.isFocusingAgent,handleModalButton:O.handleModalButton,handleRelaunch:O.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onHideConversation:x,onOpenHistory:l,onOpenRemote:b,onStopCli:y,cliViewMode:H,onSetCliViewMode:async M=>{if($&&H!==M)try{await o(Kt($)||$.routeId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:lt($),mode:M})}catch(U){ru(U)?console.warn("Skipped CLI view mode switch:",U instanceof Error?U.message:String(U)):console.error("Failed to switch CLI view mode:",U)}},handleSendChat:O.handleSendChat,handleFocusAgent:O.handleFocusAgent}):B==="machine"&&re?e.jsx(qd,{selectedMachineEntry:re,selectedMachineConversations:ae,selectedMachineRecentLaunches:de,cliProviders:ge,acpProviders:fe,selectedMachineNeedsUpgrade:se,appVersion:L,machineAction:F.machineAction,isStandalone:d,section:W,showBottomNav:k==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>J(`/machines/${re.id}`),onMachineUpgrade:()=>F.handleMachineUpgrade(re.id),onLaunchDetectedIde:(M,U)=>F.handleLaunchDetectedIde(re.id,M,U),onAddWorkspace:(M,U)=>F.handleAddWorkspace(re.id,M,U),onBrowseDirectory:M=>F.handleBrowseDirectory(re.id,M),onLaunchWorkspaceProvider:(M,U,ee)=>F.handleLaunchWorkspaceProvider(re.id,M,U,ee),onListSavedSessions:M=>F.handleListSavedSessions(re.id,M)}):e.jsx(Hd,{section:W,attentionItems:X,unreadItems:be,workingItems:ne,completedItems:le,hiddenConversations:s,machineCards:R,getAvatarText:su,onOpenConversation:ie.openConversation,onShowConversation:_,onShowAllHidden:N,onOpenNewSession:w,onOpenMachine:ie.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:T,wsStatus:u,isConnected:S,isStandalone:d})})}function Tr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function au({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[d,m]=a.useState(!1),[f,p]=a.useState(null),h=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),C=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Tr(s,r)){p("merge");return}const y=b.currentTarget.getBoundingClientRect(),u=b.clientX-y.left,S=y.width/3;u<S?p("split-left"):u>S*2?p("split-right"):p("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),l=a.useCallback(b=>{c.current=0,m(!1);const y=b.dataTransfer.getData("text/tab-key"),u=y?t.some(_=>_.tabKey===y):!1,S=f;if(p(null),i(),!!y){if(b.preventDefault(),S==="split-left"&&Tr(s,r)){r==null||r(y,"split-left");return}if(S==="split-right"&&Tr(s,r)){r==null||r(y,"split-right");return}if(u){o(y);return}n==null||n(y)}},[t,f,s,r,n,o,i]);return{dragOver:d,dropAction:f,resetDragState:h,handleDragEnter:g,handleDragOver:C,handleDragLeave:I,handleDrop:l}}function ou(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 iu({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[d,m]=a.useState(r??[]),[f,p]=a.useState(null),h=a.useRef(null),g=a.useRef(null),C=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{C.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(w=>{const v=ou(w,t);return v.length===w.length&&v.every((j,B)=>j===w[B])?w:v})},[t]);const l=a.useMemo(()=>{const w=f??d;if(w.length===0)return t;const v=new Map(w.map((j,B)=>[j,B]));return[...t].sort((j,B)=>{const E=v.get(j.tabKey)??999,W=v.get(B.tabKey)??999;return E-W})},[t,f,d]);a.useEffect(()=>{var v,j;if(l.length===0){i!==null&&(c(null),(v=C.current)==null||v.call(C,null));return}if(i&&l.some(B=>B.tabKey===i))return;const w=l[0].tabKey;w!==i&&(c(w),(j=C.current)==null||j.call(C,w))},[l,i]);const b=a.useMemo(()=>l.find(w=>w.tabKey===i),[l,i]),y=a.useCallback(w=>{var v;c(w),(v=C.current)==null||v.call(C,w)},[]),u=a.useCallback((w,v,j)=>{m(B=>{var G;const E=B.filter(A=>A!==w),W=E.indexOf(v);if(W<0)return B;const T=j==="left"?W:W+1;return E.splice(T,0,w),(G=I.current)==null||G.call(I,E),E}),p(null)},[]),S=a.useCallback((w,v,j)=>{const E=(d.length>0?d:t.map(G=>G.tabKey)).filter(G=>G!==w),W=E.indexOf(v);if(W<0)return;const T=j==="left"?W:W+1;E.splice(T,0,w),h.current=E,p(E)},[d,t]),_=a.useCallback(()=>{var v;const w=h.current;w&&(m(w),(v=I.current)==null||v.call(I,w))},[]),N=a.useCallback(()=>{h.current=null,p(null)},[]),x=a.useCallback(w=>{m(v=>{var B;const j=v.filter(E=>E!==w);return j.push(w),(B=I.current)==null||B.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:l,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:u,updatePreviewOrder:S,commitPreviewOrder:_,clearPreviewOrder:N,moveTabToEnd:x,setDraggingTabKey:w=>{g.current=w}}}function cu({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 hn({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",m=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:m}),c&&e.jsx(Co,{}),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(Ea,{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 Ao="adhdev-tab-shortcuts";function lu(){try{return JSON.parse(localStorage.getItem(Ao)||"{}")}catch{return{}}}function Mo({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>lu()),[d,m]=a.useState(null),f=a.useCallback(h=>{const g=[];return h.metaKey&&g.push(o?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(o?"⌥":"Alt"),h.shiftKey&&g.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[o]),p=a.useCallback(h=>{c(h);try{localStorage.setItem(Ao,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!d)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){m(null);return}const C=f(g);if(!C)return;const I={...i};for(const[l,b]of Object.entries(I))b===C&&delete I[l];I[d]=C,p(I),m(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,d,i,p,f]),a.useEffect(()=>{if(!t)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[C,I]of Object.entries(i))if(s.includes(C)&&f(g)===I){g.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:d,setShortcutListening:m,saveShortcuts:p}}const du=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:d,onFocus:m,onSelectTab:f,onConversationActivated:p,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:C,onClearPreviewOrder:I,onDragStateReset:l,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:u,longPressTimer:S,isGroupActive:_}){const N=ms(s),x=N.isGenerating?"agent-tab-generating":N.isWaiting?"agent-tab-waiting":"",w=N.isReconnecting,v=a.useCallback(K=>{d.current=s.tabKey,b(s.tabKey),K.dataTransfer.setData("text/tab-key",s.tabKey),K.dataTransfer.effectAllowed="move"},[s.tabKey,d,b]),j=a.useCallback(()=>{d.current=null,b(null),C(),I(),l()},[d,b,C,I,l]),B=a.useCallback(K=>{const J=d.current;if(!(!J||J===s.tabKey)&&K.dataTransfer.types.includes("text/tab-key")){K.preventDefault(),K.stopPropagation();const L=K.currentTarget.getBoundingClientRect(),$=K.clientX<L.left+L.width/2?"left":"right";h(J,s.tabKey,$)}},[s.tabKey,d,h]),E=a.useCallback(K=>{K.preventDefault(),K.stopPropagation();const J=K.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const L=K.currentTarget.getBoundingClientRect(),$=K.clientX<L.left+L.width/2?"left":"right";c.includes(J)?g(J,s.tabKey,$):y&&y(J)}I()},[s.tabKey,c,g,y,I]),W=a.useCallback(K=>{K.stopPropagation(),m(),f(s.tabKey),p(s)},[s,p,m,f]),T=a.useCallback(K=>{K.preventDefault(),u(K.clientX,K.clientY,s.tabKey)},[s.tabKey,u]),G=a.useCallback(K=>{const J=K.touches[0];S.current=setTimeout(()=>{u(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,S,u]),A=a.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),k=["adhdev-dockview-tab",x,r&&"is-active",_&&"is-group-active",w&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:k,draggable:!0,onDragStart:v,onDragEnd:j,onDragOver:B,onDrop:E,onClick:W,onContextMenu:T,onTouchStart:G,onTouchEnd:A,onTouchMove:A,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:N.isGenerating?e.jsx("div",{className:"tab-spinner"}):N.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):N.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Ve(s),children:Ve(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(s)}):N.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[os(s),e.jsx("span",{className:"connecting-dots"})]}):os(s)})]}),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 uu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:C,onReceiveTab:I,onHideTab:l,isGroupActive:b,allowTabShortcuts:y=!0}){const[u,S]=a.useState(null),_=a.useRef(null),N=a.useRef(null),x=a.useMemo(()=>t.map(T=>T.tabKey),[t]);Ps("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(u==null?void 0:u.tabKey)||null});const{isMac:w,tabShortcuts:v,shortcutListening:j,setShortcutListening:B,saveShortcuts:E}=Mo({enabled:y,sortedTabKeys:t.map(T=>T.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!u)return;const T=G=>{const A=document.querySelector("[data-pane-context-menu]");A&&A.contains(G.target)||S(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[u]),a.useEffect(()=>{const T=N.current;if(!T)return;const G=A=>{Math.abs(A.deltaY)>Math.abs(A.deltaX)&&(A.preventDefault(),T.scrollLeft+=A.deltaY)};return T.addEventListener("wheel",G,{passive:!1}),()=>T.removeEventListener("wheel",G)},[]);const W=a.useCallback((T,G,A)=>{S({x:T,y:G,tabKey:A})},[]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:e.jsxs("div",{ref:N,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(T=>e.jsx(du,{conv:T,isActive:s===T.tabKey,isDraggedTab:o.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:y?v[T.tabKey]:void 0,conversationKeys:x,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:C,onReceiveTab:I,onOpenContextMenu:W,longPressTimer:_,isGroupActive:b},T.tabKey)),t.length===0&&e.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),u&&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:u.x,top:u.y},children:[y&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:T=>{T.stopPropagation(),B(u.tabKey),S(null)},children:["⌨ ",v[u.tabKey]?`Change shortcut (${v[u.tabKey]})`:"Set shortcut"]}),v[u.tabKey]&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const T={...v};delete T[u.tabKey],E(T),S(null)},children:"✕ Remove shortcut"})]}),l&&e.jsxs(e.Fragment,{children:[y&&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:()=>{l(u.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&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:()=>B(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",w?"⌘+1":"Ctrl+1",", ",w?"⌥+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 mu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:p,onFocus:h,isSplitMode:g,numGroups:C,onMoveTab:I,onReceiveTab:l,style:b,detectedIdes:y,handleLaunchIde:u,onActiveTabChange:S,initialActiveTabId:_,initialTabOrder:N,onTabOrderChange:x,onHideTab:w,isFocused:v,allowTabShortcuts:j=!0}){const{sendCommand:B}=mt(),E=a.useRef(null),{activeTabId:W,activeConv:T,sortedConversations:G,draggingTabRef:A,selectTab:k,handleTabReorder:K,updatePreviewOrder:J,commitPreviewOrder:L,clearPreviewOrder:$,moveTabToEnd:z,setDraggingTabKey:H}=iu({conversations:t,initialActiveTabId:_,initialTabOrder:N,onActiveTabChange:S,onTabOrderChange:x}),Y=pr({sendDaemonCommand:o,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:d}),{dragOver:re,dropAction:pe,resetDragState:O,handleDragEnter:F,handleDragOver:D,handleDragLeave:me,handleDrop:ie}=au({conversations:t,numGroups:C,onMoveTab:I,onReceiveTab:l,onOwnTabDrop:z,onClearPreviewOrder:$}),X=T&&!$e(T)&&ls(T)==="terminal",be=a.useMemo(()=>T?s.find(q=>q.id===T.routeId):void 0,[s,T]),ne=a.useMemo(()=>T?n.filter(q=>q.routeId===T.tabKey):[],[n,T]),le=a.useMemo(()=>Rs(s),[s]),ae=a.useMemo(()=>new Set(G.filter(q=>uc(q,le,{isOpenConversation:q.tabKey===W})).map(q=>q.tabKey)),[W,le,G]);Ps("PaneGroup",{groupIndex:p,conversationCount:t.length,activeTabId:W,dragOver:re});const de=a.useCallback(q=>{q.streamSource==="agent-stream"&&q.agentType&&B(q.routeId,"focus_session",{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})},[B]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(uu,{conversations:G,activeTabId:W,groupIndex:p,numGroups:C,unreadTabKeys:ae,draggingTabRef:A,onFocus:h,onSelectTab:k,onConversationActivated:de,onPreviewReorder:J,onReorderTab:K,onCommitPreviewOrder:L,onClearPreviewOrder:$,onDragStateReset:O,onDragTabKeyChange:H,onMoveTab:I,onReceiveTab:l,onHideTab:w,isGroupActive:v??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:F,onDragOver:D,onDragLeave:me,onDrop:ie,children:[re&&e.jsx(cu,{dropAction:pe,canSplit:!!(C<4&&I)}),T?e.jsx(fn,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!X,ideEntry:be,terminalRef:E,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ne,userName:f,isInputActive:!g||!!v}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(hn,{conversationsCount:t.length,isSplitMode:g,isStandalone:d,hasRegisteredMachines:m,detectedIdes:y,handleLaunchIde:u})})]})]})}function pu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:C,focusedGroup:I,setFocusedGroup:l,moveTabToGroup:b,splitTabRelative:y,closeGroup:u,handleResizeStart:S,detectedIdes:_,handleLaunchIde:N,groupActiveTabIds:x,setGroupActiveTabIds:w,groupTabOrders:v,setGroupTabOrders:j,toggleHiddenTab:B,allowTabShortcuts:E=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((W,T)=>{const G=s&&n.length===r?`${n[T]}%`:void 0;return e.jsxs(Ge.Fragment,{children:[s&&T>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:A=>S(T-1,A),onDoubleClick:()=>u(T),title:"Drag to resize · Double-click to merge",children:e.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),e.jsx(mu,{style:s?{flexBasis:G??`${100/r}%`,flexGrow:G?0:1,flexShrink:G?0:1}:void 0,conversations:W,clearedTabs:i,ides:c,actionLogs:d,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:C,groupIndex:T,isFocused:s&&I===T,onFocus:()=>l(T),isSplitMode:s,numGroups:r,onMoveTab:(A,k)=>{k==="left"&&T>0?b(A,T-1):k==="right"&&T<r-1?b(A,T+1):k==="split-left"&&r<4?y(A,T,"left"):k==="split-right"&&r<4&&y(A,T,"right")},onReceiveTab:A=>b(A,T),detectedIdes:T===0?_:void 0,handleLaunchIde:T===0?N:void 0,onActiveTabChange:A=>w(k=>(k[T]??null)===(A??null)?k:{...k,[T]:A}),initialActiveTabId:x[T],initialTabOrder:v[T],onTabOrderChange:A=>j(k=>{const K=k[T]||[];return K.length===A.length&&K.every((J,L)=>J===A[L])?k:{...k,[T]:A}}),onHideTab:B,allowTabShortcuts:E})]},T)})})}function To({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,d]=a.useState(null);a.useEffect(()=>t?Fe.onScreenshot("ide-page",(p,h)=>{if(p!==t)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return t?((p=Fe.onStatus)==null?void 0:p.call(Fe,(h,g)=>{h===t&&g!=null&&g.screenshotUsage&&d(g.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const f=t?Fe.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 m=a.useCallback(async(f,p)=>{const h=t?Fe.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,p,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Lo=a.createContext(null);function br(){const t=a.useContext(Lo);if(!t)throw new Error("DashboardDockviewContext missing");return t}function er(t){return Ve(t)||t.tabKey}function fu(t){return`remote:${t}`}function Ls(t){return t.startsWith("remote:")}function xu(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 hu(t,s,r){var d;const n=[s];let o;for(const m of n){let f;for(const p of m){const h=t.addPanel({id:p.tabKey,component:"conversation",title:er(p),params:{kind:"conversation",tabKey:p.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 ua(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Ls(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!==er(n)&&o.api.setTitle(er(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:er(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 ma(t,s,r){var m,f;const n=r?fu(r):null;for(const p of[...t.panels])Ls(p.id)&&(!n||p.id!==n)&&t.removePanel(p);if(!r||!n)return;const o=Rt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=el(o);if(i){i.title!==c&&i.api.setTitle(c);return}const d=(o==null?void 0:o.tabKey)??((m=t.activePanel)==null?void 0:m.id)??((f=t.panels.find(p=>!Ls(p.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 bu({params:t,api:s}){var h;const r=br(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),d=pr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(C=>i(C.isActive)),s.onDidActiveGroupChange(C=>{if(!s.isActive&&!C.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const C of g)C.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(g=>g.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(hn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const p=!$e(c)&&ls(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(fn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,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 gu({params:t}){var m;const s=br(),r=a.useMemo(()=>Rt([...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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:d}=To({doId:o,targetSessionId:r?an(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(Ba,{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 yu(){const t=br();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(hn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function vu(t){var C,I;xu(t);const s=br(),r=a.useCallback(l=>{"button"in l&&l.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const l=Rt([...s.conversationsByTabKey.values()],t.params.routeId),b=((C=t.api.group.activePanel)==null?void 0:C.id)===t.api.id,y=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(l==null?void 0:l.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:l!=null&&l.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:l.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=As(n,s.liveSessionInboxState,{isOpenConversation:o}),d=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,p=c.isWaiting,h=c.unread,g=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${d?" is-reconnecting":""}`,title:Ve(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:l=>{l.preventDefault(),r(l),s.openTabContextMenu({x:l.clientX,y:l.clientY,tabKey:n.tabKey})},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"}):p?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:"○"}):m?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:Ve(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:d?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(n)}):m?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:os(n)}):e.jsx("span",{children:os(n)})})]}),g&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function wu({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:f,userName:p,detectedIdes:h,handleLaunchIde:g,toggleHiddenTab:C,registerActionHandlers:I,onActiveTabChange:l,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:u,scrollToBottomRequest:S}){const{theme:_}=un(),{sendCommand:N}=mt(),x=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(!1),B=a.useRef(!1),E=a.useRef(null),[W,T]=a.useState(null),[G,A]=a.useState(!1),[k,K]=a.useState(!1),J=a.useRef(null),L=a.useMemo(()=>ko(typeof window<"u"?window.innerWidth:1280),[]),$=a.useMemo(()=>new Map(t.map(M=>[M.tabKey,M])),[t]),z=a.useMemo(()=>Rs(r),[r]),H=a.useCallback(()=>{var M;(M=x.current)==null||M.focus()},[]),Y=a.useCallback(M=>{const U=x.current;if(!U)return;const ee=U.getPanel(M);ee&&(ee.group.model.openPanel(ee),ee.api.setActive())},[]),re=a.useCallback(M=>{const U=x.current,ee=U==null?void 0:U.activePanel,Q=(U==null?void 0:U.activeGroup)||(ee==null?void 0:ee.group);if(!U||!ee||!Q)return;const ce=Q.panels||[];if(ce.length<=1)return;const Ne=ce.findIndex(Re=>Re.id===ee.id);if(Ne<0)return;const Pe=(Ne+M+ce.length)%ce.length,De=ce[Pe];De&&(De.group.model.openPanel(De),De.api.setActive())},[]),pe=a.useCallback(M=>{var et;const U=x.current,ee=(U==null?void 0:U.activeGroup)||((et=U==null?void 0:U.activePanel)==null?void 0:et.group);if(!U||!ee)return;const Q=U.groups||[],ce=Q.find(Ke=>Ke.id===ee.id);if(!ce)return;const Ne=ce.element.getBoundingClientRect(),Pe=Ne.left+Ne.width/2,De=Ne.top+Ne.height/2,Re=(Ke,Ce,Ue,Ye)=>Math.max(0,Math.min(Ce,Ye)-Math.max(Ke,Ue)),ot=Ke=>{const Ce=Ke.element.getBoundingClientRect(),Ue=Ce.left+Ce.width/2,Ye=Ce.top+Ce.height/2;let Xe=0,V=0,je=0,Se=!1;if(M==="left"?(Se=Ue<Pe,Xe=Math.max(0,Ne.left-Ce.right),V=Math.abs(Ye-De),je=Re(Ne.top,Ne.bottom,Ce.top,Ce.bottom)):M==="right"?(Se=Ue>Pe,Xe=Math.max(0,Ce.left-Ne.right),V=Math.abs(Ye-De),je=Re(Ne.top,Ne.bottom,Ce.top,Ce.bottom)):M==="above"?(Se=Ye<De,Xe=Math.max(0,Ne.top-Ce.bottom),V=Math.abs(Ue-Pe),je=Re(Ne.left,Ne.right,Ce.left,Ce.right)):(Se=Ye>De,Xe=Math.max(0,Ce.top-Ne.bottom),V=Math.abs(Ue-Pe),je=Re(Ne.left,Ne.right,Ce.left,Ce.right)),!Se)return Number.POSITIVE_INFINITY;const Te=je>0?0:120;return Xe*3+V+Te};let Qe=null,ze=Number.POSITIVE_INFINITY;for(const Ke of Q){if(Ke.id===ce.id)continue;const Ce=ot(Ke);Number.isFinite(Ce)&&(Ce>=ze||(ze=Ce,Qe=Ke))}return Qe||void 0},[]),O=a.useCallback(M=>{const U=pe(M);if(!U)return;const ee=U.activePanel||U.panels[0];ee&&(U.model.openPanel(ee),ee.api.setActive())},[pe]),F=a.useCallback((M,U)=>{const ee=x.current,Q=ee==null?void 0:ee.activePanel,ce=(ee==null?void 0:ee.activeGroup)||(Q==null?void 0:Q.group);if(!ee||!Q||!ce)return;let Ne=pe(M);!Ne&&(U!=null&&U.createGroupIfMissing)&&(Ne=ee.addGroup({referenceGroup:ce,direction:M})),Ne&&(Q.api.moveTo({group:Ne,position:"center"}),Q.group.model.openPanel(Q),Q.api.setActive())},[pe]),{isMac:D,tabShortcuts:me,shortcutListening:ie,setShortcutListening:X,saveShortcuts:be}=Mo({sortedTabKeys:t.map(M=>M.tabKey),onFocus:H,onSelectTab:Y}),ne=a.useCallback(()=>{var ee;const M=x.current;if(!M)return;const U=M.activePanel;if(U){if(Ls(U.id)){const Q=((ee=U.params)==null?void 0:ee.routeId)||U.id.slice(7),ce=Rt(t,Q);ce!=null&&ce.tabKey&&X(ce.tabKey);return}$.has(U.id)&&X(U.id)}},[$,X,t]);a.useEffect(()=>(I==null||I({setShortcutForActiveTab:ne,activatePreviousTabInGroup:()=>re(-1),activateNextTabInGroup:()=>re(1),splitActiveTabRight:()=>F("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>F("below",{createGroupIfMissing:!0}),focusLeftPane:()=>O("left"),focusRightPane:()=>O("right"),focusUpPane:()=>O("above"),focusDownPane:()=>O("below"),moveActiveTabToLeftPane:()=>F("left"),moveActiveTabToRightPane:()=>F("right"),moveActiveTabToUpPane:()=>F("above"),moveActiveTabToDownPane:()=>F("below")}),()=>I==null?void 0:I(null)),[re,O,F,I,ne]),a.useEffect(()=>{if(!W)return;const M=U=>{const ee=document.querySelector("[data-dockview-tab-context-menu]");ee&&ee.contains(U.target)||T(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[W]);const le=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:$,detectedIdes:h,handleLaunchIde:g,ides:r,isStandalone:d,hasRegisteredMachines:m,liveSessionInboxState:z,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:C,userName:p,scrollToBottomRequest:S,tabShortcuts:me,openTabContextMenu:({x:M,y:U,tabKey:ee})=>T({x:M,y:U,tabKey:ee})}),[n,s,$,h,g,r,d,m,z,o,c,i,C,p,S,me]),ae=a.useCallback(M=>{if(!M)return!1;const U=x.current;if(!U)return!1;const ee=U.getPanel(M);return ee?(ee.group.model.openPanel(ee),ee.api.setActive(),u==null||u(),!0):!1},[u]),de=a.useCallback(()=>{if(B.current)return!1;const M=ae(E.current);return M&&(B.current=!0),M},[ae]),q=a.useCallback(()=>{var U;const M=x.current;M&&Md(L,{activeTabId:((U=M.activePanel)==null?void 0:U.id)??null,layout:M.toJSON()})},[L]),se=a.useCallback(()=>{const M=w.current;if(!M)return;const U=M.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const ee of U)ee.setAttribute("data-adhdev-force-hidden","true")},[]),te=a.useCallback(()=>{const M=w.current;if(!M)return;const U=M.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const ee of U)ee.removeAttribute("data-adhdev-force-hidden")},[]),ge=a.useCallback(()=>{const M=w.current;if(!M)return;const U=M.querySelectorAll(".dv-drop-target-container");for(const ce of U)ce.remove();const ee=M.querySelectorAll(".dv-drop-target-dropzone");for(const ce of ee)ce.remove();const Q=M.querySelectorAll(".dv-drop-target");for(const ce of Q)ce.classList.remove("dv-drop-target")},[]),fe=a.useCallback(()=>{A(!1),K(!1),te(),se(),ge(),!(typeof window>"u")&&(J.current!=null&&window.clearTimeout(J.current),window.requestAnimationFrame(()=>{se(),ge()}),J.current=window.setTimeout(()=>{se(),ge(),J.current=null},80))},[te,se,ge]),R=a.useCallback(M=>{var ee;x.current=M.api;const U=Ad(L);E.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&M.api.fromJSON(U.layout,{reuseExistingPanels:!1}),j.current=!!(U!=null&&U.layout)&&!f&&t.length===0,j.current||(ua(M.api,t),ma(M.api,t,y)),M.api.totalPanels===0&&t.length>0?hu(M.api,t,b):!j.current&&!ae(b)&&de(),v.current=!0,M.api.onDidActivePanelChange(Q=>{var Ne;if(E.current=(Q==null?void 0:Q.id)??null,B.current=!0,Q&&Ls(Q.id)){const Pe=((Ne=Q.params)==null?void 0:Ne.routeId)||Q.id.slice(7),De=Rt(t,Pe);l((De==null?void 0:De.tabKey)??null),q();return}if(l((Q==null?void 0:Q.id)??null),q(),!Q)return;const ce=$.get(Q.id);(ce==null?void 0:ce.streamSource)==="agent-stream"&&ce.agentType&&N(ce.routeId,"focus_session",{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})}),M.api.onDidLayoutChange(()=>{q()}),M.api.onWillDragPanel(()=>{A(!0),K(!1),se()}),M.api.onWillDragGroup(()=>{A(!0),K(!1),se()}),M.api.onWillShowOverlay(()=>{te(),K(!0)}),M.api.onDidMovePanel(fe),M.api.onDidDrop(fe),l(((ee=M.api.activePanel)==null?void 0:ee.id)??null)},[ae,fe,te,$,f,L,se,ge,l,q,b,y,N,t]);a.useEffect(()=>{const M=x.current;if(!M||!v.current||j.current&&!f||(j.current&&(j.current=!1),ua(M,t),ma(M,t,y),b&&ae(b)))return;!M.activePanel&&M.panels[0]&&(M.panels[0].group.model.openPanel(M.panels[0]),M.panels[0].api.setActive()),!!(M.activePanel&&M.getPanel(M.activePanel.id))||de()},[ae,de,f,b,y,t]),a.useEffect(()=>{v.current&&ae(b)},[ae,b]),a.useEffect(()=>{if(!G||typeof window>"u")return;const M=()=>fe();return window.addEventListener("pointerup",M),window.addEventListener("mouseup",M),window.addEventListener("dragend",M),()=>{window.removeEventListener("pointerup",M),window.removeEventListener("mouseup",M),window.removeEventListener("dragend",M)}},[fe,G]),a.useEffect(()=>()=>{typeof window>"u"||J.current!=null&&window.clearTimeout(J.current)},[]),a.useEffect(()=>{const M=U=>{const ee=U.target;if(!ee)return;const Q=ee.querySelector("[data-tab-key]")||ee.closest("[data-tab-key]");if(Q){const ce=Q.getAttribute("data-tab-key");ce&&U.dataTransfer&&U.dataTransfer.setData("text/tab-key",ce)}};return window.addEventListener("dragstart",M),()=>window.removeEventListener("dragstart",M)},[]);const xe=_==="light"?xi:hi;return e.jsxs(Lo.Provider,{value:le,children:[e.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(fi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${G?" is-dragging-dockview":""}${k?" is-showing-dockview-overlay":""}`,components:{conversation:bu,remote:gu},defaultTabComponent:vu,watermarkComponent:yu,onReady:R,singleTabMode:"default",tabAnimation:"smooth",theme:xe})}),W&&e.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:W.x,top:W.y},children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors",onClick:M=>{M.stopPropagation(),X(W.tabKey),T(null)},children:["⌨ ",me[W.tabKey]?`Change shortcut (${me[W.tabKey]})`:"Set shortcut"]}),me[W.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 M={...me};delete M[W.tabKey],be(M),T(null)},children:"✕ Remove shortcut"})]}),ie&&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:()=>X(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.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. ",D?"⌘+1":"Ctrl+1",", ",D?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}const Po="adhdev-recent-launch-args-v1",ju=8;function ku(t){return String(t||"").trim().replace(/\s+/g," ")}function Ro(t,s){return`${t.trim()}::${s.trim()}`}function Eo(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(Po)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Nu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Po,JSON.stringify(t))}catch{}}function $o(t,s){var i;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Eo().byKey[Ro(r,n)])==null?void 0:i.items)||[]}function Do(t,s,r){var p;const n=String(t||"").trim(),o=String(s||"").trim(),i=ku(r);if(!n||!o||!i)return;const c=Eo(),d=Ro(n,o),m=((p=c.byKey[d])==null?void 0:p.items)||[],f=[i,...m.filter(h=>h!==i)].slice(0,ju);c.byKey[d]={items:f},Nu(c)}function Lr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Su(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function pa(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function fa(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 Cu(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Iu(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 _u(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 Au(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 Mu({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var G;const[d,m]=a.useState(n||((G=t[0])==null?void 0:G.id)||null),[f,p]=a.useState(""),[h,g]=a.useState(null),[C,I]=a.useState(!1);a.useEffect(()=>{var A;m(n||((A=t[0])==null?void 0:A.id)||null)},[n,t]);const l=a.useMemo(()=>t.find(A=>A.id===d)||t[0]||null,[d,t]),b=a.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const k=Su(A.daemonId||A.id);return!!(l!=null&&l.id)&&k===l.id}),[l==null?void 0:l.id,r]),y=bo(l==null?void 0:l.id,{enabled:!!(l!=null&&l.id),includeSessions:!0,limit:6,intervalMs:1e4}),u=y.diagnostics,S=y.loading,_=y.applyDiagnostics,N=a.useMemo(()=>{const A=new Map;for(const k of b){const K=s.find(J=>J.sessionId===k.sessionId||J.routeId===k.id);k.sessionId&&K&&A.set(k.sessionId,K)}return A},[b,s]),x=a.useCallback(async()=>{if(l!=null&&l.id){I(!0);try{const A=await o(l.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),k=Lr(A);if(!(k!=null&&k.success))throw new Error((k==null?void 0:k.error)||"Could not load session host diagnostics");_(k.diagnostics||k.result||null),p("")}catch(A){const k=A instanceof Error?A.message:"Could not load session host diagnostics";p(k)}finally{I(!1)}}},[l==null?void 0:l.id,_,o]),w=a.useCallback(async(A,k)=>{if(!(l!=null&&l.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${k.displayName}?
|
|
41
|
-
This will terminate the hosted runtime.`))return;const K=`${
|
|
42
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){g("session_host_prune_duplicate_sessions");try{const k=await o(l.id,"session_host_prune_duplicate_sessions",{}),K=Lr(k);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Duplicate prune failed");const J=K.result||{},L=Array.isArray(J.prunedSessionIds)?J.prunedSessionIds.length:0,$=typeof J.duplicateGroupCount=="number"?J.duplicateGroupCount:0;nt.showToast(`Pruned ${L} duplicate runtime(s) across ${$} group(s)`,"success"),await x()}catch(k){const K=k instanceof Error?k.message:"Duplicate prune failed";p(K),nt.showToast(K,"warning")}finally{g(k=>k==="session_host_prune_duplicate_sessions"?null:k)}}},[l==null?void 0:l.id,x,o]),j=a.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((A,k)=>(k.lastActivityAt||0)-(A.lastActivityAt||0)),[u==null?void 0:u.sessions]),B=a.useMemo(()=>Au(j),[j]),E=a.useMemo(()=>j.reduce((A,k)=>{var K;return A+(((K=k.attachedClients)==null?void 0:K.length)||0)},0),[j]),W=a.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[u==null?void 0:u.recentLogs]),T=a.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-3).reverse(),[u==null?void 0:u.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:A=>A.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(Bt,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(l==null?void 0:l.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:S||C,"aria-label":"Refresh session host",children:e.jsx(us,{size:16})}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close session host",children:e.jsx(bt,{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(A=>e.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${A.id===(l==null?void 0:l.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>m(A.id),children:A.label},A.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&&!u&&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(Xt,{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})]})]})}),u&&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:u.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:E})]}),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:fa(u.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:pa(u.hostStartedAt)})]})]}),W&&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(Xt,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:W.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(lr,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:h==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:h==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),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(A=>{var Y,re;const k=N.get(A.sessionId),K=b.find(pe=>pe.sessionId===A.sessionId),J=h===`session_host_resume_session:${A.sessionId}`,L=h===`session_host_restart_session:${A.sessionId}`,$=h===`session_host_stop_session:${A.sessionId}`,z=Iu(A.meta),H=typeof((Y=A.meta)==null?void 0:Y.runtimeRecoveryError)=="string"?String(A.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:A.displayName||(K==null?void 0:K.runtimeDisplayName)||(K==null?void 0:K.cliName)||A.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${_u(A.lifecycle)}`,children:A.lifecycle}),z&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:z})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(K==null?void 0:K.runtimeWorkspaceLabel)||A.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:A.runtimeKey}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsx("span",{className:((re=A.writeOwner)==null?void 0:re.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Cu(A.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(Zr,{size:11})," ",A.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",fa(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:""]}),H&&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:H})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[k&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(k),c()},children:"Open chat"}),(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{w("session_host_resume_session",A)},children:J?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{w("session_host_restart_session",A)},children:L?"Restarting…":"Restart"}),(A.lifecycle==="running"||A.lifecycle==="starting"||A.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:()=>{w("session_host_stop_session",A)},children:$?"Stopping…":"Stop"})]})]},A.sessionId)})}),T.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:T.map(A=>{const k=j.find(K=>K.sessionId===A.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:(k==null?void 0:k.displayName)||A.sessionId}),e.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),e.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:pa(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Pr(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 qs(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Tu({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:d,onListSavedSessions:m,sendDaemonCommand:f,onOpenConversation:p}){var Ye,Xe;const h=$s(),g=a.useMemo(()=>[...t].sort(sn),[t]),[C,I]=a.useState(((Ye=g[0])==null?void 0:Ye.id)||""),l=a.useMemo(()=>g.find(V=>V.id===C)||g[0],[C,g]),b=a.useMemo(()=>((l==null?void 0:l.workspaces)||[]).map(V=>({id:V.id,path:V.path,label:V.label})),[l]),y=(l==null?void 0:l.defaultWorkspaceId)||null,[u,S]=a.useState(""),[_,N]=a.useState(""),[x,w]=a.useState(Pr(g[0])),[v,j]=a.useState(""),[B,E]=a.useState(""),[W,T]=a.useState([]),[G,A]=a.useState(""),[k,K]=a.useState([]),[J,L]=a.useState(!1),[$,z]=a.useState(""),[H,Y]=a.useState(!1),[re,pe]=a.useState(!1),[O,F]=a.useState(null),[D,me]=a.useState(!1),[ie,X]=a.useState(""),[be,ne]=a.useState(!1),[le,ae]=a.useState(""),[de,q]=a.useState([]),[se,te]=a.useState(!1),[ge,fe]=a.useState(""),[R,xe]=a.useState(!1),M=a.useRef(null),U=a.useRef(0);a.useEffect(()=>{var V;!C&&((V=g[0])!=null&&V.id)&&I(g[0].id)},[C,g]),a.useEffect(()=>{!l||!(!l.workspaces||!l.availableProviders||!l.detectedIdes||!l.recentLaunches)||h(l.id,{minFreshMs:3e4}).catch(()=>{})},[h,l]);const ee=a.useMemo(()=>((l==null?void 0:l.availableProviders)||[]).filter(V=>V.category==="cli"&&V.installed!==!1),[l]),Q=a.useMemo(()=>((l==null?void 0:l.availableProviders)||[]).filter(V=>V.category==="acp"&&V.installed!==!1),[l]),ce=a.useMemo(()=>((l==null?void 0:l.detectedIdes)||[]).map(V=>({id:V.type,label:V.name||V.type,meta:V.running?"Detected locally":"Available to open"})),[l]),Ne=a.useMemo(()=>x==="cli"?ee.map(V=>({id:V.type,label:V.displayName||V.type,meta:"CLI provider"})):x==="acp"?Q.map(V=>({id:V.type,label:V.displayName||V.type,meta:"ACP provider"})):ce,[Q,x,ee,ce]);a.useEffect(()=>{var je;if(!l)return;if(M.current!==l.id){M.current=l.id,S(y||((je=b[0])==null?void 0:je.id)||"__home__"),N(""),w(Pr(l)),j(""),E(""),A(""),K([]),z(""),X("");return}S(Se=>{var Te;return Se==="__custom__"||Se==="__home__"||b.some(kt=>kt.id===Se)?Se:y||((Te=b[0])==null?void 0:Te.id)||"__home__"}),w(Se=>Se==="ide"&&ce.length>0||Se==="cli"&&ee.length>0||Se==="acp"&&Q.length>0?Se:Pr(l))},[Q.length,ee.length,y,ce.length,l,b]),a.useEffect(()=>{var V;x&&(Ne.some(je=>je.id===v)||j(((V=Ne[0])==null?void 0:V.id)||""))},[x,Ne,v]);const Pe=a.useCallback(async(V,je)=>{const Se=U.current+1;return U.current=Se,L(!0),z(""),m(V,je).then(Te=>{U.current===Se&&K(Te)}).catch(Te=>{U.current===Se&&(K([]),z(Te instanceof Error?Te.message:"Could not load saved sessions"))}).finally(()=>{U.current===Se&&L(!1)})},[m]),De=a.useCallback((V,je)=>{T($o(V,je))},[]);a.useEffect(()=>{if(A(""),!l||!v||x==="ide"?T([]):De(l.id,v),x!=="cli"){K([]),z(""),L(!1);return}if(!l||!v){K([]),z(""),L(!1);return}Pe(l.id,v)},[x,De,Pe,l,v]),a.useEffect(()=>{if(!G)return;const V=k.find(je=>je.providerSessionId===G);V!=null&&V.canResume||A("")},[k,G]);const Re=u==="__custom__"?_.trim():u==="__home__"?"":((Xe=b.find(V=>V.id===u))==null?void 0:Xe.path)||"",ot=a.useCallback(V=>{const je=String(V.workspace||"").trim();if(!je)return;const Se=b.find(Te=>qs(Te.path)===qs(je));if(Se){S(Se.id),N("");return}S("__custom__"),N(je)},[b]),Qe=a.useCallback(V=>{const je=String(V.workspace||"").trim();if(!je)return{workspaceId:null,workspacePath:null};const Se=b.find(Te=>qs(Te.path)===qs(je));return Se?{workspaceId:Se.id,workspacePath:null}:{workspaceId:null,workspacePath:je}},[b]),ze=a.useMemo(()=>{var je;if(x!=="cli"||!l||!v)return null;const V=((je=ee.find(Se=>Se.type===v))==null?void 0:je.displayName)||v;return{routeId:l.id,daemonId:l.id,providerSessionId:G||void 0,transport:"pty",mode:"chat",agentName:V,agentType:v,status:"idle",title:V,messages:[],ideType:v,workspaceName:Re,displayPrimary:V,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${l.id}:${v}`,machineName:dt(l,{fallbackId:l.id})}},[x,ee,Re,l,G,v]),et=a.useCallback(()=>{var je,Se;if(!l)return;S("__custom__"),ne(!0),fe("");const V=fr(l.platform,[_.trim(),Re,(je=b.find(Te=>Te.id===y))==null?void 0:je.path,(Se=b[0])==null?void 0:Se.path]);te(!0),o(l.id,V).then(Te=>{ae(Te.path),N(Te.path),q(Te.directories)}).catch(Te=>{fe(Te instanceof Error?Te.message:"Could not load folder")}).finally(()=>te(!1))},[_,y,o,Re,l,b]),Ke=a.useCallback(V=>{l&&(te(!0),fe(""),o(l.id,V).then(je=>{ae(je.path),N(je.path),q(je.directories)}).catch(je=>{fe(je instanceof Error?je.message:"Could not load folder")}).finally(()=>te(!1)))},[o,l]),Ce=a.useCallback(async()=>{if(!l||!Re)return;xe(!0),X("");const V=await i(l.id,Re);if(xe(!1),!V.ok){X(V.error||"Could not save workspace");return}X("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Re,l]),Ue=a.useCallback(async()=>{if(!l||!x||!v)return;me(!0),X("");const V=B.trim()?B.trim().split(/\s+/).filter(Boolean):[],je=x==="ide"?await c(l.id,v,{workspacePath:Re||null}):await d(l.id,x,v,{workspaceId:u!=="__home__"&&u!=="__custom__"?u:null,workspacePath:u==="__custom__"&&Re||null,resumeSessionId:x==="cli"&&G?G:null,cliArgs:V});if(me(!1),!je.ok){X(je.error||"Could not start session");return}x!=="ide"&&B.trim()&&(Do(l.id,v,B),De(l.id,v)),n()},[x,B,De,n,c,d,Re,l,G,v,u]);return l?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(bt,{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:l.id,onChange:V=>I(V.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D,children:g.map(V=>e.jsx("option",{value:V.id,children:dt(V,{fallbackId:V.id})},V.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:D||!l,onClick:()=>pe(!0),children:[e.jsx(Bt,{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:et,disabled:D,children:"Browse…"})]}),e.jsxs("select",{value:u,onChange:V=>{const je=V.target.value;S(je),je==="__custom__"?et():X("")},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:[e.jsx("option",{value:"__home__",children:"Home directory"}),b.map(V=>e.jsxs("option",{value:V.id,children:[V.id===y?"⭐ ":"",ur(V.path,V.label)||V.path]},V.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:u==="__home__"?"Launch without a workspace.":Re||"Select a workspace folder."}),u==="__custom__"&&Re&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:D,children:[e.jsx(cs,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:D||R,children:R?"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:ee.length>0},{id:"ide",label:"IDE",enabled:ce.length>0},{id:"acp",label:"ACP",enabled:Q.length>0}].map(V=>e.jsx("button",{type:"button",className:`btn btn-sm ${x===V.id?"btn-primary":"btn-secondary"}`,onClick:()=>w(V.id),disabled:!V.enabled||D,children:V.label},V.id))})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:x==="ide"?"Choose IDE":x==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ne.map(V=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===V.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>j(V.id),disabled:D,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:V.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:V.meta})]},V.id)),Ne.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:B,onChange:V=>E(V.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:D}),W.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:W.map(V=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>E(V),disabled:D,title:V,children:V},V))})]}),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:D||!l||!v||J,onClick:()=>{!l||!v||Pe(l.id,v)},children:J?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:D||!l||!v,onClick:()=>{!l||!v||(Y(!0),Pe(l.id,v))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:G,onChange:V=>{const je=V.target.value;if(A(je),!je)return;const Se=k.find(Te=>Te.providerSessionId===je);!Se||!Se.canResume||ot(Se)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D||J,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),k.map(V=>e.jsxs("option",{value:V.providerSessionId,disabled:!V.canResume,children:[V.title||V.providerSessionId,V.canResume?"":" (workspace missing)"]},V.providerSessionId))]})}),G&&(()=>{const V=k.find(je=>je.providerSessionId===G);return V?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:V.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[V.workspace||"Workspace unknown",V.currentModel?` · ${V.currentModel}`:""]})]}):null})(),$&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:$}),!J&&!$&&k.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),ie&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ie.includes("saved")||ie.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ie})]}),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: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:Ue,disabled:D||!x||!v||u==="__custom__"&&!Re,children:[e.jsx(en,{size:14}),D?"Starting…":"Start session"]})]})]})}),be&&e.jsx(hr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:de,busy:se,error:ge,onClose:()=>ne(!1),onNavigate:Ke,onConfirm:V=>{N(V),ae(V),S("__custom__"),ne(!1)}}),H&&ze&&e.jsx(cn,{activeConv:ze,ides:[],isCreatingChat:!1,isRefreshingHistory:J,savedSessions:k,isSavedSessionsLoading:J,isResumingSavedSessionId:O,onClose:()=>Y(!1),onNewChat:()=>{A(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!l||!v||Pe(l.id,v)},onResumeSavedSession:V=>{if(!l||!v||O||!V.canResume)return;const je=Qe(V);A(V.providerSessionId),ot(V),F(V.providerSessionId),Y(!1),me(!0),X(""),d(l.id,"cli",v,{workspaceId:je.workspaceId,workspacePath:je.workspacePath,resumeSessionId:V.providerSessionId}).then(Se=>{if(!Se.ok){X(Se.error||"Could not resume session");return}n()}).finally(()=>{me(!1),F(Se=>Se===V.providerSessionId?null:Se)})}}),re&&l&&e.jsx(Mu,{machineCards:[{id:l.id,label:dt(l,{fallbackId:l.id}),subtitle:[l.platform||"machine",_o(l)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:l.id,sendDaemonCommand:f,onOpenConversation:V=>{pe(!1),n(),p(V)},onClose:()=>pe(!1)})]}):null}const Bo="adhdev-dashboard-action-shortcuts",Lu=1200,Pu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Ru(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function He(t,s){switch(t){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ko(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:He("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:He("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:He("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:He("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:He("openRemoteForActiveTab",t)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:He("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:He("splitActiveTabDown",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:He("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:He("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:He("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:He("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:He("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:He("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:He("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:He("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:He("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:He("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:He("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:He("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:He("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:He("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:He("toggleCliView",t)}]}function Eu(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function xa(t){const s=Object.fromEntries(Ko(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Bo)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Pu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function $u(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Du({enabled:t=!0,onTrigger:s}){const r=Ru(),[n,o]=a.useState(()=>xa(r)),[i,c]=a.useState(null),[d,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),p=a.useCallback(l=>{const b=[];return l.metaKey&&b.push(r?"⌘":"Meta"),l.ctrlKey&&b.push("Ctrl"),l.altKey&&b.push(r?"⌥":"Alt"),l.shiftKey&&l.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(l.key)?null:(b.push($u(l.key)),b.join("+"))},[r]),h=a.useCallback(l=>{o(l);try{localStorage.setItem(Bo,JSON.stringify(l))}catch{}},[]);a.useEffect(()=>{const l=xa(r),b=Object.entries(n),y=Object.entries(l);b.length===y.length&&b.every(([u,S])=>l[u]===S)||h(l)},[n,r,h]);const g=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),C=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Lu))},[]);a.useEffect(()=>{if(!i)return;const l=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const y=p(b);if(!y)return;const S=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(d.length===0&&S){m([y]);return}const N=[...d,y].slice(0,2).join(" "),x={...n};for(const[w,v]of Object.entries(x))v===N&&delete x[w];x[i]=N,h(x),c(null),m([])};return window.addEventListener("keydown",l,!0),()=>window.removeEventListener("keydown",l,!0)},[n,p,h,i,d]),a.useEffect(()=>{if(!t||i)return;const l=b=>{if(b.defaultPrevented)return;const y=p(b);if(!y)return;const u=b.metaKey||b.ctrlKey||b.altKey;if(Eu(b.target)&&!u)return;const S=f.current.parts,_=u?[y]:[...S.slice(-1),y].slice(-2),N=_.join(" "),x=_[_.length-1],w=Object.entries(n).filter(([,W])=>!!W),v=w.find(([,W])=>W===N);if(v){b.preventDefault(),g(),s(v[0]);return}if(w.some(([,W])=>W.startsWith(`${N} `))){b.preventDefault(),f.current.parts=_,C();return}const B=w.find(([,W])=>W===x);if(B){b.preventDefault(),g(),s(B[0]);return}if(w.some(([,W])=>W.startsWith(`${x} `))){b.preventDefault(),f.current.parts=[x],C();return}g()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[n,C,t,p,s,g,i]),a.useEffect(()=>()=>g(),[g]);const I=a.useMemo(()=>Ko(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:d,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:h}}function Bu(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 Ku(t){return t instanceof Error?t.message:String(t||"")}function Wu(t){const s=Ku(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ou({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:d,onStopCli:m,activeCliViewMode:f,onSetActiveCliViewMode:p,mobileChatConversations:h,hiddenConversations:g,ides:C,actionLogs:I,sendDaemonCommand:l,setLocalUserMessages:b,setActionLogs:y,isStandalone:u,initialDataLoaded:S,userName:_,requestedMobileTabKey:N,onRequestedMobileTabConsumed:x,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:j,onRequestedMobileSectionConsumed:B,containerRef:E,isSplitMode:W,numGroups:T,groupSizes:G,groupedConvs:A,clearedTabs:k,focusedGroup:K,setFocusedGroup:J,moveTabToGroup:L,splitTabRelative:$,closeGroup:z,handleResizeStart:H,detectedIdes:Y,handleLaunchIde:re,groupActiveTabIds:pe,setGroupActiveTabIds:O,groupTabOrders:F,setGroupTabOrders:D,toggleHiddenTab:me,visibleConversations:ie,requestedDesktopTabKey:X,onRequestedDesktopTabConsumed:be,onDesktopActiveTabChange:ne,onHideConversation:le,onShowHiddenConversation:ae,onShowAllHiddenConversations:de,scrollToBottomRequest:q,machineEntries:se,onBrowseMachineDirectory:te,onSaveMachineWorkspace:ge,onLaunchMachineIde:fe,onLaunchMachineProvider:R,onListMachineSavedSessions:xe}){const M=Ge.useRef(null),[U,ee]=Ge.useState(!1),[Q,ce]=Ge.useState(!1),[Ne,Pe]=Ge.useState(!1),[De,Re]=Ge.useState(!1),[ot,Qe]=Ge.useState(!1),[ze,et]=Ge.useState("quickstart"),[Ke,Ce]=Ge.useState("workspace"),Ue=!t&&!s,Ye=Ge.useCallback(ue=>{ee(ue),ue&&ce(!1)},[]),Xe=Ge.useCallback(ue=>{ce(ue),ue&&ee(!1)},[]),V=Ge.useCallback(()=>{et(ie.length===0?"quickstart":"shortcuts"),Ce("workspace"),Pe(!0),ee(!1),ce(!1)},[ie.length]),je=Ge.useCallback(async ue=>{var yt;if(!r)return;const Ee=(yt=r.modalButtons)==null?void 0:yt[ue];if(!Ee)return;const gt=Ts(r);if(!gt)return;const At=Ee.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),$t=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(At);try{await l(gt,"resolve_action",{button:Ee,action:$t?"approve":"reject",buttonIndex:ue,...is(r)})}catch(P){Wu(P)||console.error("[Shortcut approval] Failed:",P)}},[r,l]),{isMac:Se,actionDefinitions:Te,actionShortcuts:kt,shortcutListening:pt,shortcutListeningDraft:Et,setShortcutListening:Nt,setShortcutListeningDraft:It,saveShortcuts:St}=Du({enabled:Ue&&!Ne,onTrigger:ue=>{var Ee,gt,At,$t,yt,P,Z,oe,ye,_e,Ie,Be,it;if(ue==="openShortcutHelp"){V();return}if(ue==="hideCurrentTab"){r&&le(r);return}if(ue==="toggleHiddenTabs"){Xe(!Q);return}if(ue==="openHistoryForActiveTab"){r&&!$e(r)&&c(r);return}if(ue==="openRemoteForActiveTab"){r&&!We(r)&&!$e(r)&&d(r);return}if(ue==="splitActiveTabRight"){(Ee=M.current)==null||Ee.splitActiveTabRight();return}if(ue==="splitActiveTabDown"){(gt=M.current)==null||gt.splitActiveTabDown();return}if(ue==="focusLeftPane"){(At=M.current)==null||At.focusLeftPane();return}if(ue==="focusRightPane"){($t=M.current)==null||$t.focusRightPane();return}if(ue==="focusUpPane"){(yt=M.current)==null||yt.focusUpPane();return}if(ue==="focusDownPane"){(P=M.current)==null||P.focusDownPane();return}if(ue==="moveActiveTabToLeftPane"){(Z=M.current)==null||Z.moveActiveTabToLeftPane();return}if(ue==="moveActiveTabToRightPane"){(oe=M.current)==null||oe.moveActiveTabToRightPane();return}if(ue==="moveActiveTabToUpPane"){(ye=M.current)==null||ye.moveActiveTabToUpPane();return}if(ue==="moveActiveTabToDownPane"){(_e=M.current)==null||_e.moveActiveTabToDownPane();return}if(ue==="triggerPrimaryApprovalAction"){je(0);return}if(ue==="triggerSecondaryApprovalAction"){je(1);return}if(ue==="triggerTertiaryApprovalAction"){je(2);return}if(ue==="setActiveTabShortcut"){(Ie=M.current)==null||Ie.setShortcutForActiveTab();return}if(ue==="selectPreviousGroupTab"){(Be=M.current)==null||Be.activatePreviousTabInGroup();return}if(ue==="selectNextGroupTab"){(it=M.current)==null||it.activateNextTabInGroup();return}!r||!We(r)||$e(r)||ue==="toggleCliView"&&p(f==="chat"?"terminal":"chat")}}),_t=Ge.useCallback(()=>{Pe(!1),Nt(null),It([])},[Nt,It]),ps=Ge.useMemo(()=>Ke==="all"?Te:Te.filter(ue=>Bu(ue)===Ke),[Te,Ke]),Ae=Ge.useCallback(()=>{const ue=Object.fromEntries(Te.map(Ee=>[Ee.id,""]));St(ue)},[Te,St]),Wt=Ge.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ue=Object.fromEntries(Te.map(Ee=>[Ee.id,Ee.defaultShortcut]));St(ue)},[Te,St]);return Ge.useEffect(()=>{const ue=Ee=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ee.metaKey&&Ee.key.toLowerCase()==="w":Ee.ctrlKey&&Ee.key.toLowerCase()==="w")&&(Ee.preventDefault(),r&&le&&le(r))};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[r,le]),Ge.useEffect(()=>{if(!Ne||pt)return;const ue=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),_t())};return window.addEventListener("keydown",ue,!0),()=>window.removeEventListener("keydown",ue,!0)},[_t,Ne,pt]),Ge.useEffect(()=>{if(!Ue){Qe(!1);return}Qe(!0);const ue=window.setTimeout(()=>{Qe(!1)},1e4);return()=>window.clearTimeout(ue)},[Ue]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(nl,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:ie,hiddenConversations:g,onOpenHistory:c,onOpenConversation:ae,onHideConversation:le,onShowConversation:ae,onShowAllHidden:de,inboxOpen:U,onInboxOpenChange:Ye,hiddenOpen:Q,onHiddenOpenChange:Xe,onOpenNewSession:s?void 0:()=>Re(!0),onOpenRemote:()=>{!r||We(r)||$e(r)||d(r)},onStopCli:m,activeCliViewMode:f,onSetCliViewMode:p}),t?e.jsx(nu,{conversations:h,hiddenConversations:g,ides:C,actionLogs:I,sendDaemonCommand:l,setLocalUserMessages:b,setActionLogs:y,isStandalone:u,userName:_,requestedActiveTabKey:N,onRequestedActiveTabConsumed:x,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:j,onRequestedMobileSectionConsumed:B,onOpenHistory:c,onOpenRemote:d,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:ae,onShowAllHiddenConversations:de,onOpenNewSession:()=>Re(!0)}):s?e.jsx(pu,{containerRef:E,isSplitMode:W,numGroups:T,groupSizes:G,groupedConvs:A,clearedTabs:k,ides:C,actionLogs:I,sendDaemonCommand:l,setLocalUserMessages:b,setActionLogs:y,isStandalone:u,hasRegisteredMachines:se.length>0,userName:_,focusedGroup:K,setFocusedGroup:J,moveTabToGroup:L,splitTabRelative:$,closeGroup:z,handleResizeStart:H,detectedIdes:Y,handleLaunchIde:re,groupActiveTabIds:pe,setGroupActiveTabIds:O,groupTabOrders:F,setGroupTabOrders:D,toggleHiddenTab:me,allowTabShortcuts:!1}):e.jsx(wu,{visibleConversations:ie,clearedTabs:k,ides:C,actionLogs:I,sendDaemonCommand:l,setLocalUserMessages:b,setActionLogs:y,isStandalone:u,hasRegisteredMachines:se.length>0,initialDataLoaded:S,userName:_,detectedIdes:Y,handleLaunchIde:re,toggleHiddenTab:me,registerActionHandlers:ue=>{M.current=ue},onActiveTabChange:ne,requestedActiveTabKey:X,onRequestedActiveTabConsumed:be,scrollToBottomRequest:q}),De&&e.jsx(Tu,{machines:se,conversations:h,ides:C,onClose:()=>Re(!1),onBrowseDirectory:te,onSaveWorkspace:ge,onLaunchIde:fe,onLaunchProvider:R,onListSavedSessions:xe,sendDaemonCommand:l,onOpenConversation:ue=>{Re(!1),ae(ue),ne(ue.tabKey)}}),Ne&&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:_t,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:ue=>ue.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, plus grouped shortcuts you can tune."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_t,children:"Close"})]}),e.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(ue=>e.jsx("button",{type:"button",className:`btn btn-sm ${ze===ue.id?"btn-primary":"btn-secondary"}`,onClick:()=>et(ue.id),children:ue.label},ue.id))}),ze==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Se?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ze==="quickstart"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; one active pane is usually the cleanest default."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ze==="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(ue=>e.jsx("button",{type:"button",className:`btn btn-sm ${Ke===ue.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(ue.id),children:ue.label},ue.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,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:Wt,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:ps.map(ue=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${pt===ue.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:ue.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ue.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:ue.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:pt===ue.id?Et.length>0?`${Et.join(" ")} ...`:"Listening...":kt[ue.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Nt(ue.id),It([])},children:pt===ue.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ee={...kt};Ee[ue.id]="",St(Ee)},children:"Disable"})]})]})},ue.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Se?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:V,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 ${ot?"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:"?"}),ot&&e.jsx("span",{children:"Guide"})]})]})}const Rr=[{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 zu({onClose:t}){const[s,r]=a.useState(0),n=Rr[s],o=s===Rr.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(bt,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Rr.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:`
|
|
40
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:j,onCancel:()=>p(null)})]})}const Yl=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Xl(){const{preference:t,setPreference:s}=un();return e.jsx("div",{className:"flex gap-2",children:Yl.map(r=>e.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${t===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:t===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[e.jsx("span",{children:r.icon}),r.label]},r.id))})}function Jl(t){const s=t.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Zl(t){return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16)}}function Ir(t){const s=t/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Zn(t){const{r:s,g:r,b:n}=Zl(t);return .2126*Ir(s)+.7152*Ir(r)+.0722*Ir(n)}function Qn(t,s){const r=Zn(t),n=Zn(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function mo(t){const s=Jl(t);if(!s)return"#111827";const r="#111827",n="#ffffff";return Qn(s,r)>=Qn(s,n)?r:n}const Fr={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},Vr={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},Ql=[{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"}}}],po="adhdev-chat-theme",fo="adhdev-chat-theme-custom";function Qs(){if(typeof window>"u")return"ember";try{return localStorage.getItem(po)||"ember"}catch{return"ember"}}function jt(t){try{const s=localStorage.getItem(fo);if(s){const r=JSON.parse(s);return{...t==="dark"?Fr:Vr,...r[t]}}}catch{}return t==="dark"?Fr:Vr}function zs(t,s){try{localStorage.setItem(fo,JSON.stringify({dark:t,light:s}))}catch{}}function xt(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 or(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 ed={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ss(t,s){var o;const r=(o=ed[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",or(r,24)),n.style.setProperty("--accent-on-primary",mo(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${or(r,18)})`),n.style.setProperty("--border-accent",xt(r,.35)),n.style.setProperty("--nav-active-bg",xt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${xt(r,.06)}`)}function Ft(t){const s=document.documentElement;s.style.setProperty("--bg-primary",t.bgPrimary),s.style.setProperty("--bg-secondary",t.bgSecondary),s.style.setProperty("--bg-card",xt(t.surfacePrimary,.92)),s.style.setProperty("--surface-primary",t.surfacePrimary),s.style.setProperty("--surface-secondary",t.bgSecondary),s.style.setProperty("--bg-glass",xt(t.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",xt(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",xt(t.borderSubtle,.5)),s.style.setProperty("--border-default",xt(t.borderDefault,.5)),s.style.setProperty("--accent-primary",t.accentColor),s.style.setProperty("--accent-primary-light",or(t.accentColor,30)),s.style.setProperty("--accent-on-primary",mo(t.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${t.accentColor}, ${or(t.accentColor,40)})`),s.style.setProperty("--border-accent",xt(t.accentColor,.35)),s.style.setProperty("--nav-active-bg",xt(t.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${t.accentColor}, 0 0 12px ${xt(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 ${xt(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 mn(){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 td(t){try{localStorage.setItem(po,t)}catch{}if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(jt(s))}else mn(),Ss(t,Vt()?"dark":"light")}function sd(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const t=Qs();if(document.documentElement.setAttribute("data-chat-theme",t),t==="custom"){const s=Vt()?"dark":"light";Ft(jt(s))}else mn(),Ss(t,Vt()?"dark":"light")}function Vt(){const t=document.documentElement.getAttribute("data-theme");return t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function st({label:t,value:s,onChange:r}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[e.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),e.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function bs({title:t,children:s}){return e.jsxs("div",{style:{marginBottom:14},children:[e.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:t}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function rd({dark:t,onColorsChange:s}){const r=t?"dark":"light",[n,o]=a.useState(()=>jt(r));a.useEffect(()=>{o(jt(r))},[r]);const i=a.useCallback((c,u)=>{o(m=>{const f={...m,[c]:u},h=jt(r==="dark"?"light":"dark");return r==="dark"?zs(f,h):zs(h,f),Ft(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(bs,{title:"App Background",children:[e.jsx(st,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),e.jsx(st,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),e.jsx(st,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),e.jsxs(bs,{title:"App Text",children:[e.jsx(st,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),e.jsx(st,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),e.jsx(st,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),e.jsxs(bs,{title:"Borders & Accent",children:[e.jsx(st,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),e.jsx(st,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),e.jsx(st,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),e.jsxs("div",{children:[e.jsxs(bs,{title:"Chat Bubbles",children:[e.jsx(st,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),e.jsx(st,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),e.jsx(st,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),e.jsx(st,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),e.jsxs(bs,{title:"Chat Layout",children:[e.jsx(st,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),e.jsx(st,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),e.jsx(st,{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?Fr:Vr,m=jt(t?"light":"dark");t?zs(c,m):zs(m,c),o(c),Ft(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 nd(){const[t,s]=a.useState(Qs),[r,n]=a.useState(!0),[o,i]=a.useState(()=>jt("dark"));a.useEffect(()=>{n(Vt());const m=new MutationObserver(()=>{const h=Vt();n(h);const g=Qs();g==="custom"?Ft(jt(h?"dark":"light")):Ss(g,h?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const h=Vt();n(h);const g=Qs();g==="custom"?Ft(jt(h?"dark":"light")):Ss(g,h?"dark":"light")};return f.addEventListener("change",p),()=>{m.disconnect(),f.removeEventListener("change",p)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ft(jt(r?"dark":"light")):(mn(),Ss(t,r?"dark":"light"))},[t,r]),a.useEffect(()=>{i(jt(r?"dark":"light"))},[r]);const c=m=>{s(m),td(m)},u=[...Ql,{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:u.map(m=>{const f=t===m.id,p=r?m.preview.dark:m.preview.light,h=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return e.jsxs("button",{onClick:()=>c(m.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:p.containerBg},children:[e.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.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:p.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:p.assistantBubble,border:p.assistantBorder,color:p.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:m.id==="custom"?"🎨 Custom":m.name}),e.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),t==="custom"&&e.jsx(rd,{dark:r,onColorsChange:m=>i(m)})]})}const xo="adhdev_mobileDashboardMode_v1";function ho(){try{return localStorage.getItem(xo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ad(t){try{localStorage.setItem(xo,t)}catch{}}function od(){const[t,s]=a.useState(!0);return a.useEffect(()=>{s(ho()==="chat")},[]),e.jsx(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Lt,{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),ad(r?"chat":"workspace")},extra:e.jsx("span",{className:"text-[11px] text-text-muted",children:t?"Chat mode":"Workspace"})})}function id(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 cd(t,s){const{sendData:r}=mt(),{injectEntries:n,getIdes:o}=rr(),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 u=c.map(m=>Dt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const p=o().find(g=>g.id===m),h=id(p,m,f);n([h])}));return()=>{u.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function bo(t,s){const{sendData:r}=mt(),[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);const u=Dt.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}:{}}},m=>{o(m.diagnostics),c(!1)});return()=>{u()}},[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 ld(t){return t.daemonId||(t.routeId.includes(":")?t.routeId.split(":")[0]||null:t.routeId||null)}function go(t){const{sendData:s}=mt(),[r,n]=a.useState({});return a.useEffect(()=>{const o=ld(t);if(!o||!t.sessionId||!s){n({});return}const i=Dt.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})});return()=>{i()}},[t.daemonId,t.routeId,t.sessionId,s]),r}const yo="adhdev_hiddenTabs";function dd(){try{const t=localStorage.getItem(yo);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ss(t){try{localStorage.setItem(yo,JSON.stringify([...t]))}catch{}}function ud(){const[t,s]=a.useState(dd),r=a.useCallback(f=>{s(p=>{const h=new Set(p);return h.has(f)?h.delete(f):h.add(f),ss(h),h})},[]),n=a.useCallback(f=>{s(p=>{if(p.has(f))return p;const h=new Set(p);return h.add(f),ss(h),h})},[]),o=a.useCallback(f=>{s(p=>{if(!p.has(f))return p;const h=new Set(p);return h.delete(f),ss(h),h})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const p=new Set;return ss(p),p})},[]),c=a.useCallback((f,p)=>{s(h=>{const g=new Set(h);for(const C of p)g.add(C);return ss(g),g})},[]),u=a.useCallback((f,p)=>{s(h=>{const g=new Set(h);for(const C of p)g.delete(C);return ss(g),g})},[]),m=a.useCallback(f=>t.has(f),[t]);return{hiddenTabs:t,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:u,isHidden:m}}function md({visibleConversations:t,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{wl()},[]);const o=a.useMemo(()=>t.map(i=>({id:i.tabKey,name:eo(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[t]);return kl(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(u=>{const m=Date.now(),f={};for(const[p,h]of Object.entries(u))m-h<5e3&&(f[p]=h);return Object.keys(f).length===Object.keys(u).length?u:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(u=>{const m=u.filter(f=>f.timestamp>c).slice(-100);return m.length===u.length?u:m})},6e4);return()=>clearInterval(i)},[n]),null}function pd(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 Gt(t){const s=[...t.messages].reverse().find(r=>!(r!=null&&r._localId))||t.messages[t.messages.length-1];return pd(s==null?void 0:s.receivedAt)||0}function Gr(t,s=0){return Gt(t)||t.lastUpdated||s||0}function vo(t){return Gt(t)||t.lastUpdated||0}function wo(t,s,r=vo){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 qr(t){var r;const s=rt(t.status,{activeModal:(r=t.modalButtons)!=null&&r.length?{buttons:t.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function fd(t){var s;return t.messages.length===0&&!((s=t.modalButtons)!=null&&s.length)&&!qr(t)&&!t.title.trim()}function xd(t){return t.length===0?null:[...t].sort((s,r)=>{const n=Number(qr(r))-Number(qr(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:wo(s,r)})[0]||null}function Rt(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=xd(o);return n?i&&fd(n)?i:n:i||r[0]||null}function hd(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 Hs(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 bd(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 gd(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 yd(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 vd(t){return[...t.messages].reverse().find(s=>!(s!=null&&s._localId))||t.messages[t.messages.length-1]}function wd(t){const s=vd(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=Jt(s.content).slice(0,240);return`${t.messages.length}:${r}:${n}`}function jd({ides:t,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),u=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const x=hd(t);return Hs(i.current,x)?i.current:(i.current=x,x)},[t]),p=a.useMemo(()=>so(t),[t]),h=a.useRef(new Map),g=a.useRef(new Map),C=a.useMemo(()=>{const x=new Map,w=[];for(const E of f){const{connectionState:W="new",machineName:T}=ro(E,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),G=gd(E,r),_=h.current.get(E.id);if(_&&_.ide===E&&_.connectionState===W&&_.machineName===T&&yd(_.localRefs,G)){x.set(E.id,_),w.push(..._.conversations);continue}const k=ln(E,r,{machineNames:p,connectionStates:s,defaultConnectionState:"new"}),K={ide:E,connectionState:W,machineName:T,localRefs:G,conversations:k};x.set(E.id,K),w.push(...k)}h.current=x;const v=new Map,j=E=>{const W=wd(E),T=g.current.get(E.tabKey);if(T&&T.signature===W)return v.set(E.tabKey,T),T.timestamp;const G={signature:W,timestamp:vo(E)||(T==null?void 0:T.timestamp)||0};return v.set(E.tabKey,G),G.timestamp},B=[...w].sort((E,W)=>wo(E,W,j));return g.current=v,B},[f,r,s,p]),I=a.useMemo(()=>{const x=bd(C,n);return Hs(c.current,x)?c.current:(c.current=x,x)},[C,n]),d=a.useMemo(()=>{const x=new Map,w=Array.from(new Set(I.map(v=>v.routeId)));for(const v of w){const j=Rt(I,v);j&&x.set(v,j)}return x},[I]),b=a.useMemo(()=>{const x=new Map;for(const w of I)if(w.sessionId&&x.set(w.sessionId,w),w.streamSource==="native"&&w.sessionId){const v=d.get(w.routeId);v&&x.set(w.sessionId,v)}return x},[I,d]),y=a.useMemo(()=>{const x=new Map;for(const w of I)w.sessionId&&x.set(w.sessionId,w),x.set(w.routeId,d.get(w.routeId)||w),x.set(w.tabKey,w);return x},[I,d]),l=a.useCallback(x=>{if(x)return b.get(x)},[b]),S=a.useCallback(x=>{if(x)return y.get(x)},[y]),M=a.useMemo(()=>{const x=I.filter(w=>!o.has(w.tabKey));return Hs(u.current,x)?u.current:(u.current=x,x)},[I,o]),N=a.useMemo(()=>{const x=M.map(w=>w.tabKey);return Hs(m.current,x)?m.current:(m.current=x,x)},[M]);return{chatIdes:f,conversations:I,visibleConversations:M,visibleTabKeys:N,resolveConversationBySessionId:l,resolveConversationByTarget:S}}function kd({isMobile:t,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var u;return t||!s?null:((u=r(s))==null?void 0:u.tabKey)??null},[t,r,s]),i=a.useMemo(()=>{var u;return!t||!s?null:((u=r(s))==null?void 0:u.tabKey)??null},[t,r,s]),c=a.useCallback(()=>{s&&n(u=>{const m=new URLSearchParams(u);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Nd({ides:t,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{nt.setIdes(t)},[t]),a.useEffect(()=>{nt.setResolveAction((i,c,u)=>{s(i,c,u).catch(()=>{})})},[s]),a.useEffect(()=>{const i=nt.onToast(m=>{r(p=>p.some(g=>g.message===m.message&&m.timestamp-g.timestamp<3e3)?p:[...p.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const f=m.duration||5e3;setTimeout(()=>r(p=>p.filter(h=>h.id!==m.id)),f)}),c=nt.onSystemMessage((m,f)=>{var C,I;const p=o(m),h=(C=f._localId)==null?void 0:C.startsWith("sys_approval_"),g=!!(p&&(p.status==="waiting_approval"||(I=p.modalButtons)!=null&&I.length||p.modalMessage));h&&g||n(d=>({...d,[m]:[...d[m]||[],f]}))}),u=nt.onClearSystemMessage((m,f)=>{n(p=>{var h;return(h=p[m])!=null&&h.length?{...p,[m]:p[m].filter(g=>{var C;return!(g.role==="system"&&((C=g._localId)!=null&&C.startsWith(f)))})}:p})});return()=>{i(),c(),u()}},[r,n]),a.useEffect(()=>{const i=Ja.on("status_event",c=>{nt.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=u=>{var b;const m=u.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const f=m.targetSessionId||m.targetKey||m.daemonId,p=o(f),h=(p==null?void 0:p.routeId)||m.daemonId;if(!h)return;const g=Number(m.buttonIndex),C=m.button||((b=p==null?void 0:p.modalButtons)==null?void 0:b[g])||"Approve",I=String(C).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I);s(h,"resolve_action",{action:d?"approve":"reject",button:C,...Number.isFinite(g)&&{buttonIndex:g},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var u;return(u=navigator.serviceWorker)==null?void 0:u.removeEventListener("message",i)}},[o,s])}const Sd="adhdev_dashboardLayout_v1",Cd="adhdev_dashboardDockview_v1",gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function jo(t,s){try{const r=localStorage.getItem(t);return r?JSON.parse(r):s}catch{return s}}function ko(t){return t<768?"mobile":t<1280?"desktop-narrow":"desktop-wide"}function No(t){return`${Sd}:${t}`}function Id(t){const s=No(t);return jo(s,null)}function Md(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=No(t);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function So(t){return`${Cd}:${t}`}function _d(t){const s=So(t);return jo(s,null)}function Ad(t,s){try{const r=So(t);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Td(){return{groupAssignments:[...gs.groupAssignments],focusedGroup:gs.focusedGroup,groupActiveTabIds:{...gs.groupActiveTabIds},groupTabOrders:{...gs.groupTabOrders},groupSizes:[...gs.groupSizes]}}function Pd(){const[t]=a.useState(()=>ko(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[u,m]=a.useState({}),[f,p]=a.useState([]),[h,g]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,I]=a.useState(!1),d=a.useCallback(()=>{if(C)return;const b=Id(t)??Td();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),p(b.groupSizes),I(!0)},[C,t]);return a.useEffect(()=>{C&&Md(t,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:u,groupSizes:f})},[C,t,s,n,i,u,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=l=>g(l.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:u,setGroupTabOrders:m,groupSizes:f,setGroupSizes:p,isMobile:h,hasHydratedStoredLayout:C,hydrateStoredLayout:d}}function Ld(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 Rd({urlActiveTab:t,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:u,setSearchParams:m,historyModalOpen:f,activeConv:p,isRefreshingHistory:h,ides:g,handleRefreshHistory:C}){const I=a.useRef(!1),d=a.useRef(!1),b=a.useRef(null),y=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 S=n.get(l.tabKey)??0;c(M=>({...M,[S]:l.tabKey})),u(S),I.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(M=>{const N=new URLSearchParams(M);return N.delete("activeTab"),N},{replace:!0})},[t,s,r,n,o,i,c,u,m]),a.useEffect(()=>{if(!(d.current||o)&&s.length!==0){if(!t){i(),d.current=!0;return}if(I.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||o)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[t,s.length,o,i]),a.useEffect(()=>{if(!f){y.current=!1;return}if(!p||y.current||h)return;const l=g.find(S=>S.id===p.routeId);l&&(!l.chats||l.chats.length===0||Ld(l.chats,p))&&(y.current=!0,C())},[f,p,h,g,C]),a.useEffect(()=>{if(!p)return;let l=null,S=0,M=-1,N=0;const x=()=>{l=null;const w=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(j=>j.offsetParent!==null);if(w.length===0){S<18&&(S+=1,l=requestAnimationFrame(x));return}let v=0;for(const j of w)j.scrollTop=j.scrollHeight,v+=j.scrollHeight;v===M?N+=1:(N=0,M=v),S+=1,!(N>=2||S>=18)&&(l=requestAnimationFrame(x))};return l=requestAnimationFrame(x),()=>{l!=null&&cancelAnimationFrame(l)}},[p==null?void 0:p.tabKey])}function Ed({isMobile:t,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:u}){const[m,f]=a.useState(null),[p,h]=a.useState(null),g=a.useMemo(()=>{if(t||!n)return null;const y=u(n);return y&&!We(y)&&!$e(y)?y:null},[t,n,u]),C=a.useMemo(()=>{const y=m==null?void 0:m.routeId;if(!y)return null;const l=m!=null&&m.tabKey?i.find(S=>S.tabKey===m.tabKey):o?i.find(S=>S.tabKey===o):null;return(l==null?void 0:l.routeId)===y?l:Rt(i,y)},[i,m,o]),I=a.useMemo(()=>{if(C)return c.find(y=>y.id===C.routeId)},[c,C]);a.useEffect(()=>{g&&(f({routeId:g.routeId,tabKey:Dn(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=a.useCallback(y=>{y&&(f({routeId:y.routeId,tabKey:Dn(y)}),h(y))},[]),b=a.useCallback(()=>{f(null),h(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:I,remoteDialogActiveConv:p,setRemoteDialogActiveConv:h,openRemoteDialog:d,closeRemoteDialog:b}}function is(t){if(!t)return{};const s=t.sessionId?{targetSessionId:t.sessionId}:{};return t.sessionId?s:We(t)||$e(t)?{agentType:lt(t)}:t.streamSource==="agent-stream"?{agentType:lt(t)}:s}function Ts(t){return t?nr(t):""}function ys(t,s){t(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Mr(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 ea({sendDaemonCommand:t,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[u,m]=a.useState(!1),[f,p]=a.useState(!1),h=a.useCallback(async d=>{try{await t("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[t]),g=a.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",l=await t(y,"switch_chat",{id:b,sessionId:b,...is(s)}),S=l==null?void 0:l.result;if((l==null?void 0:l.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?ys(o,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?ys(o,`⚠️ Switch error: ${S}`):ys(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),ys(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,t,o]),C=a.useCallback(async()=>{if(!(!s||u)){m(!0);try{const d=Ts(s);await t(d,"new_chat",{...is(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,u,t,c,i]),I=a.useCallback(async()=>{var d,b;if(!(!s||f)){p(!0);try{const y=Ts(s),l=async()=>t(y,"list_chats",{forceExpand:!0,...is(s)});let S=await l(),M=(S==null?void 0:S.chats)||((d=S==null?void 0:S.result)==null?void 0:d.chats);Mr(M,s)&&(await new Promise(N=>setTimeout(N,450)),S=await l(),M=(S==null?void 0:S.chats)||((b=S==null?void 0:S.result)==null?void 0:b.chats)),S!=null&&S.success&&Array.isArray(M)&&(n(s.routeId,M),Mr(M,s)&&!Mr(r,s)&&ys(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{p(!1)}}},[s,r,f,t,n,o]);return{isCreatingChat:u,isRefreshingHistory:f,handleLaunchIde:h,handleSwitchSession:g,handleNewChat:C,handleRefreshHistory:I}}function $d(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 Dd(t,s){return t.length!==s.length?!1:t.every((r,n)=>r===s[n])}function ta(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 Us(t,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,u]of t)!r.has(c)||u<=0||n.includes(u)||n.push(u);n.sort((c,u)=>c-u);const o={};n.forEach((c,u)=>{o[c]=u}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,u]of t){if(!r.has(c)||u<=0)continue;const m=o[u];typeof m=="number"&&m>0&&i.set(c,m)}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 Bd(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 Kd(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,u)=>c+u,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function ra(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 na(t){return Array(t).fill(100/t)}function Wd({groupAssignments:t,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:u,visibleConversations:m,visibleTabKeys:f}){const p=a.useRef(null),h=a.useMemo(()=>Us(t,f),[t,f]),g=h.assignments,C=a.useMemo(()=>u?1:h.groupCount,[h.groupCount,u]),I=C>1,d=a.useCallback((N,x)=>{s(w=>{const v=new Map(Us(w,f).assignments);return x===0?v.delete(N):v.set(N,x),v}),n(w=>({...w,[x]:N})),r(x)},[s,f,n,r]),b=a.useCallback(N=>{s(x=>{const w=Us(x,f).assignments,v=new Map;for(const[j,B]of w)B!==N&&(B>N?v.set(j,B-1):v.set(j,B));return v}),c(x=>{if(x.length<=1)return[];const w=[...x];w.splice(N,1);const v=w.reduce((j,B)=>j+B,0);return v>0?w.map(j=>j/v*100):[]}),r(0)},[s,f,c,r]),y=a.useCallback((N,x)=>{x.preventDefault();const w=p.current;if(!w)return;const v=x.clientX,j=w.offsetWidth,B=i.length===C?[...i]:na(C),E=T=>{const _=(T.clientX-v)/j*100,k=[...B];k[N]=Math.max(15,B[N]+_),k[N+1]=Math.max(15,B[N+1]-_),c(k)},W=()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",W),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",E),document.addEventListener("mouseup",W)},[i,C,c]),l=a.useCallback((N,x,w)=>{if(C>=4)return;const v=w==="left"?x:x+1;s(j=>{const B=Us(j,f).assignments,E=new Map;for(const W of m){const T=B.get(W.tabKey)??0,G=T>=v?T+1:T;G>0&&E.set(W.tabKey,G)}return v>0&&E.set(N,v),E}),c(j=>{const B=j.length===C?[...j]:na(C),E=B[x]??100/C,W=Math.max(15,E/2),T=Math.max(15,E/2),G=[...B];G[x]=W,G.splice(v,0,T);const _=G.reduce((k,K)=>k+K,0);return G.map(k=>k/_*100)}),n(j=>{const B=ra(j,v);return B[v]=N,B}),o(j=>{const B=ra(j,v);return B[v]=[N],B}),r(v)},[C,s,f,m,c,n,o,r]);a.useEffect(()=>{$d(t,g)||s(g)},[t,g,s]),a.useEffect(()=>{const{mapping:N,usedGroups:x}=h;n(w=>{const v=sa(w,N);return ta(w,v)?w:v}),o(w=>{const v=sa(w,N);return ta(w,v)?w:v}),r(w=>{const v=u?0:Bd(w,x,N);return w===v?w:v}),c(w=>{const v=u?[]:Kd(w,x,h.groupCount);return Dd(w,v)?w:v})},[h,u,n,o,r,c]);const S=a.useMemo(()=>{const N=Array.from({length:C},()=>[]);for(const x of m){const w=g.get(x.tabKey)??0,v=Math.min(w,C-1);N[v].push(x)}return N},[m,g,C]),M=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:p,normalizedGroupAssignments:g,numGroups:C,isSplitMode:I,groupedConvs:S,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:l,clearAllSplits:M}}function Od({ides:t,sendDaemonCommand:s}){const r="0.8.39",n=a.useMemo(()=>t.filter(f=>{if(f.type!=="adhdev-daemon")return!1;const p=f.version||f.daemonVersion||null;return!p||!r?!1:p!==r}),[r,t]),[o,i]=a.useState(!1),[c,u]=a.useState({}),m=a.useCallback(async f=>{var p,h;u(g=>({...g,[f]:"upgrading"}));try{const g=await s(f,"daemon_upgrade",{});(p=g==null?void 0:g.result)!=null&&p.upgraded||(h=g==null?void 0:g.result)!=null&&h.success?u(C=>({...C,[f]:"done"})):u(C=>({...C,[f]:"error"}))}catch{u(g=>({...g,[f]:"error"}))}},[s]);return{versionMismatchDaemons:n,appVersion:r,versionBannerDismissed:o,setVersionBannerDismissed:i,upgradingDaemons:c,handleBannerUpgrade:m}}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 oa(t){const s=pn(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ia(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 pr({sendDaemonCommand:t,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[u,m]=a.useState(!1),f=a.useRef(!1),p=a.useRef(null),h=a.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||f.current)return;const y=s.tabKey,l=Date.now(),S=p.current;if(S&&S.tabKey===y&&S.message===b&&l-S.timestamp<2e3)return;f.current=!0,m(!0),p.current={tabKey:y,message:b,timestamp:l};const M=`${l}-${Math.random().toString(36).slice(2,8)}`,N={role:"user",content:b,timestamp:l,_localId:M},x=!(We(s)||$e(s));x&&r(w=>({...w,[y]:[...w[y]||[],N]}));try{const w=Ts(s);if(!w)return;const v=await t(w,"send_chat",{message:b,...is(s)}),j=aa(v);if(x&&(j!=null&&j.deduplicated||(j==null?void 0:j.sent)===!1)){r(B=>({...B,[y]:(B[y]||[]).filter(E=>E._localId!==M)}));return}if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");setTimeout(()=>{const B=Date.now()-6e4;r(E=>{const W=E[y];if(!W)return E;const T=W.filter(G=>G.timestamp>B);return T.length===W.length?E:{...E,[y]:T}})},6e4)}catch(w){const v=pn(w);v.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",v):console.error("Send failed",w),x&&r(j=>({...j,[y]:(j[y]||[]).filter(B=>B._localId!==M)}))}finally{f.current=!1,m(!1)}},[s,t,r]),g=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await t(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,t]),C=a.useCallback(async d=>{if(s)try{const y=(s.modalButtons||[]).indexOf(d),l=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(l),M=Ts(s);if(!M)return;const N=await t(M,"resolve_action",{button:d,action:S?"approve":"reject",...y>=0&&{buttonIndex:y},...is(s)}),x=aa(N);x.success||n(w=>[...w,{routeId:s.tabKey,text:ia(d,x==null?void 0:x.error),timestamp:Date.now()}])}catch(b){oa(b)||console.error("[ModalButton] Error:",b),n(y=>[...y,{routeId:s.tabKey,text:oa(b)?ia(d,b):`❌ **${d}** 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(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,t]);return{isSendingChat:u,isFocusingAgent:i,handleSendChat:h,handleRelaunch:g,handleModalButton:C,handleFocusAgent:I}}const fn=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:u,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:d=!0}){const b=go(s),y=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(Oa,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.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(Xt,{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:u,children:"Relaunch with CDP"})]})}):null,y.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:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&e.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:e.jsx(zr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:d})})]}):e.jsx(zr,{activeConv:y,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:p,isFocusingAgent:h,actionLogs:g,userName:C,scrollToBottomRequestNonce:I,isInputActive:d})]})},(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 zd({selectedConversation:t,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:u,onBack:m,onOpenNativeConversation:f,onOpenMachine:p,onOpenHistory:h,onOpenRemote:g,onHideConversation:C,onStopCli:I,cliViewMode:d,onSetCliViewMode:b,handleSendChat:y,handleFocusAgent:l,handleModalButton:S,handleRelaunch:M}){const N=a.useRef(null),x=We(t)&&!s,w=x&&d==="terminal",v=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 ${v} 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:m,type:"button","aria-label":"Back",children:e.jsx(Jr,{size:18})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ve(t)}),e.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:e.jsx(Va,{conversation:t,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(t),onOpenMachine:()=>p(t)})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[x&&d&&e.jsx(on,{mode:d,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(bt,{size:14})}),e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(t),type:"button",children:e.jsx(Qr,{size:14})}),!s&&!x&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(t),type:"button",children:e.jsx(ut,{size:14})}),C&&e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(t),type:"button",title:"Close chat",children:e.jsx(bt,{size:14})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:e.jsx(fn,{activeConv:t,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:N,handleModalButton:S,handleRelaunch:M,handleSendChat:y,isSendingChat:c,handleFocusAgent:l,isFocusingAgent:u,actionLogs:o,userName:i})})]})}const _r={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 Hd(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Co(){const[t,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=t==="unix"?"unix":r;a.useEffect(()=>{s(Hd())},[]);const u=a.useCallback(()=>{navigator.clipboard.writeText(_r[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:u,title:"Click to copy",children:[e.jsx("span",{className:"text-text-muted select-none",children:_r[c].prompt}),e.jsx("span",{className:"flex-1 break-all",children:_r[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 Io({section:t,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:ut},{key:"chats",label:"Chats",icon:Lt}];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 Fs({title:t,className:s=""}){return e.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:e.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:t})})}function rs({children:t,className:s=""}){return e.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:t})}function vs({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 Vs({item:t,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",u=s==="task_complete",{isReconnecting:m,isConnecting:f}=ms(t.conversation),p=Ve(t.conversation),h=Qt(t.conversation),g=Qa(t.conversation,{requiresAction:s==="needs_attention"}),C=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",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",l=c?"text-text-muted opacity-80":"text-text-muted",S="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] ${C}`,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(p)}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:p}),!i&&e.jsx("span",{className:`text-[11px] font-medium shrink-0 ${l}`,children:Wa(t.timestamp)})]}),e.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[h,m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:`${S} 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…"})]}):g==="Action needed"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{className:S,children:"Action needed"})]})]}),e.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:t.preview})]}),o&&!u&&e.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&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 ca({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 Ud({section:t,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:u,onOpenConversation:m,onShowConversation:f,onShowAllHidden:p,onOpenNewSession:h,onOpenMachine:g,onOpenSettings:C,onSectionChange:I,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",l=c.length>0,S=s.length>0||r.length>0||n.length>0||o.length>0,M=t==="machines"?"Machines":"Chats",N=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 ${N}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:M}),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(dr,{size:13}),e.jsx("span",{children:s.length+r.length})]}),e.jsx("button",{onClick:C,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(cr,{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:y?e.jsx(vs,{icon:e.jsx(ca,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?e.jsx(vs,{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(Co,{})})}):e.jsx(rs,{children:c.map((w,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(w.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:u(w.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:w.label}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:w.unread>0?e.jsxs("span",{className:"text-accent-primary",children:[w.unread," new"]}):w.total>0?`${w.total} chats`:"Idle"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:w.subtitle}),w.total>0?e.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[w.total," chat",w.total!==1?"s":"",w.unread>0?` · ${w.unread} unread`:""]}):e.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},w.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(Fs,{title:"Needs attention",className:"mb-0"}),e.jsx(rs,{children:s.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"needs_attention",getAvatarText:u,onOpenConversation:m})},w.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(Fs,{title:"Task complete",className:"mb-0 mt-2"}),e.jsx(rs,{children:r.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"task_complete",getAvatarText:u,onOpenConversation:m})},w.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(Fs,{title:"Working now",className:"mb-0 mt-2"}),e.jsx(rs,{children:n.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"working",getAvatarText:u,onOpenConversation:m})},w.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(Fs,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?e.jsx(rs,{children:o.map((w,v)=>e.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:e.jsx(Vs,{item:w,type:"earlier",getAvatarText:u,onOpenConversation:m})},w.conversation.tabKey))}):S?e.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?e.jsx(vs,{icon:e.jsx(ca,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):l?e.jsx(vs,{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(Lt,{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(vs,{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:p,children:"Restore all"})]}),e.jsx(rs,{className:"bg-bg-secondary/25",children:i.map((w,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(w),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:u(Ve(w))}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:Ve(w)}),e.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),e.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:Qt(w)}),e.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},w.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(Io,{section:t,onSectionChange:I})]})}function Fd(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 fr(t,s=[]){if(t==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Fd(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 Vd(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 xr(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=(m,f)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${f}`:m==="/"||m==="\\"?`${i}${f}`:`${m.replace(/[\\/]+$/,"")}${i}${f}`,u=Array.isArray(n==null?void 0:n.files)?n.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:c(o,m.name)})).sort((m,f)=>m.name.localeCompare(f.name)):[];return{path:o,directories:u}}function hr({title:t,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:u,onNavigate:m,onConfirm:f}){const[p,h]=a.useState(r);a.useEffect(()=>{h(r)},[r]);const g=Vd(r),C=p.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:u,"aria-label":"Close folder browser",children:e.jsx(bt,{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:()=>{!g||o||m(g)},disabled:!g||o,children:[e.jsx(Jr,{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:p,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key!=="Enter"||!C||o||(I.preventDefault(),m(C))},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:()=>{!C||o||m(C)},disabled:!C||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:()=>m(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(cs,{size:17})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children: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:u,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>f(C||r),disabled:!C&&!r||o,children:c})]})]})})}function xn({title:t,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busy:u=!1,showArgsInput:m,argsValue:f,onArgsChange:p,showModelInput:h,modelValue:g,onModelChange:C,historyProviderNode:I,onConfirm:d,onCancel:b}){const y=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(bt,{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:u,children:n.map(l=>e.jsx("option",{value:l.key,children:l.label},l.key))}),(y==null?void 0:y.description)&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.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&&C&&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:g||"",onChange:l=>C(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:u})]}),m&&p&&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=>p(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:u})]})]}),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:u,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:d,disabled:u,children:[e.jsx(en,{size:14}),u?"Launching…":c]})]})]})})}function la(t,s){return s||t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t}function qt(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 m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${la(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",u=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!u&&i.push({key:`custom:${c}`,label:la(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(f=>f.key===m))return{options:i,selectedKey:m}}return u?{options:i,selectedKey:`saved:${u.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Ar(t,s,r){return t?"ide":s>0?"cli":r>0?"acp":null}function Gd({selectedMachineEntry:t,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var xe,A,H,ee;const c=$s(),[u,m]=a.useState(!1),f=(((xe=t.detectedIdes)==null?void 0:xe.length)||0)>0,p=a.useMemo(()=>(t.workspaces||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[t]),h=t.defaultWorkspaceId||null,[g,C]=a.useState(h||((A=p[0])==null?void 0:A.id)||""),[I,d]=a.useState(""),[b,y]=a.useState(""),[l,S]=a.useState([]),[M,N]=a.useState(!1),[x,w]=a.useState(""),[v,j]=a.useState(!1),[B,E]=a.useState(Ar(f,s.length,r.length)),W=a.useRef(null),[T,G]=a.useState(null),_=a.useRef("__home__"),[k,K]=a.useState("__home__"),[J,P]=a.useState(""),[$,z]=a.useState(""),[U,Y]=a.useState(""),[re,pe]=a.useState([]),[O,F]=a.useState(!1),[D,me]=a.useState(!1),ie=a.useRef(null);a.useEffect(()=>{(!t.workspaces||!t.availableProviders||!t.detectedIdes||!t.recentLaunches)&&c(t.id,{minFreshMs:3e4}).catch(()=>{})},[c,t]);const X=g==="__custom__"?I.trim():((H=p.find(Q=>Q.id===g))==null?void 0:H.path)||"",be=g==="__custom__"&&!!X&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ne=g!=="__custom__"&&((ee=p.find(Q=>Q.id===g))==null?void 0:ee.path)||"",le=a.useCallback(async Q=>{N(!0),w("");try{const ce=await o(Q);y(ce.path),d(ce.path),S(ce.directories)}catch(ce){w(ce instanceof Error?ce.message:"Could not load folder")}finally{N(!1)}},[o]),ae=a.useCallback(()=>{var ce,Ne;C("__custom__"),j(!0);const Q=fr(t.platform,[I.trim(),ne,(ce=p.find(Le=>Le.id===h))==null?void 0:ce.path,(Ne=p[0])==null?void 0:Ne.path]);le(Q)},[I,h,le,ne,t.platform,p]),de=a.useCallback(Q=>{if(Q!=null&&Q.workspaceId){C(Q.workspaceId),d("");return}if(Q!=null&&Q.workspacePath){C("__custom__"),d(Q.workspacePath);return}C(""),d("")},[]),q=a.useCallback(Q=>{if(C(Q),Q==="__custom__"){ae();return}d("")},[ae]),se=a.useCallback(Q=>{C("__custom__"),d(Q)},[]),te=a.useCallback((Q,ce)=>{W.current=ce,_.current=Q.selectedWorkspaceKey||"__home__",K(Q.selectedWorkspaceKey||"__home__"),P(Q.initialArgs||""),z(Q.initialModel||""),Y(""),pe([]),G(Q),Q.providerType&&i&&(F(!0),i(Q.providerType).then(Ne=>pe(Ne||[])).catch(Ne=>console.warn("Failed to load saved sessions",Ne)).finally(()=>F(!1)))},[i]),ge=a.useCallback(()=>{W.current&&(me(!0),W.current().finally(()=>{W.current=null,me(!1),G(null)}))},[]),fe=a.useCallback(()=>{W.current=null,G(null)},[]),R=a.useCallback(Q=>{_.current=Q,K(Q)},[]);return a.useEffect(()=>{var Q;ie.current!==t.id&&(ie.current=t.id,C(h||((Q=p[0])==null?void 0:Q.id)||"__custom__"),d(""),y(""),S([]),w(""),j(!1),E(Ar(f,s.length,r.length)))},[r.length,s.length,h,f,t.id,p]),a.useEffect(()=>{var Q;g!=="__custom__"&&(g&&p.some(ce=>ce.id===g)||C(h||((Q=p[0])==null?void 0:Q.id)||"__custom__"))},[h,g,p]),a.useEffect(()=>{B==="ide"&&f||B==="cli"&&s.length>0||B==="acp"&&r.length>0||E(Ar(f,s.length,r.length))},[B,r.length,s.length,f]),{showAllRecent:u,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:p,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:I,browseCurrentPath:b,browseDirectories:l,browseBusy:M,browseError:x,browseDialogOpen:v,activeLauncherKind:B,launchConfirm:T,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:k,launchConfirmArgs:J,launchConfirmModel:$,launchConfirmResumeId:U,launchConfirmSavedSessions:re,launchConfirmSessionsLoading:O,launchConfirmBusy:D,resolvedWorkspacePath:X,canCreateMissingWorkspace:be,openBrowseDialog:ae,loadBrowsePath:le,handleWorkspaceChoiceChange:q,chooseCustomWorkspacePath:se,setCustomWorkspacePath:d,setBrowseDialogOpen:j,setActiveLauncherKind:E,openLaunchConfirm:te,handleConfirmLaunch:ge,closeLaunchConfirm:fe,setWorkspaceSelectionFromOption:de,setLaunchConfirmWorkspaceKeyAndSync:R,setLaunchConfirmArgs:P,setLaunchConfirmModel:z,setLaunchConfirmResumeId:Y}}function qd({selectedMachineEntry:t,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:u,isStandalone:m,section:f,showBottomNav:p,onBack:h,onSectionChange:g,onOpenConversation:C,onOpenRecent:I,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:l,onBrowseDirectory:S,onLaunchWorkspaceProvider:M,onListSavedSessions:N}){const x=k=>k==="ide"?"IDE":k==="cli"?"CLI":"ACP",w=r.slice(0,4),v=s.slice(0,3),j=Gd({selectedMachineEntry:t,cliProviders:n,acpProviders:o,machineAction:u,onBrowseDirectory:S,onListSavedSessions:N}),B=a.useMemo(()=>w.map(k=>({key:`recent-launch:${k.id}`,primary:k.label,secondary:`${x(k.kind)}${k.subtitle?` · ${k.subtitle}`:""}`,onClick:()=>{const{options:K,selectedKey:J}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:k.workspace});j.openLaunchConfirm({title:`Launch ${k.label}?`,description:"Recent launches require one more confirmation before they run.",confirmLabel:"Launch",workspaceOptions:K,selectedWorkspaceKey:J,details:[{label:"Mode",value:x(k.kind)},...k.providerType?[{label:"Provider",value:k.providerType}]:[]]},async()=>{const P=K.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(P),await I({...k,workspace:(P==null?void 0:P.workspacePath)??null})})}})),[j,I,w]),E=a.useMemo(()=>v.map(k=>({key:`recent-chat:${k.conversation.tabKey}`,primary:Ve(k.conversation),secondary:Xc(k.conversation,{timestampLabel:k.timestamp?Wa(k.timestamp):null}),unread:k.unread,onClick:()=>C(k.conversation)})),[C,v]),W=j.showAllRecent?B:B.slice(0,4),T=B.length>0,G=E.length>0,_=m?"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(Jr,{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:dt(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:[G&&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:E.map(k=>e.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${k.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:k.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:k.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))})]}),T&&e.jsxs("section",{className:"flex flex-col gap-0",children:[e.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),e.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:W.map(k=>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:k.onClick,children:[e.jsx("span",{className:"text-sm font-bold text-text-primary",children:k.primary}),e.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:k.secondary})]},k.key))}),B.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(k=>!k),children:j.showAllRecent?"Show fewer":`Show ${B.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:k=>j.handleWorkspaceChoiceChange(k.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(k=>e.jsxs("option",{value:k.id,children:[k.id===j.defaultWorkspaceId?"⭐ ":"",ur(k.path,k.label)||k.path]},k.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(cs,{size:17})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),e.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children: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(k=>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:K,selectedKey:J}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${k.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:K,selectedWorkspaceKey:J,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:k.name}]},async()=>{const P=K.find($=>$.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(P),y(k.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[e.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:k.name}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},k.type)):(j.activeLauncherKind==="cli"?n:o).map(k=>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 K=j.activeLauncherKind==="cli"?"cli":"acp",{options:J,selectedKey:P}=qt({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${k.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${K.toUpperCase()}`,workspaceOptions:J,selectedWorkspaceKey:P,details:[{label:"Mode",value:K.toUpperCase()},{label:"Provider",value:k.displayName}],showArgsInput:!0,showModelInput:K==="acp",initialArgs:"",initialModel:"",providerType:k.type},async()=>{const $=J.find(z=>z.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption($),M(K,k.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:[k.icon?`${k.icon} `:"",k.displayName]}),e.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},k.type))})]}),u.message&&e.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${u.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[u.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:d,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(hr,{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:k=>{j.loadBrowsePath(k)},onConfirm:k=>{j.chooseCustomWorkspacePath(k),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&e.jsx(xn,{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:k=>j.setLaunchConfirmResumeId(k.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(k=>e.jsxs("option",{value:k.providerSessionId,disabled:!k.canResume,children:[k.title||k.providerSessionId," ",k.canResume?"":"(workspace missing)"]},k.providerSessionId))]})]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),p&&e.jsx(Io,{section:f,onSectionChange:g})]})}function Mo(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 Yd(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,u,m,f;const o=As(n)?"cli":as(n)?"acp":"ide";return{id:`${o}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(As(n)?n.cliName||n.type:as(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:as(n)?n.currentModel||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,currentModel:n.currentModel,timestamp:((f=(m=(u=(c=n.activeChat)==null?void 0:c.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:f.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function Xd(t,s){const r=new Map;for(const n of s){const o=Kt(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,g)=>g.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,u=Or(n),m=o.filter(h=>h.unread||h.requiresAction).length,f=Mo(n),p=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:dt(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:u,preview:c?Jc(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 Gs(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 Jd({conversations:t,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:u,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:C,setSelectedTabKey:I,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:l,resetMachineAction:S}){const M=a.useRef(null),N=a.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const w=Ms(x,c),v=Math.max(Date.now(),Gt(x),w.lastUpdated||0);Gs("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:Ve(x),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:Gt(x),readAt:v}),u(Kt(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,seenAt:v}).then(j=>{Gs("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:j})}).catch(j=>{Gs("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:j instanceof Error?j.message:String(j)})})},[c,u]);return a.useEffect(()=>{var w;if(!n){d("inbox"),I(((w=t[0])==null?void 0:w.tabKey)||null),M.current=null;return}if(i!=="chat"){M.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;M.current!==x&&(M.current=x,N(n))},[t,N,i,n,d,I]),a.useEffect(()=>{if(!m)return;const x=t.find(w=>w.tabKey===m);x&&(I(x.tabKey),d("chat"),f==null||f())},[t,f,m,d,I]),a.useEffect(()=>{if(!p)return;const x=s.find(w=>w.id===p);x&&(b(x.id),S(),y("machines"),l("inbox"),d("machine"),h==null||h())},[s,h,p,S,l,d,y,b]),a.useEffect(()=>{g&&(y(g),d("inbox"),C==null||C())},[C,g,d,y]),a.useEffect(()=>{const x=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);x.length!==0&&Gs("inbox_state",{screen:i,selectedTabKey:o,items:x.map(w=>{const v=Ms(w.conversation,c);return{liveState:v,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:Ve(w.conversation),serverBucket:v.inboxBucket,computedBucket:w.inboxBucket,serverUnread:v.unread,computedUnread:w.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:Gt(w.conversation)}})})},[r,c,i,o]),{markConversationRead:N}}function Zd(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function da(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qd(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function eu({sendDaemonCommand:t,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,u]=a.useState(""),[m,f]=a.useState(null),p=a.useCallback(()=>{i("idle"),u(""),f(null)},[]),h=a.useCallback(async(l,S,M)=>{var N;try{i("loading"),u(`Launching ${S}…`);const x={ideType:S,enableCdp:!0};(N=M==null?void 0:M.workspacePath)!=null&&N.trim()&&(x.workspace=M.workspacePath.trim()),await t(l,"launch_ide",x),i("done"),u(`${S} launch requested`)}catch(x){i("error"),u(x instanceof Error?x.message:"Launch IDE failed"),console.error("Launch IDE failed",x)}},[t]),g=a.useCallback(async(l,S,M)=>{if(S.trim())try{i("loading"),u(M!=null&&M.createIfMissing?"Creating folder…":"Saving workspace…");const N=await t(l,"workspace_add",{path:S.trim(),createIfMissing:(M==null?void 0:M.createIfMissing)===!0});if(N!=null&&N.success){i("done"),u(M!=null&&M.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((N==null?void 0:N.error)||"Could not save workspace")}catch(N){i("error"),u(N instanceof Error?N.message:"Could not save workspace")}},[t]),C=a.useCallback(async l=>{var S,M,N,x,w,v;try{i("loading"),u("Starting daemon upgrade…");const j=await t(l,"daemon_upgrade",{});if((S=j==null?void 0:j.result)!=null&&S.alreadyLatest){i("done"),u(`Already on v${((M=j==null?void 0:j.result)==null?void 0:M.version)||"latest"}.`);return}if((N=j==null?void 0:j.result)!=null&&N.upgraded||(x=j==null?void 0:j.result)!=null&&x.success){i("done"),u(`Upgrade to v${((w=j==null?void 0:j.result)==null?void 0:w.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((v=j==null?void 0:j.result)==null?void 0:v.error)||"Upgrade failed")}catch(j){i("error"),u(j instanceof Error?j.message:"Upgrade failed")}},[t]),I=a.useCallback(async(l,S,M,N)=>{var v,j,B;const x=Date.now(),w={machineId:l,kind:S,providerType:M,workspaceId:(N==null?void 0:N.workspaceId)||null,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:x};try{i("loading"),u(`Launching ${M}…`),f(w);const E={cliType:M};(v=N==null?void 0:N.workspacePath)!=null&&v.trim()?E.dir=N.workspacePath.trim():N!=null&&N.workspaceId&&(E.workspaceId=N.workspaceId),N!=null&&N.resumeSessionId&&(E.resumeSessionId=N.resumeSessionId),(j=N==null?void 0:N.args)!=null&&j.trim()&&(E.cliArgs=N.args.trim().split(/\s+/).filter(Boolean)),(B=N==null?void 0:N.model)!=null&&B.trim()&&(E.initialModel=N.model.trim());const W=await t(l,"launch_cli",E),T=(W==null?void 0:W.result)||W,G=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(W!=null&&W.success&&G){f(null),i("done"),u(`${M} launched`),s(`/dashboard?activeTab=${encodeURIComponent(G)}`);return}if(W!=null&&W.success){i("loading"),u(`${M} launch requested — waiting for session…`);return}f(null),i("error"),u((W==null?void 0:W.error)||(T==null?void 0:T.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(E){if(Qd(E)){i("loading"),u(`${M} launch requested — waiting for session…`);return}f(null),i("error"),u(E instanceof Error?E.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,t]),d=a.useCallback(async(l,S)=>{try{const M=await t(l,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),N=(M==null?void 0:M.result)??M;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(M){return console.error("Failed to list saved sessions on mobile:",M),[]}},[t]),b=a.useCallback(async(l,S)=>xr(t,l,S),[t]);a.useEffect(()=>{var N;if(!m)return;const l=da(m.workspacePath),S=r.find(x=>{var W,T,G,_;if(!x||x.type==="adhdev-daemon"||Zd(x.daemonId||x.id)!==m.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==m.kind||String(x.agentType||x.type||"")!==m.providerType)return!1;const B=String(x.providerSessionId||"");if(m.resumeSessionId&&B)return B===m.resumeSessionId;if(l){const k=da(x.workspace||x.runtimeWorkspaceLabel);return k?k===l:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((_=(G=(T=(W=x.activeChat)==null?void 0:W.messages)==null?void 0:T.at)==null?void 0:G.call(T,-1))==null?void 0:_.timestamp)||0)>=m.startedAt-5e3});if(!S)return;const M=typeof S.sessionId=="string"&&S.sessionId?S.sessionId:typeof S.instanceId=="string"&&S.instanceId?S.instanceId:(N=n.find(x=>x.routeId===S.id))==null?void 0:N.sessionId;M&&(f(null),i("done"),u(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(M)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const l=window.setTimeout(()=>{f(S=>!S||S.startedAt!==m.startedAt?S:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(l)},[m]);const y=a.useCallback(async(l,S)=>{if(S.kind==="ide"&&S.providerType){await h(l,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await I(l,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[h,I]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:I,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function tu({conversations:t,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:u,setSection:m,setMachineBackTarget:f}){const p=a.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),h=a.useCallback(y=>{const l=t.find(S=>S.routeId===y.routeId&&S.streamSource==="native");l&&(i(l.tabKey),c("chat"),n(l))},[t,n,c,i]),g=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),C=a.useCallback((y,l="inbox")=>{u(y),o(),m("machines"),f(l),c("machine")},[o,f,c,m,u]),I=a.useCallback(y=>{const l=Kt(y);l&&C(l,"chat")},[C]),d=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(y=>{m(y),c("inbox")},[c,m]);return{openConversation:p,openNativeConversation:h,backFromConversation:g,openMachine:C,openConversationMachine:I,backFromMachine:d,changeMachineSection:b}}function su(t){const s=t.trim();return s?s[0].toUpperCase():"?"}function ru(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 nu({conversations:t,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:l,isConnected:S,onShowHiddenConversation:M,onShowAllHiddenConversations:N,onHideConversation:x,onOpenNewSession:w}){const[v,j]=a.useState(()=>{var A;return((A=t[0])==null?void 0:A.tabKey)||null}),[B,E]=a.useState(()=>t[0]?"chat":"inbox"),[W,T]=a.useState("chats"),[G,_]=a.useState(null),[k,K]=a.useState("inbox"),J=ds(),P="0.8.39",$=a.useMemo(()=>t.find(A=>A.tabKey===v)||t[0]||null,[t,v]),z=a.useMemo(()=>$?r.find(A=>A.id===$.routeId):void 0,[r,$]),U=a.useMemo(()=>!$||$e($)||!We($)?null:ls($),[$]),Y=a.useMemo(()=>r.filter(A=>A.type==="adhdev-daemon").sort(sn),[r]),re=a.useMemo(()=>Y.find(A=>A.id===G)||null,[Y,G]),pe=a.useMemo(()=>Rs(r),[r]),O=pr({sendDaemonCommand:o,activeConv:$||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:u}),F=eu({sendDaemonCommand:o,navigate:J,ides:r,conversations:t}),D=a.useMemo(()=>t.map(A=>{const H=B==="chat"&&($==null?void 0:$.tabKey)===A.tabKey,ee=_s(A,pe,{hideOpenTaskCompleteUnread:!0,isOpenConversation:H}),Q=Gt(A),ce=Za(A);return{conversation:A,timestamp:Q,preview:ce,unread:ee.unread,requiresAction:ee.requiresAction,isWorking:ee.isWorking,inboxBucket:ee.inboxBucket}}),[t,pe,B,$]),{markConversationRead:me}=Jd({conversations:t,machineEntries:Y,items:D,selectedConversation:$,selectedTabKey:v,screen:B,liveSessionInboxState:pe,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:p,requestedMachineId:h,onRequestedMachineConsumed:g,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,setSelectedTabKey:j,setScreen:E,setSelectedMachineId:_,setSection:T,setMachineBackTarget:K,resetMachineAction:F.resetMachineAction}),ie=tu({conversations:t,selectedConversation:$,machineBackTarget:k,markConversationRead:me,resetMachineAction:F.resetMachineAction,setSelectedTabKey:j,setScreen:E,setSelectedMachineId:_,setSection:T,setMachineBackTarget:K}),X=a.useMemo(()=>D.filter(A=>A.requiresAction),[D]),be=a.useMemo(()=>D.filter(A=>A.unread&&!A.requiresAction),[D]),ne=a.useMemo(()=>D.filter(A=>!A.unread&&!A.requiresAction&&A.isWorking),[D]),le=a.useMemo(()=>D.filter(A=>!A.unread&&!A.requiresAction&&!A.isWorking),[D]),ae=a.useMemo(()=>re?D.filter(A=>Kt(A.conversation)===re.id):[],[D,re]),de=a.useMemo(()=>Yd(re,r),[r,re]),q=(re==null?void 0:re.version)||null,se=!!re&&!!q&&!0&&q!==P,te=a.useMemo(()=>(re==null?void 0:re.availableProviders)||[],[re]),ge=a.useMemo(()=>te.filter(A=>A.category==="cli"&&A.installed!==!1).map(A=>({type:A.type,displayName:A.displayName||A.type,icon:A.icon})),[te]),fe=a.useMemo(()=>te.filter(A=>A.category==="acp"&&A.installed!==!1).map(A=>({type:A.type,displayName:A.displayName||A.type,icon:A.icon})),[te]),R=a.useMemo(()=>Xd(Y,D),[D,Y]),xe=a.useCallback(async A=>{re&&await F.handleOpenRecent(re.id,A)},[F,re]);return e.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:B==="chat"&&$?e.jsx(zd,{selectedConversation:$,isAcp:$e($),isStandalone:u,selectedIdeEntry:z,actionLogs:n,userName:m,isSendingChat:O.isSendingChat,isFocusingAgent:O.isFocusingAgent,handleModalButton:O.handleModalButton,handleRelaunch:O.handleRelaunch,onBack:ie.backFromConversation,onOpenNativeConversation:ie.openNativeConversation,onOpenMachine:ie.openConversationMachine,onHideConversation:x,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:U,onSetCliViewMode:async A=>{if($&&U!==A)try{await o(Kt($)||$.routeId,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:lt($),mode:A})}catch(H){ru(H)?console.warn("Skipped CLI view mode switch:",H instanceof Error?H.message:String(H)):console.error("Failed to switch CLI view mode:",H)}},handleSendChat:O.handleSendChat,handleFocusAgent:O.handleFocusAgent}):B==="machine"&&re?e.jsx(qd,{selectedMachineEntry:re,selectedMachineConversations:ae,selectedMachineRecentLaunches:de,cliProviders:ge,acpProviders:fe,selectedMachineNeedsUpgrade:se,appVersion:P,machineAction:F.machineAction,isStandalone:u,section:W,showBottomNav:k==="inbox",onBack:ie.backFromMachine,onSectionChange:ie.changeMachineSection,onOpenConversation:ie.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>J(`/machines/${re.id}`),onMachineUpgrade:()=>F.handleMachineUpgrade(re.id),onLaunchDetectedIde:(A,H)=>F.handleLaunchDetectedIde(re.id,A,H),onAddWorkspace:(A,H)=>F.handleAddWorkspace(re.id,A,H),onBrowseDirectory:A=>F.handleBrowseDirectory(re.id,A),onLaunchWorkspaceProvider:(A,H,ee)=>F.handleLaunchWorkspaceProvider(re.id,A,H,ee),onListSavedSessions:A=>F.handleListSavedSessions(re.id,A)}):e.jsx(Ud,{section:W,attentionItems:X,unreadItems:be,workingItems:ne,completedItems:le,hiddenConversations:s,machineCards:R,getAvatarText:su,onOpenConversation:ie.openConversation,onShowConversation:M,onShowAllHidden:N,onOpenNewSession:w,onOpenMachine:ie.openMachine,onOpenSettings:()=>J("/settings"),onSectionChange:T,wsStatus:l,isConnected:S,isStandalone:u})})}function Tr(t,s){return!!(t<4&&s&&window.innerWidth>=768)}function au({conversations:t,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[u,m]=a.useState(!1),[f,p]=a.useState(null),h=a.useCallback(()=>{c.current=0,m(!1),p(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=a.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,m(!0))},[]),C=a.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Tr(s,r)){p("merge");return}const y=b.currentTarget.getBoundingClientRect(),l=b.clientX-y.left,S=y.width/3;l<S?p("split-left"):l>S*2?p("split-right"):p("merge")},[s,r]),I=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),p(null))},[]),d=a.useCallback(b=>{c.current=0,m(!1);const y=b.dataTransfer.getData("text/tab-key"),l=y?t.some(M=>M.tabKey===y):!1,S=f;if(p(null),i(),!!y){if(b.preventDefault(),S==="split-left"&&Tr(s,r)){r==null||r(y,"split-left");return}if(S==="split-right"&&Tr(s,r)){r==null||r(y,"split-right");return}if(l){o(y);return}n==null||n(y)}},[t,f,s,r,n,o,i]);return{dragOver:u,dropAction:f,resetDragState:h,handleDragEnter:g,handleDragOver:C,handleDragLeave:I,handleDrop:d}}function ou(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 iu({conversations:t,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[u,m]=a.useState(r??[]),[f,p]=a.useState(null),h=a.useRef(null),g=a.useRef(null),C=a.useRef(n),I=a.useRef(o);a.useEffect(()=>{C.current=n},[n]),a.useEffect(()=>{I.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(w=>{const v=ou(w,t);return v.length===w.length&&v.every((j,B)=>j===w[B])?w:v})},[t]);const d=a.useMemo(()=>{const w=f??u;if(w.length===0)return t;const v=new Map(w.map((j,B)=>[j,B]));return[...t].sort((j,B)=>{const E=v.get(j.tabKey)??999,W=v.get(B.tabKey)??999;return E-W})},[t,f,u]);a.useEffect(()=>{var v,j;if(d.length===0){i!==null&&(c(null),(v=C.current)==null||v.call(C,null));return}if(i&&d.some(B=>B.tabKey===i))return;const w=d[0].tabKey;w!==i&&(c(w),(j=C.current)==null||j.call(C,w))},[d,i]);const b=a.useMemo(()=>d.find(w=>w.tabKey===i),[d,i]),y=a.useCallback(w=>{var v;c(w),(v=C.current)==null||v.call(C,w)},[]),l=a.useCallback((w,v,j)=>{m(B=>{var G;const E=B.filter(_=>_!==w),W=E.indexOf(v);if(W<0)return B;const T=j==="left"?W:W+1;return E.splice(T,0,w),(G=I.current)==null||G.call(I,E),E}),p(null)},[]),S=a.useCallback((w,v,j)=>{const E=(u.length>0?u:t.map(G=>G.tabKey)).filter(G=>G!==w),W=E.indexOf(v);if(W<0)return;const T=j==="left"?W:W+1;E.splice(T,0,w),h.current=E,p(E)},[u,t]),M=a.useCallback(()=>{var v;const w=h.current;w&&(m(w),(v=I.current)==null||v.call(I,w))},[]),N=a.useCallback(()=>{h.current=null,p(null)},[]),x=a.useCallback(w=>{m(v=>{var B;const j=v.filter(E=>E!==w);return j.push(w),(B=I.current)==null||B.call(I,j),j})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:l,updatePreviewOrder:S,commitPreviewOrder:M,clearPreviewOrder:N,moveTabToEnd:x,setDraggingTabKey:w=>{g.current=w}}}function cu({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 hn({conversationsCount:t,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,detectedIdes:o,handleLaunchIde:i}){const c=!r&&!n,u=r?"Waiting for your daemon":n?"No conversations yet":"Connect your first machine",m=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:u}),e.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&e.jsx(Co,{}),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(Ea,{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 _o="adhdev-tab-shortcuts";function lu(){try{return JSON.parse(localStorage.getItem(_o)||"{}")}catch{return{}}}function Ao({enabled:t=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>lu()),[u,m]=a.useState(null),f=a.useCallback(h=>{const g=[];return h.metaKey&&g.push(o?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(o?"⌥":"Alt"),h.shiftKey&&g.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[o]),p=a.useCallback(h=>{c(h);try{localStorage.setItem(_o,JSON.stringify(h))}catch{}},[]);return a.useEffect(()=>{if(!t||!u)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){m(null);return}const C=f(g);if(!C)return;const I={...i};for(const[d,b]of Object.entries(I))b===C&&delete I[d];I[u]=C,p(I),m(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[t,u,i,p,f]),a.useEffect(()=>{if(!t)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[C,I]of Object.entries(i))if(s.includes(C)&&f(g)===I){g.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:u,setShortcutListening:m,saveShortcuts:p}}const du=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:u,onFocus:m,onSelectTab:f,onConversationActivated:p,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:C,onClearPreviewOrder:I,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:l,longPressTimer:S,isGroupActive:M}){const N=ms(s),x=N.isGenerating?"agent-tab-generating":N.isWaiting?"agent-tab-waiting":"",w=N.isReconnecting,v=a.useCallback(K=>{u.current=s.tabKey,b(s.tabKey),K.dataTransfer.setData("text/tab-key",s.tabKey),K.dataTransfer.effectAllowed="move"},[s.tabKey,u,b]),j=a.useCallback(()=>{u.current=null,b(null),C(),I(),d()},[u,b,C,I,d]),B=a.useCallback(K=>{const J=u.current;if(!(!J||J===s.tabKey)&&K.dataTransfer.types.includes("text/tab-key")){K.preventDefault(),K.stopPropagation();const P=K.currentTarget.getBoundingClientRect(),$=K.clientX<P.left+P.width/2?"left":"right";h(J,s.tabKey,$)}},[s.tabKey,u,h]),E=a.useCallback(K=>{K.preventDefault(),K.stopPropagation();const J=K.dataTransfer.getData("text/tab-key");if(J&&J!==s.tabKey){const P=K.currentTarget.getBoundingClientRect(),$=K.clientX<P.left+P.width/2?"left":"right";c.includes(J)?g(J,s.tabKey,$):y&&y(J)}I()},[s.tabKey,c,g,y,I]),W=a.useCallback(K=>{K.stopPropagation(),m(),f(s.tabKey),p(s)},[s,p,m,f]),T=a.useCallback(K=>{K.preventDefault(),l(K.clientX,K.clientY,s.tabKey)},[s.tabKey,l]),G=a.useCallback(K=>{const J=K.touches[0];S.current=setTimeout(()=>{l(J.clientX,J.clientY,s.tabKey)},600)},[s.tabKey,S,l]),_=a.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),k=["adhdev-dockview-tab",x,r&&"is-active",M&&"is-group-active",w&&"is-reconnecting"].filter(Boolean).join(" ");return e.jsxs("div",{"data-tabkey":s.tabKey,className:k,draggable:!0,onDragStart:v,onDragEnd:j,onDragOver:B,onDrop:E,onClick:W,onContextMenu:T,onTouchStart:G,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:N.isGenerating?e.jsx("div",{className:"tab-spinner"}):N.isWaiting?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):N.isConnecting?e.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("span",{className:"adhdev-dockview-tab-primary",title:Ve(s),children:Ve(s)}),e.jsx("span",{className:"adhdev-dockview-tab-meta",children:w?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(s)}):N.isConnecting?e.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[os(s),e.jsx("span",{className:"connecting-dots"})]}):os(s)})]}),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 uu({conversations:t,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:C,onReceiveTab:I,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[l,S]=a.useState(null),M=a.useRef(null),N=a.useRef(null),x=a.useMemo(()=>t.map(T=>T.tabKey),[t]);Ls("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:t.length,ctxMenuTab:(l==null?void 0:l.tabKey)||null});const{isMac:w,tabShortcuts:v,shortcutListening:j,setShortcutListening:B,saveShortcuts:E}=Ao({enabled:y,sortedTabKeys:t.map(T=>T.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!l)return;const T=G=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(G.target)||S(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[l]),a.useEffect(()=>{const T=N.current;if(!T)return;const G=_=>{Math.abs(_.deltaY)>Math.abs(_.deltaX)&&(_.preventDefault(),T.scrollLeft+=_.deltaY)};return T.addEventListener("wheel",G,{passive:!1}),()=>T.removeEventListener("wheel",G)},[]);const W=a.useCallback((T,G,_)=>{S({x:T,y:G,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:N,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none"},children:[t.map(T=>e.jsx(du,{conv:T,isActive:s===T.tabKey,isDraggedTab:o.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:y?v[T.tabKey]:void 0,conversationKeys:x,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:C,onReceiveTab:I,onOpenContextMenu:W,longPressTimer:M,isGroupActive:b},T.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:[y&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:T=>{T.stopPropagation(),B(l.tabKey),S(null)},children:["⌨ ",v[l.tabKey]?`Change shortcut (${v[l.tabKey]})`:"Set shortcut"]}),v[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 T={...v};delete T[l.tabKey],E(T),S(null)},children:"✕ Remove shortcut"})]}),d&&e.jsxs(e.Fragment,{children:[y&&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:()=>{d(l.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&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:()=>B(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",w?"⌘+1":"Ctrl+1",", ",w?"⌥+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 mu({conversations:t,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:p,onFocus:h,isSplitMode:g,numGroups:C,onMoveTab:I,onReceiveTab:d,style:b,detectedIdes:y,handleLaunchIde:l,onActiveTabChange:S,initialActiveTabId:M,initialTabOrder:N,onTabOrderChange:x,onHideTab:w,isFocused:v,allowTabShortcuts:j=!0}){const{sendCommand:B}=mt(),E=a.useRef(null),{activeTabId:W,activeConv:T,sortedConversations:G,draggingTabRef:_,selectTab:k,handleTabReorder:K,updatePreviewOrder:J,commitPreviewOrder:P,clearPreviewOrder:$,moveTabToEnd:z,setDraggingTabKey:U}=iu({conversations:t,initialActiveTabId:M,initialTabOrder:N,onActiveTabChange:S,onTabOrderChange:x}),Y=pr({sendDaemonCommand:o,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:u}),{dragOver:re,dropAction:pe,resetDragState:O,handleDragEnter:F,handleDragOver:D,handleDragLeave:me,handleDrop:ie}=au({conversations:t,numGroups:C,onMoveTab:I,onReceiveTab:d,onOwnTabDrop:z,onClearPreviewOrder:$}),X=T&&!$e(T)&&ls(T)==="terminal",be=a.useMemo(()=>T?s.find(q=>q.id===T.routeId):void 0,[s,T]),ne=a.useMemo(()=>T?n.filter(q=>q.routeId===T.tabKey):[],[n,T]),le=a.useMemo(()=>Rs(s),[s]),ae=a.useMemo(()=>new Set(G.filter(q=>uc(q,le,{isOpenConversation:q.tabKey===W})).map(q=>q.tabKey)),[W,le,G]);Ls("PaneGroup",{groupIndex:p,conversationCount:t.length,activeTabId:W,dragOver:re});const de=a.useCallback(q=>{q.streamSource==="agent-stream"&&q.agentType&&B(q.routeId,"focus_session",{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})},[B]);return e.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...b,outline:re?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[e.jsx(uu,{conversations:G,activeTabId:W,groupIndex:p,numGroups:C,unreadTabKeys:ae,draggingTabRef:_,onFocus:h,onSelectTab:k,onConversationActivated:de,onPreviewReorder:J,onReorderTab:K,onCommitPreviewOrder:P,onClearPreviewOrder:$,onDragStateReset:O,onDragTabKeyChange:U,onMoveTab:I,onReceiveTab:d,onHideTab:w,isGroupActive:v??!1,allowTabShortcuts:j}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:F,onDragOver:D,onDragLeave:me,onDrop:ie,children:[re&&e.jsx(cu,{dropAction:pe,canSplit:!!(C<4&&I)}),T?e.jsx(fn,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!X,ideEntry:be,terminalRef:E,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ne,userName:f,isInputActive:!g||!!v}):e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:e.jsx(hn,{conversationsCount:t.length,isSplitMode:g,isStandalone:u,hasRegisteredMachines:m,detectedIdes:y,handleLaunchIde:l})})]})]})}function pu({containerRef:t,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:u,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:C,focusedGroup:I,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:l,handleResizeStart:S,detectedIdes:M,handleLaunchIde:N,groupActiveTabIds:x,setGroupActiveTabIds:w,groupTabOrders:v,setGroupTabOrders:j,toggleHiddenTab:B,allowTabShortcuts:E=!0}){return e.jsx("div",{ref:t,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((W,T)=>{const G=s&&n.length===r?`${n[T]}%`:void 0;return e.jsxs(Ge.Fragment,{children:[s&&T>0&&e.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>S(T-1,_),onDoubleClick:()=>l(T),title:"Drag to resize · Double-click to merge",children:e.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),e.jsx(mu,{style:s?{flexBasis:G??`${100/r}%`,flexGrow:G?0:1,flexShrink:G?0:1}:void 0,conversations:W,clearedTabs:i,ides:c,actionLogs:u,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:p,isStandalone:h,hasRegisteredMachines:g,userName:C,groupIndex:T,isFocused:s&&I===T,onFocus:()=>d(T),isSplitMode:s,numGroups:r,onMoveTab:(_,k)=>{k==="left"&&T>0?b(_,T-1):k==="right"&&T<r-1?b(_,T+1):k==="split-left"&&r<4?y(_,T,"left"):k==="split-right"&&r<4&&y(_,T,"right")},onReceiveTab:_=>b(_,T),detectedIdes:T===0?M:void 0,handleLaunchIde:T===0?N:void 0,onActiveTabChange:_=>w(k=>(k[T]??null)===(_??null)?k:{...k,[T]:_}),initialActiveTabId:x[T],initialTabOrder:v[T],onTabOrderChange:_=>j(k=>{const K=k[T]||[];return K.length===_.length&&K.every((J,P)=>J===_[P])?k:{...k,[T]:_}}),onHideTab:B,allowTabShortcuts:E})]},T)})})}function To({doId:t,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,u]=a.useState(null);a.useEffect(()=>t?Fe.onScreenshot("ide-page",(p,h)=>{if(p!==t)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(h)}):void 0,[t]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var p;return t?((p=Fe.onStatus)==null?void 0:p.call(Fe,(h,g)=>{h===t&&g!=null&&g.screenshotUsage&&u(g.screenshotUsage)}))||(()=>{}):void 0},[t]),a.useEffect(()=>{i(null)},[t,s]),a.useEffect(()=>{const f=t?Fe.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 m=a.useCallback(async(f,p)=>{const h=t?Fe.get(t):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(f,p,s)},[t,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Po=a.createContext(null);function br(){const t=a.useContext(Po);if(!t)throw new Error("DashboardDockviewContext missing");return t}function er(t){return Ve(t)||t.tabKey}function fu(t){return`remote:${t}`}function Ps(t){return t.startsWith("remote:")}function xu(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 hu(t,s,r){var u;const n=[s];let o;for(const m of n){let f;for(const p of m){const h=t.addPanel({id:p.tabKey,component:"conversation",title:er(p),params:{kind:"conversation",tabKey:p.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??((u=s[0])==null?void 0:u.tabKey)??null;if(!i)return;const c=t.getPanel(i);c&&c.group.model.openPanel(c)}function ua(t,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...t.panels])Ps(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!==er(n)&&o.api.setTitle(er(n));continue}t.addPanel({id:n.tabKey,component:"conversation",title:er(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 ma(t,s,r){var m,f;const n=r?fu(r):null;for(const p of[...t.panels])Ps(p.id)&&(!n||p.id!==n)&&t.removePanel(p);if(!r||!n)return;const o=Rt(s,r);if(!o&&t.totalPanels===0)return;const i=t.getPanel(n),c=el(o);if(i){i.title!==c&&i.api.setTitle(c);return}const u=(o==null?void 0:o.tabKey)??((m=t.activePanel)==null?void 0:m.id)??((f=t.panels.find(p=>!Ps(p.id)))==null?void 0:f.id);t.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...u?{position:{referencePanel:u,direction:"right"},inactive:!0}:{}})}function bu({params:t,api:s}){var h;const r=br(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(t.tabKey),u=pr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(C=>i(C.isActive)),s.onDidActiveGroupChange(C=>{if(!s.isActive&&!C.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const C of g)C.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(g=>g.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(hn,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,detectedIdes:r.detectedIdes,handleLaunchIde:r.handleLaunchIde})});const p=!$e(c)&&ls(c)==="terminal";return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:e.jsx(fn,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:p,ideEntry:m,terminalRef:n,handleModalButton:u.handleModalButton,handleRelaunch:u.handleRelaunch,handleSendChat:u.handleSendChat,isSendingChat:u.isSendingChat,handleFocusAgent:u.handleFocusAgent,isFocusingAgent:u.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 gu({params:t}){var m;const s=br(),r=a.useMemo(()=>Rt([...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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||t.routeId.split(":")[0]||t.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:u}=To({doId:o,targetSessionId:r?an(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(Ba,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:u})}):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 yu(){const t=br();return e.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:e.jsx(hn,{conversationsCount:0,isSplitMode:!1,isStandalone:t.isStandalone,hasRegisteredMachines:t.hasRegisteredMachines,detectedIdes:t.detectedIdes,handleLaunchIde:t.handleLaunchIde})})}function vu(t){var C,I;xu(t);const s=br(),r=a.useCallback(d=>{"button"in d&&d.button!==0||t.api.setActive()},[t.api]);if(t.params.kind==="remote"){const d=Rt([...s.conversationsByTabKey.values()],t.params.routeId),b=((C=t.api.group.activePanel)==null?void 0:C.id)===t.api.id,y=t.api.isGroupActive;return e.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:t.api.title||"Remote","data-tab-key":(d==null?void 0:d.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:d!=null&&d.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:d.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=_s(n,s.liveSessionInboxState,{isOpenConversation:o}),u=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,p=c.isWaiting,h=c.unread,g=s.tabShortcuts[n.tabKey];return e.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${u?" is-reconnecting":""}`,title:Ve(n),"data-tab-key":t.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey})},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"}):p?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):u?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?e.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?e.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):e.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),e.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[e.jsx("div",{className:"adhdev-dockview-tab-primary",children:Ve(n)}),e.jsx("div",{className:"adhdev-dockview-tab-meta",children:u?e.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:os(n)}):m?e.jsx("span",{className:"adhdev-dockview-tab-connecting",children:os(n)}):e.jsx("span",{children:os(n)})})]}),g&&e.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function wu({visibleConversations:t,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:p,detectedIdes:h,handleLaunchIde:g,toggleHiddenTab:C,registerActionHandlers:I,onActiveTabChange:d,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:l,scrollToBottomRequest:S}){const{theme:M}=un(),{sendCommand:N}=mt(),x=a.useRef(null),w=a.useRef(null),v=a.useRef(!1),j=a.useRef(!1),B=a.useRef(!1),E=a.useRef(null),[W,T]=a.useState(null),[G,_]=a.useState(!1),[k,K]=a.useState(!1),J=a.useRef(null),P=a.useMemo(()=>ko(typeof window<"u"?window.innerWidth:1280),[]),$=a.useMemo(()=>new Map(t.map(A=>[A.tabKey,A])),[t]),z=a.useMemo(()=>Rs(r),[r]),U=a.useCallback(()=>{var A;(A=x.current)==null||A.focus()},[]),Y=a.useCallback(A=>{const H=x.current;if(!H)return;const ee=H.getPanel(A);ee&&(ee.group.model.openPanel(ee),ee.api.setActive())},[]),re=a.useCallback(A=>{const H=x.current,ee=H==null?void 0:H.activePanel,Q=(H==null?void 0:H.activeGroup)||(ee==null?void 0:ee.group);if(!H||!ee||!Q)return;const ce=Q.panels||[];if(ce.length<=1)return;const Ne=ce.findIndex(Re=>Re.id===ee.id);if(Ne<0)return;const Le=(Ne+A+ce.length)%ce.length,De=ce[Le];De&&(De.group.model.openPanel(De),De.api.setActive())},[]),pe=a.useCallback(A=>{var et;const H=x.current,ee=(H==null?void 0:H.activeGroup)||((et=H==null?void 0:H.activePanel)==null?void 0:et.group);if(!H||!ee)return;const Q=H.groups||[],ce=Q.find(Ke=>Ke.id===ee.id);if(!ce)return;const Ne=ce.element.getBoundingClientRect(),Le=Ne.left+Ne.width/2,De=Ne.top+Ne.height/2,Re=(Ke,Ce,He,Ye)=>Math.max(0,Math.min(Ce,Ye)-Math.max(Ke,He)),ot=Ke=>{const Ce=Ke.element.getBoundingClientRect(),He=Ce.left+Ce.width/2,Ye=Ce.top+Ce.height/2;let Xe=0,V=0,je=0,Se=!1;if(A==="left"?(Se=He<Le,Xe=Math.max(0,Ne.left-Ce.right),V=Math.abs(Ye-De),je=Re(Ne.top,Ne.bottom,Ce.top,Ce.bottom)):A==="right"?(Se=He>Le,Xe=Math.max(0,Ce.left-Ne.right),V=Math.abs(Ye-De),je=Re(Ne.top,Ne.bottom,Ce.top,Ce.bottom)):A==="above"?(Se=Ye<De,Xe=Math.max(0,Ne.top-Ce.bottom),V=Math.abs(He-Le),je=Re(Ne.left,Ne.right,Ce.left,Ce.right)):(Se=Ye>De,Xe=Math.max(0,Ce.top-Ne.bottom),V=Math.abs(He-Le),je=Re(Ne.left,Ne.right,Ce.left,Ce.right)),!Se)return Number.POSITIVE_INFINITY;const Te=je>0?0:120;return Xe*3+V+Te};let Qe=null,ze=Number.POSITIVE_INFINITY;for(const Ke of Q){if(Ke.id===ce.id)continue;const Ce=ot(Ke);Number.isFinite(Ce)&&(Ce>=ze||(ze=Ce,Qe=Ke))}return Qe||void 0},[]),O=a.useCallback(A=>{const H=pe(A);if(!H)return;const ee=H.activePanel||H.panels[0];ee&&(H.model.openPanel(ee),ee.api.setActive())},[pe]),F=a.useCallback((A,H)=>{const ee=x.current,Q=ee==null?void 0:ee.activePanel,ce=(ee==null?void 0:ee.activeGroup)||(Q==null?void 0:Q.group);if(!ee||!Q||!ce)return;let Ne=pe(A);!Ne&&(H!=null&&H.createGroupIfMissing)&&(Ne=ee.addGroup({referenceGroup:ce,direction:A})),Ne&&(Q.api.moveTo({group:Ne,position:"center"}),Q.group.model.openPanel(Q),Q.api.setActive())},[pe]),{isMac:D,tabShortcuts:me,shortcutListening:ie,setShortcutListening:X,saveShortcuts:be}=Ao({sortedTabKeys:t.map(A=>A.tabKey),onFocus:U,onSelectTab:Y}),ne=a.useCallback(()=>{var ee;const A=x.current;if(!A)return;const H=A.activePanel;if(H){if(Ps(H.id)){const Q=((ee=H.params)==null?void 0:ee.routeId)||H.id.slice(7),ce=Rt(t,Q);ce!=null&&ce.tabKey&&X(ce.tabKey);return}$.has(H.id)&&X(H.id)}},[$,X,t]);a.useEffect(()=>(I==null||I({setShortcutForActiveTab:ne,activatePreviousTabInGroup:()=>re(-1),activateNextTabInGroup:()=>re(1),splitActiveTabRight:()=>F("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>F("below",{createGroupIfMissing:!0}),focusLeftPane:()=>O("left"),focusRightPane:()=>O("right"),focusUpPane:()=>O("above"),focusDownPane:()=>O("below"),moveActiveTabToLeftPane:()=>F("left"),moveActiveTabToRightPane:()=>F("right"),moveActiveTabToUpPane:()=>F("above"),moveActiveTabToDownPane:()=>F("below")}),()=>I==null?void 0:I(null)),[re,O,F,I,ne]),a.useEffect(()=>{if(!W)return;const A=H=>{const ee=document.querySelector("[data-dockview-tab-context-menu]");ee&&ee.contains(H.target)||T(null)};return window.addEventListener("mousedown",A,!0),()=>window.removeEventListener("mousedown",A,!0)},[W]);const le=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:$,detectedIdes:h,handleLaunchIde:g,ides:r,isStandalone:u,hasRegisteredMachines:m,liveSessionInboxState:z,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:C,userName:p,scrollToBottomRequest:S,tabShortcuts:me,openTabContextMenu:({x:A,y:H,tabKey:ee})=>T({x:A,y:H,tabKey:ee})}),[n,s,$,h,g,r,u,m,z,o,c,i,C,p,S,me]),ae=a.useCallback(A=>{if(!A)return!1;const H=x.current;if(!H)return!1;const ee=H.getPanel(A);return ee?(ee.group.model.openPanel(ee),ee.api.setActive(),l==null||l(),!0):!1},[l]),de=a.useCallback(()=>{if(B.current)return!1;const A=ae(E.current);return A&&(B.current=!0),A},[ae]),q=a.useCallback(()=>{var H;const A=x.current;A&&Ad(P,{activeTabId:((H=A.activePanel)==null?void 0:H.id)??null,layout:A.toJSON()})},[P]),se=a.useCallback(()=>{const A=w.current;if(!A)return;const H=A.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection, .dv-render-overlay");for(const ee of H)ee.setAttribute("data-adhdev-force-hidden","true")},[]),te=a.useCallback(()=>{const A=w.current;if(!A)return;const H=A.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const ee of H)ee.removeAttribute("data-adhdev-force-hidden")},[]),ge=a.useCallback(()=>{const A=w.current;if(!A)return;const H=A.querySelectorAll(".dv-drop-target-container");for(const ce of H)ce.remove();const ee=A.querySelectorAll(".dv-drop-target-dropzone");for(const ce of ee)ce.remove();const Q=A.querySelectorAll(".dv-drop-target");for(const ce of Q)ce.classList.remove("dv-drop-target")},[]),fe=a.useCallback(()=>{_(!1),K(!1),te(),se(),ge(),!(typeof window>"u")&&(J.current!=null&&window.clearTimeout(J.current),window.requestAnimationFrame(()=>{se(),ge()}),J.current=window.setTimeout(()=>{se(),ge(),J.current=null},80))},[te,se,ge]),R=a.useCallback(A=>{var ee;x.current=A.api;const H=_d(P);E.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&A.api.fromJSON(H.layout,{reuseExistingPanels:!1}),j.current=!!(H!=null&&H.layout)&&!f&&t.length===0,j.current||(ua(A.api,t),ma(A.api,t,y)),A.api.totalPanels===0&&t.length>0?hu(A.api,t,b):!j.current&&!ae(b)&&de(),v.current=!0,A.api.onDidActivePanelChange(Q=>{var Ne;if(E.current=(Q==null?void 0:Q.id)??null,B.current=!0,Q&&Ps(Q.id)){const Le=((Ne=Q.params)==null?void 0:Ne.routeId)||Q.id.slice(7),De=Rt(t,Le);d((De==null?void 0:De.tabKey)??null),q();return}if(d((Q==null?void 0:Q.id)??null),q(),!Q)return;const ce=$.get(Q.id);(ce==null?void 0:ce.streamSource)==="agent-stream"&&ce.agentType&&N(ce.routeId,"focus_session",{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})}),A.api.onDidLayoutChange(()=>{q()}),A.api.onWillDragPanel(()=>{_(!0),K(!1),se()}),A.api.onWillDragGroup(()=>{_(!0),K(!1),se()}),A.api.onWillShowOverlay(()=>{te(),K(!0)}),A.api.onDidMovePanel(fe),A.api.onDidDrop(fe),d(((ee=A.api.activePanel)==null?void 0:ee.id)??null)},[ae,fe,te,$,f,P,se,ge,d,q,b,y,N,t]);a.useEffect(()=>{const A=x.current;if(!A||!v.current||j.current&&!f||(j.current&&(j.current=!1),ua(A,t),ma(A,t,y),b&&ae(b)))return;!A.activePanel&&A.panels[0]&&(A.panels[0].group.model.openPanel(A.panels[0]),A.panels[0].api.setActive()),!!(A.activePanel&&A.getPanel(A.activePanel.id))||de()},[ae,de,f,b,y,t]),a.useEffect(()=>{v.current&&ae(b)},[ae,b]),a.useEffect(()=>{if(!G||typeof window>"u")return;const A=()=>fe();return window.addEventListener("pointerup",A),window.addEventListener("mouseup",A),window.addEventListener("dragend",A),()=>{window.removeEventListener("pointerup",A),window.removeEventListener("mouseup",A),window.removeEventListener("dragend",A)}},[fe,G]),a.useEffect(()=>()=>{typeof window>"u"||J.current!=null&&window.clearTimeout(J.current)},[]),a.useEffect(()=>{const A=H=>{const ee=H.target;if(!ee)return;const Q=ee.querySelector("[data-tab-key]")||ee.closest("[data-tab-key]");if(Q){const ce=Q.getAttribute("data-tab-key");ce&&H.dataTransfer&&H.dataTransfer.setData("text/tab-key",ce)}};return window.addEventListener("dragstart",A),()=>window.removeEventListener("dragstart",A)},[]);const xe=M==="light"?xi:hi;return e.jsxs(Po.Provider,{value:le,children:[e.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx(fi,{className:`h-full min-h-0 min-w-0 adhdev-dockview${G?" is-dragging-dockview":""}${k?" is-showing-dockview-overlay":""}`,components:{conversation:bu,remote:gu},defaultTabComponent:vu,watermarkComponent:yu,onReady:R,singleTabMode:"default",tabAnimation:"smooth",theme:xe})}),W&&e.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:W.x,top:W.y},children:[e.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors",onClick:A=>{A.stopPropagation(),X(W.tabKey),T(null)},children:["⌨ ",me[W.tabKey]?`Change shortcut (${me[W.tabKey]})`:"Set shortcut"]}),me[W.tabKey]&&e.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{const A={...me};delete A[W.tabKey],be(A),T(null)},children:"✕ Remove shortcut"})]}),ie&&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:()=>X(null),children:e.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:A=>A.stopPropagation(),children:[e.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),e.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",D?"⌘+1":"Ctrl+1",", ",D?"⌥+A":"Alt+A",")"]}),e.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),e.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}const Lo="adhdev-recent-launch-args-v1",ju=8;function ku(t){return String(t||"").trim().replace(/\s+/g," ")}function Ro(t,s){return`${t.trim()}::${s.trim()}`}function Eo(){if(typeof window>"u")return{byKey:{}};try{const t=JSON.parse(window.localStorage.getItem(Lo)||"{}");return{byKey:typeof t.byKey=="object"&&t.byKey?t.byKey:{}}}catch{return{byKey:{}}}}function Nu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Lo,JSON.stringify(t))}catch{}}function $o(t,s){var i;const r=String(t||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Eo().byKey[Ro(r,n)])==null?void 0:i.items)||[]}function Do(t,s,r){var p;const n=String(t||"").trim(),o=String(s||"").trim(),i=ku(r);if(!n||!o||!i)return;const c=Eo(),u=Ro(n,o),m=((p=c.byKey[u])==null?void 0:p.items)||[],f=[i,...m.filter(h=>h!==i)].slice(0,ju);c.byKey[u]={items:f},Nu(c)}function Pr(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function Su(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function pa(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function fa(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 Cu(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function Iu(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 Mu(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 _u(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 Au({machineCards:t,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var G;const[u,m]=a.useState(n||((G=t[0])==null?void 0:G.id)||null),[f,p]=a.useState(""),[h,g]=a.useState(null),[C,I]=a.useState(!1);a.useEffect(()=>{var _;m(n||((_=t[0])==null?void 0:_.id)||null)},[n,t]);const d=a.useMemo(()=>t.find(_=>_.id===u)||t[0]||null,[u,t]),b=a.useMemo(()=>r.filter(_=>{if(_.type==="adhdev-daemon"||_.transport!=="pty")return!1;const k=Su(_.daemonId||_.id);return!!(d!=null&&d.id)&&k===d.id}),[d==null?void 0:d.id,r]),y=bo(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),l=y.diagnostics,S=y.loading,M=y.applyDiagnostics,N=a.useMemo(()=>{const _=new Map;for(const k of b){const K=s.find(J=>J.sessionId===k.sessionId||J.routeId===k.id);k.sessionId&&K&&_.set(k.sessionId,K)}return _},[b,s]),x=a.useCallback(async()=>{if(d!=null&&d.id){I(!0);try{const _=await o(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),k=Pr(_);if(!(k!=null&&k.success))throw new Error((k==null?void 0:k.error)||"Could not load session host diagnostics");M(k.diagnostics||k.result||null),p("")}catch(_){const k=_ instanceof Error?_.message:"Could not load session host diagnostics";p(k)}finally{I(!1)}}},[d==null?void 0:d.id,M,o]),w=a.useCallback(async(_,k)=>{if(!(d!=null&&d.id)||_==="session_host_stop_session"&&!window.confirm(`Stop ${k.displayName}?
|
|
41
|
+
This will terminate the hosted runtime.`))return;const K=`${_}:${k.sessionId}`;g(K);try{const J=await o(d.id,_,{sessionId:k.sessionId}),P=Pr(J);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const $=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${$}: ${k.displayName}`,"success"),await x()}catch(J){const P=J instanceof Error?J.message:"Session host action failed";p(P),nt.showToast(P,"warning")}finally{g(J=>J===K?null:J)}},[d==null?void 0:d.id,x,o]),v=a.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
42
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){g("session_host_prune_duplicate_sessions");try{const k=await o(d.id,"session_host_prune_duplicate_sessions",{}),K=Pr(k);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Duplicate prune failed");const J=K.result||{},P=Array.isArray(J.prunedSessionIds)?J.prunedSessionIds.length:0,$=typeof J.duplicateGroupCount=="number"?J.duplicateGroupCount:0;nt.showToast(`Pruned ${P} duplicate runtime(s) across ${$} group(s)`,"success"),await x()}catch(k){const K=k instanceof Error?k.message:"Duplicate prune failed";p(K),nt.showToast(K,"warning")}finally{g(k=>k==="session_host_prune_duplicate_sessions"?null:k)}}},[d==null?void 0:d.id,x,o]),j=a.useMemo(()=>[...(l==null?void 0:l.sessions)||[]].sort((_,k)=>(k.lastActivityAt||0)-(_.lastActivityAt||0)),[l==null?void 0:l.sessions]),B=a.useMemo(()=>_u(j),[j]),E=a.useMemo(()=>j.reduce((_,k)=>{var K;return _+(((K=k.attachedClients)==null?void 0:K.length)||0)},0),[j]),W=a.useMemo(()=>[...(l==null?void 0:l.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[l==null?void 0:l.recentLogs]),T=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(Bt,{size:14})," Session Host"]}),e.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.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:S||C,"aria-label":"Refresh session host",children:e.jsx(us,{size:16})}),e.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close session host",children:e.jsx(bt,{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===(d==null?void 0:d.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>m(_.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(Xt,{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:E})]}),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:fa(l.hostStartedAt)}),e.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:pa(l.hostStartedAt)})]})]}),W&&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(Xt,{size:13})," Latest warning"]}),e.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:W.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(lr,{size:14})," Hosted runtimes"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:h==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:h==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),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,re;const k=N.get(_.sessionId),K=b.find(pe=>pe.sessionId===_.sessionId),J=h===`session_host_resume_session:${_.sessionId}`,P=h===`session_host_restart_session:${_.sessionId}`,$=h===`session_host_stop_session:${_.sessionId}`,z=Iu(_.meta),U=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||(K==null?void 0:K.runtimeDisplayName)||(K==null?void 0:K.cliName)||_.providerType}),e.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Mu(_.lifecycle)}`,children:_.lifecycle}),z&&e.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:z})]}),e.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:_.workspaceLabel||(K==null?void 0:K.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:((re=_.writeOwner)==null?void 0:re.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Cu(_.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(Zr,{size:11})," ",_.attachedClients.length]})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",fa(_.lastActivityAt),_.osPid?` · pid ${_.osPid}`:""]}),U&&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:U})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[k&&e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(k),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:()=>{w("session_host_resume_session",_)},children:J?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!h,onClick:()=>{w("session_host_restart_session",_)},children:P?"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:()=>{w("session_host_stop_session",_)},children:$?"Stopping…":"Stop"})]})]},_.sessionId)})}),T.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:T.map(_=>{const k=j.find(K=>K.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:(k==null?void 0:k.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:pa(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]})]})]})]})})}function Lr(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 qs(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Tu({machines:t,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:u,onListSavedSessions:m,sendDaemonCommand:f,onOpenConversation:p}){var Ye,Xe;const h=$s(),g=a.useMemo(()=>[...t].sort(sn),[t]),[C,I]=a.useState(((Ye=g[0])==null?void 0:Ye.id)||""),d=a.useMemo(()=>g.find(V=>V.id===C)||g[0],[C,g]),b=a.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(V=>({id:V.id,path:V.path,label:V.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[l,S]=a.useState(""),[M,N]=a.useState(""),[x,w]=a.useState(Lr(g[0])),[v,j]=a.useState(""),[B,E]=a.useState(""),[W,T]=a.useState([]),[G,_]=a.useState(""),[k,K]=a.useState([]),[J,P]=a.useState(!1),[$,z]=a.useState(""),[U,Y]=a.useState(!1),[re,pe]=a.useState(!1),[O,F]=a.useState(null),[D,me]=a.useState(!1),[ie,X]=a.useState(""),[be,ne]=a.useState(!1),[le,ae]=a.useState(""),[de,q]=a.useState([]),[se,te]=a.useState(!1),[ge,fe]=a.useState(""),[R,xe]=a.useState(!1),A=a.useRef(null),H=a.useRef(0);a.useEffect(()=>{var V;!C&&((V=g[0])!=null&&V.id)&&I(g[0].id)},[C,g]),a.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||h(d.id,{minFreshMs:3e4}).catch(()=>{})},[h,d]);const ee=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(V=>V.category==="cli"&&V.installed!==!1),[d]),Q=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(V=>V.category==="acp"&&V.installed!==!1),[d]),ce=a.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(V=>({id:V.type,label:V.name||V.type,meta:V.running?"Detected locally":"Available to open"})),[d]),Ne=a.useMemo(()=>x==="cli"?ee.map(V=>({id:V.type,label:V.displayName||V.type,meta:"CLI provider"})):x==="acp"?Q.map(V=>({id:V.type,label:V.displayName||V.type,meta:"ACP provider"})):ce,[Q,x,ee,ce]);a.useEffect(()=>{var je;if(!d)return;if(A.current!==d.id){A.current=d.id,S(y||((je=b[0])==null?void 0:je.id)||"__home__"),N(""),w(Lr(d)),j(""),E(""),_(""),K([]),z(""),X("");return}S(Se=>{var Te;return Se==="__custom__"||Se==="__home__"||b.some(kt=>kt.id===Se)?Se:y||((Te=b[0])==null?void 0:Te.id)||"__home__"}),w(Se=>Se==="ide"&&ce.length>0||Se==="cli"&&ee.length>0||Se==="acp"&&Q.length>0?Se:Lr(d))},[Q.length,ee.length,y,ce.length,d,b]),a.useEffect(()=>{var V;x&&(Ne.some(je=>je.id===v)||j(((V=Ne[0])==null?void 0:V.id)||""))},[x,Ne,v]);const Le=a.useCallback(async(V,je)=>{const Se=H.current+1;return H.current=Se,P(!0),z(""),m(V,je).then(Te=>{H.current===Se&&K(Te)}).catch(Te=>{H.current===Se&&(K([]),z(Te instanceof Error?Te.message:"Could not load saved sessions"))}).finally(()=>{H.current===Se&&P(!1)})},[m]),De=a.useCallback((V,je)=>{T($o(V,je))},[]);a.useEffect(()=>{if(_(""),!d||!v||x==="ide"?T([]):De(d.id,v),x!=="cli"){K([]),z(""),P(!1);return}if(!d||!v){K([]),z(""),P(!1);return}Le(d.id,v)},[x,De,Le,d,v]),a.useEffect(()=>{if(!G)return;const V=k.find(je=>je.providerSessionId===G);V!=null&&V.canResume||_("")},[k,G]);const Re=l==="__custom__"?M.trim():l==="__home__"?"":((Xe=b.find(V=>V.id===l))==null?void 0:Xe.path)||"",ot=a.useCallback(V=>{const je=String(V.workspace||"").trim();if(!je)return;const Se=b.find(Te=>qs(Te.path)===qs(je));if(Se){S(Se.id),N("");return}S("__custom__"),N(je)},[b]),Qe=a.useCallback(V=>{const je=String(V.workspace||"").trim();if(!je)return{workspaceId:null,workspacePath:null};const Se=b.find(Te=>qs(Te.path)===qs(je));return Se?{workspaceId:Se.id,workspacePath:null}:{workspaceId:null,workspacePath:je}},[b]),ze=a.useMemo(()=>{var je;if(x!=="cli"||!d||!v)return null;const V=((je=ee.find(Se=>Se.type===v))==null?void 0:je.displayName)||v;return{routeId:d.id,daemonId:d.id,providerSessionId:G||void 0,transport:"pty",mode:"chat",agentName:V,agentType:v,status:"idle",title:V,messages:[],ideType:v,workspaceName:Re,displayPrimary:V,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${v}`,machineName:dt(d,{fallbackId:d.id})}},[x,ee,Re,d,G,v]),et=a.useCallback(()=>{var je,Se;if(!d)return;S("__custom__"),ne(!0),fe("");const V=fr(d.platform,[M.trim(),Re,(je=b.find(Te=>Te.id===y))==null?void 0:je.path,(Se=b[0])==null?void 0:Se.path]);te(!0),o(d.id,V).then(Te=>{ae(Te.path),N(Te.path),q(Te.directories)}).catch(Te=>{fe(Te instanceof Error?Te.message:"Could not load folder")}).finally(()=>te(!1))},[M,y,o,Re,d,b]),Ke=a.useCallback(V=>{d&&(te(!0),fe(""),o(d.id,V).then(je=>{ae(je.path),N(je.path),q(je.directories)}).catch(je=>{fe(je instanceof Error?je.message:"Could not load folder")}).finally(()=>te(!1)))},[o,d]),Ce=a.useCallback(async()=>{if(!d||!Re)return;xe(!0),X("");const V=await i(d.id,Re);if(xe(!1),!V.ok){X(V.error||"Could not save workspace");return}X("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Re,d]),He=a.useCallback(async()=>{if(!d||!x||!v)return;me(!0),X("");const V=B.trim()?B.trim().split(/\s+/).filter(Boolean):[],je=x==="ide"?await c(d.id,v,{workspacePath:Re||null}):await u(d.id,x,v,{workspaceId:l!=="__home__"&&l!=="__custom__"?l:null,workspacePath:l==="__custom__"&&Re||null,resumeSessionId:x==="cli"&&G?G:null,cliArgs:V});if(me(!1),!je.ok){X(je.error||"Could not start session");return}x!=="ide"&&B.trim()&&(Do(d.id,v,B),De(d.id,v)),n()},[x,B,De,n,c,u,Re,d,G,v,l]);return d?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(bt,{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:d.id,onChange:V=>I(V.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D,children:g.map(V=>e.jsx("option",{value:V.id,children:dt(V,{fallbackId:V.id})},V.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:D||!d,onClick:()=>pe(!0),children:[e.jsx(Bt,{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:et,disabled:D,children:"Browse…"})]}),e.jsxs("select",{value:l,onChange:V=>{const je=V.target.value;S(je),je==="__custom__"?et():X("")},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:[e.jsx("option",{value:"__home__",children:"Home directory"}),b.map(V=>e.jsxs("option",{value:V.id,children:[V.id===y?"⭐ ":"",ur(V.path,V.label)||V.path]},V.id)),e.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),e.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:l==="__home__"?"Launch without a workspace.":Re||"Select a workspace folder."}),l==="__custom__"&&Re&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:D,children:[e.jsx(cs,{size:14}),"Select folder"]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ce,disabled:D||R,children:R?"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:ee.length>0},{id:"ide",label:"IDE",enabled:ce.length>0},{id:"acp",label:"ACP",enabled:Q.length>0}].map(V=>e.jsx("button",{type:"button",className:`btn btn-sm ${x===V.id?"btn-primary":"btn-secondary"}`,onClick:()=>w(V.id),disabled:!V.enabled||D,children:V.label},V.id))})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:x==="ide"?"Choose IDE":x==="cli"?"Choose CLI provider":"Choose ACP provider"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ne.map(V=>e.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===V.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>j(V.id),disabled:D,children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:V.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:V.meta})]},V.id)),Ne.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:B,onChange:V=>E(V.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:D}),W.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:W.map(V=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>E(V),disabled:D,title:V,children:V},V))})]}),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:D||!d||!v||J,onClick:()=>{!d||!v||Le(d.id,v)},children:J?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:D||!d||!v,onClick:()=>{!d||!v||(Y(!0),Le(d.id,v))},children:"Open History"})]})]}),e.jsx("div",{className:"mt-2",children:e.jsxs("select",{value:G,onChange:V=>{const je=V.target.value;if(_(je),!je)return;const Se=k.find(Te=>Te.providerSessionId===je);!Se||!Se.canResume||ot(Se)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:D||J,children:[e.jsx("option",{value:"",children:"Start a new CLI session"}),k.map(V=>e.jsxs("option",{value:V.providerSessionId,disabled:!V.canResume,children:[V.title||V.providerSessionId,V.canResume?"":" (workspace missing)"]},V.providerSessionId))]})}),G&&(()=>{const V=k.find(je=>je.providerSessionId===G);return V?e.jsxs("div",{className:"mt-2 text-[11px] text-text-muted leading-relaxed",children:[e.jsx("div",{className:"font-mono break-all",children:V.providerSessionId}),e.jsxs("div",{className:"mt-1",children:[V.workspace||"Workspace unknown",V.currentModel?` · ${V.currentModel}`:""]})]}):null})(),$&&e.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:$}),!J&&!$&&k.length===0&&e.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved sessions found for this provider yet."})]}),ie&&e.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ie.includes("saved")||ie.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ie})]}),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: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:He,disabled:D||!x||!v||l==="__custom__"&&!Re,children:[e.jsx(en,{size:14}),D?"Starting…":"Start session"]})]})]})}),be&&e.jsx(hr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:de,busy:se,error:ge,onClose:()=>ne(!1),onNavigate:Ke,onConfirm:V=>{N(V),ae(V),S("__custom__"),ne(!1)}}),U&&ze&&e.jsx(cn,{activeConv:ze,ides:[],isCreatingChat:!1,isRefreshingHistory:J,savedSessions:k,isSavedSessionsLoading:J,isResumingSavedSessionId:O,onClose:()=>Y(!1),onNewChat:()=>{_(""),Y(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!v||Le(d.id,v)},onResumeSavedSession:V=>{if(!d||!v||O||!V.canResume)return;const je=Qe(V);_(V.providerSessionId),ot(V),F(V.providerSessionId),Y(!1),me(!0),X(""),u(d.id,"cli",v,{workspaceId:je.workspaceId,workspacePath:je.workspacePath,resumeSessionId:V.providerSessionId}).then(Se=>{if(!Se.ok){X(Se.error||"Could not resume session");return}n()}).finally(()=>{me(!1),F(Se=>Se===V.providerSessionId?null:Se)})}}),re&&d&&e.jsx(Au,{machineCards:[{id:d.id,label:dt(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Mo(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:f,onOpenConversation:V=>{pe(!1),n(),p(V)},onClose:()=>pe(!1)})]}):null}const Bo="adhdev-dashboard-action-shortcuts",Pu=1200,Lu={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Ru(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Ue(t,s){switch(t){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Ko(t){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Ue("openShortcutHelp",t)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Ue("hideCurrentTab",t)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Ue("toggleHiddenTabs",t)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Ue("openHistoryForActiveTab",t)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Ue("openRemoteForActiveTab",t)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:Ue("splitActiveTabRight",t)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:Ue("splitActiveTabDown",t)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Ue("focusLeftPane",t)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Ue("focusRightPane",t)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Ue("focusUpPane",t)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Ue("focusDownPane",t)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Ue("moveActiveTabToLeftPane",t)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Ue("moveActiveTabToRightPane",t)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Ue("moveActiveTabToUpPane",t)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Ue("moveActiveTabToDownPane",t)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Ue("triggerPrimaryApprovalAction",t)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Ue("triggerSecondaryApprovalAction",t)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Ue("triggerTertiaryApprovalAction",t)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Ue("setActiveTabShortcut",t)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Ue("selectPreviousGroupTab",t)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Ue("selectNextGroupTab",t)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Ue("toggleCliView",t)}]}function Eu(t){if(!(t instanceof HTMLElement))return!1;if(t.isContentEditable)return!0;const s=t.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function xa(t){const s=Object.fromEntries(Ko(t).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Bo)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Lu))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function $u(t){return t===" "?"Space":t==="Escape"?"Esc":t==="ArrowLeft"?"←":t==="ArrowRight"?"→":t==="ArrowUp"?"↑":t==="ArrowDown"?"↓":t.length===1?t.toUpperCase():t}function Du({enabled:t=!0,onTrigger:s}){const r=Ru(),[n,o]=a.useState(()=>xa(r)),[i,c]=a.useState(null),[u,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),p=a.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push($u(d.key)),b.join("+"))},[r]),h=a.useCallback(d=>{o(d);try{localStorage.setItem(Bo,JSON.stringify(d))}catch{}},[]);a.useEffect(()=>{const d=xa(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([l,S])=>d[l]===S)||h(d)},[n,r,h]);const g=a.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),C=a.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Pu))},[]);a.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const y=p(b);if(!y)return;const S=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(u.length===0&&S){m([y]);return}const N=[...u,y].slice(0,2).join(" "),x={...n};for(const[w,v]of Object.entries(x))v===N&&delete x[w];x[i]=N,h(x),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,p,h,i,u]),a.useEffect(()=>{if(!t||i)return;const d=b=>{if(b.defaultPrevented)return;const y=p(b);if(!y)return;const l=b.metaKey||b.ctrlKey||b.altKey;if(Eu(b.target)&&!l)return;const S=f.current.parts,M=l?[y]:[...S.slice(-1),y].slice(-2),N=M.join(" "),x=M[M.length-1],w=Object.entries(n).filter(([,W])=>!!W),v=w.find(([,W])=>W===N);if(v){b.preventDefault(),g(),s(v[0]);return}if(w.some(([,W])=>W.startsWith(`${N} `))){b.preventDefault(),f.current.parts=M,C();return}const B=w.find(([,W])=>W===x);if(B){b.preventDefault(),g(),s(B[0]);return}if(w.some(([,W])=>W.startsWith(`${x} `))){b.preventDefault(),f.current.parts=[x],C();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,C,t,p,s,g,i]),a.useEffect(()=>()=>g(),[g]);const I=a.useMemo(()=>Ko(r),[r]);return{isMac:r,actionDefinitions:I,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:u,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:h}}function Bu(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 Ku(t){return t instanceof Error?t.message:String(t||"")}function Wu(t){const s=Ku(t).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ou({showMobileChatMode:t,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:u,onStopCli:m,activeCliViewMode:f,onSetActiveCliViewMode:p,mobileChatConversations:h,hiddenConversations:g,ides:C,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,initialDataLoaded:S,userName:M,requestedMobileTabKey:N,onRequestedMobileTabConsumed:x,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:j,onRequestedMobileSectionConsumed:B,containerRef:E,isSplitMode:W,numGroups:T,groupSizes:G,groupedConvs:_,clearedTabs:k,focusedGroup:K,setFocusedGroup:J,moveTabToGroup:P,splitTabRelative:$,closeGroup:z,handleResizeStart:U,detectedIdes:Y,handleLaunchIde:re,groupActiveTabIds:pe,setGroupActiveTabIds:O,groupTabOrders:F,setGroupTabOrders:D,toggleHiddenTab:me,visibleConversations:ie,requestedDesktopTabKey:X,onRequestedDesktopTabConsumed:be,onDesktopActiveTabChange:ne,onHideConversation:le,onShowHiddenConversation:ae,onShowAllHiddenConversations:de,scrollToBottomRequest:q,machineEntries:se,onBrowseMachineDirectory:te,onSaveMachineWorkspace:ge,onLaunchMachineIde:fe,onLaunchMachineProvider:R,onListMachineSavedSessions:xe}){const A=Ge.useRef(null),[H,ee]=Ge.useState(!1),[Q,ce]=Ge.useState(!1),[Ne,Le]=Ge.useState(!1),[De,Re]=Ge.useState(!1),[ot,Qe]=Ge.useState(!1),[ze,et]=Ge.useState("quickstart"),[Ke,Ce]=Ge.useState("workspace"),He=!t&&!s,Ye=Ge.useCallback(ue=>{ee(ue),ue&&ce(!1)},[]),Xe=Ge.useCallback(ue=>{ce(ue),ue&&ee(!1)},[]),V=Ge.useCallback(()=>{et(ie.length===0?"quickstart":"shortcuts"),Ce("workspace"),Le(!0),ee(!1),ce(!1)},[ie.length]),je=Ge.useCallback(async ue=>{var yt;if(!r)return;const Ee=(yt=r.modalButtons)==null?void 0:yt[ue];if(!Ee)return;const gt=Ts(r);if(!gt)return;const _t=Ee.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),$t=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_t);try{await d(gt,"resolve_action",{button:Ee,action:$t?"approve":"reject",buttonIndex:ue,...is(r)})}catch(L){Wu(L)||console.error("[Shortcut approval] Failed:",L)}},[r,d]),{isMac:Se,actionDefinitions:Te,actionShortcuts:kt,shortcutListening:pt,shortcutListeningDraft:Et,setShortcutListening:Nt,setShortcutListeningDraft:It,saveShortcuts:St}=Du({enabled:He&&!Ne,onTrigger:ue=>{var Ee,gt,_t,$t,yt,L,Z,oe,ye,Me,Ie,Be,it;if(ue==="openShortcutHelp"){V();return}if(ue==="hideCurrentTab"){r&&le(r);return}if(ue==="toggleHiddenTabs"){Xe(!Q);return}if(ue==="openHistoryForActiveTab"){r&&!$e(r)&&c(r);return}if(ue==="openRemoteForActiveTab"){r&&!We(r)&&!$e(r)&&u(r);return}if(ue==="splitActiveTabRight"){(Ee=A.current)==null||Ee.splitActiveTabRight();return}if(ue==="splitActiveTabDown"){(gt=A.current)==null||gt.splitActiveTabDown();return}if(ue==="focusLeftPane"){(_t=A.current)==null||_t.focusLeftPane();return}if(ue==="focusRightPane"){($t=A.current)==null||$t.focusRightPane();return}if(ue==="focusUpPane"){(yt=A.current)==null||yt.focusUpPane();return}if(ue==="focusDownPane"){(L=A.current)==null||L.focusDownPane();return}if(ue==="moveActiveTabToLeftPane"){(Z=A.current)==null||Z.moveActiveTabToLeftPane();return}if(ue==="moveActiveTabToRightPane"){(oe=A.current)==null||oe.moveActiveTabToRightPane();return}if(ue==="moveActiveTabToUpPane"){(ye=A.current)==null||ye.moveActiveTabToUpPane();return}if(ue==="moveActiveTabToDownPane"){(Me=A.current)==null||Me.moveActiveTabToDownPane();return}if(ue==="triggerPrimaryApprovalAction"){je(0);return}if(ue==="triggerSecondaryApprovalAction"){je(1);return}if(ue==="triggerTertiaryApprovalAction"){je(2);return}if(ue==="setActiveTabShortcut"){(Ie=A.current)==null||Ie.setShortcutForActiveTab();return}if(ue==="selectPreviousGroupTab"){(Be=A.current)==null||Be.activatePreviousTabInGroup();return}if(ue==="selectNextGroupTab"){(it=A.current)==null||it.activateNextTabInGroup();return}!r||!We(r)||$e(r)||ue==="toggleCliView"&&p(f==="chat"?"terminal":"chat")}}),Mt=Ge.useCallback(()=>{Le(!1),Nt(null),It([])},[Nt,It]),ps=Ge.useMemo(()=>Ke==="all"?Te:Te.filter(ue=>Bu(ue)===Ke),[Te,Ke]),_e=Ge.useCallback(()=>{const ue=Object.fromEntries(Te.map(Ee=>[Ee.id,""]));St(ue)},[Te,St]),Wt=Ge.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ue=Object.fromEntries(Te.map(Ee=>[Ee.id,Ee.defaultShortcut]));St(ue)},[Te,St]);return Ge.useEffect(()=>{const ue=Ee=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ee.metaKey&&Ee.key.toLowerCase()==="w":Ee.ctrlKey&&Ee.key.toLowerCase()==="w")&&(Ee.preventDefault(),r&&le&&le(r))};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[r,le]),Ge.useEffect(()=>{if(!Ne||pt)return;const ue=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),Mt())};return window.addEventListener("keydown",ue,!0),()=>window.removeEventListener("keydown",ue,!0)},[Mt,Ne,pt]),Ge.useEffect(()=>{if(!He){Qe(!1);return}Qe(!0);const ue=window.setTimeout(()=>{Qe(!1)},1e4);return()=>window.clearTimeout(ue)},[He]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(nl,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:ie,hiddenConversations:g,onOpenHistory:c,onOpenConversation:ae,onHideConversation:le,onShowConversation:ae,onShowAllHidden:de,inboxOpen:H,onInboxOpenChange:Ye,hiddenOpen:Q,onHiddenOpenChange:Xe,onOpenNewSession:s?void 0:()=>Re(!0),onOpenRemote:()=>{!r||We(r)||$e(r)||u(r)},onStopCli:m,activeCliViewMode:f,onSetCliViewMode:p}),t?e.jsx(nu,{conversations:h,hiddenConversations:g,ides:C,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,userName:M,requestedActiveTabKey:N,onRequestedActiveTabConsumed:x,requestedMachineId:w,onRequestedMachineConsumed:v,requestedMobileSection:j,onRequestedMobileSectionConsumed:B,onOpenHistory:c,onOpenRemote:u,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:ae,onShowAllHiddenConversations:de,onOpenNewSession:()=>Re(!0)}):s?e.jsx(pu,{containerRef:E,isSplitMode:W,numGroups:T,groupSizes:G,groupedConvs:_,clearedTabs:k,ides:C,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,hasRegisteredMachines:se.length>0,userName:M,focusedGroup:K,setFocusedGroup:J,moveTabToGroup:P,splitTabRelative:$,closeGroup:z,handleResizeStart:U,detectedIdes:Y,handleLaunchIde:re,groupActiveTabIds:pe,setGroupActiveTabIds:O,groupTabOrders:F,setGroupTabOrders:D,toggleHiddenTab:me,allowTabShortcuts:!1}):e.jsx(wu,{visibleConversations:ie,clearedTabs:k,ides:C,actionLogs:I,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:l,hasRegisteredMachines:se.length>0,initialDataLoaded:S,userName:M,detectedIdes:Y,handleLaunchIde:re,toggleHiddenTab:me,registerActionHandlers:ue=>{A.current=ue},onActiveTabChange:ne,requestedActiveTabKey:X,onRequestedActiveTabConsumed:be,scrollToBottomRequest:q}),De&&e.jsx(Tu,{machines:se,conversations:h,ides:C,onClose:()=>Re(!1),onBrowseDirectory:te,onSaveWorkspace:ge,onLaunchIde:fe,onLaunchProvider:R,onListSavedSessions:xe,sendDaemonCommand:d,onOpenConversation:ue=>{Re(!1),ae(ue),ne(ue.tabKey)}}),Ne&&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:Mt,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:ue=>ue.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, plus grouped shortcuts you can tune."})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Mt,children:"Close"})]}),e.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(ue=>e.jsx("button",{type:"button",className:`btn btn-sm ${ze===ue.id?"btn-primary":"btn-secondary"}`,onClick:()=>et(ue.id),children:ue.label},ue.id))}),ze==="overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Se?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ze==="quickstart"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; one active pane is usually the cleanest default."]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),e.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ze==="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(ue=>e.jsx("button",{type:"button",className:`btn btn-sm ${Ke===ue.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ce(ue.id),children:ue.label},ue.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,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:Wt,children:"Reset to defaults"})]})]}),e.jsx("div",{className:"space-y-2",children:ps.map(ue=>e.jsx("div",{className:`rounded-xl border px-4 py-3 ${pt===ue.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:ue.label}),e.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ue.description}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",e.jsx("span",{className:"font-mono",children:ue.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:pt===ue.id?Et.length>0?`${Et.join(" ")} ...`:"Listening...":kt[ue.id]||"Off"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Nt(ue.id),It([])},children:pt===ue.id?"Listening":"Set"}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ee={...kt};Ee[ue.id]="",St(Ee)},children:"Disable"})]})]})},ue.id))}),e.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Se?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!t&&e.jsxs("button",{type:"button",onClick:V,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 ${ot?"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:"?"}),ot&&e.jsx("span",{children:"Guide"})]})]})}const Rr=[{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 zu({onClose:t}){const[s,r]=a.useState(0),n=Rr[s],o=s===Rr.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(bt,{size:20})}),e.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Rr.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:`
|
|
43
43
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
44
44
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
45
|
-
`})]})}function Uu({hasExtensions:t,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab: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",m=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)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"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 Hu({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,d]=a.useState(()=>i||"native"),m=a.useMemo(()=>so(s),[s]),f=a.useMemo(()=>t?ln(t,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,m,r]),p=a.useMemo(()=>f.find(b=>b.streamSource==="native"),[f]),h=a.useMemo(()=>f.filter(b=>b.streamSource==="agent-stream"),[f]),g=a.useMemo(()=>t?Rt(f,t.id):null,[f,t]);a.useEffect(()=>{i&&d(i)},[i]),a.useEffect(()=>{if(i||!g)return;const b=g.streamSource==="native"?"native":g.tabKey;!b||c===b||c==="native"&&d(b)},[c,g,i]),a.useEffect(()=>{var b;c!=="native"&&(h.some(y=>y.tabKey===c)||d(((b=h[0])==null?void 0:b.tabKey)||"native"))},[c,h]),a.useEffect(()=>{c==="native"&&(p||h[0]&&d(h[0].tabKey))},[c,p,h]);const C=a.useMemo(()=>c==="native"&&p?p:h.find(b=>b.tabKey===c)||g||p||h[0],[c,p,g,h]),I=a.useMemo(()=>h.map(b=>({tabKey:b.tabKey,title:eo(b)||o,status:b.status})),[h,o]),l=a.useCallback(b=>{if(b)return f.find(y=>y.sessionId===b||y.routeId===b||y.tabKey===b)},[f]);return{activeChatTab:c,setActiveChatTab:d,activeConv:C,conversations:f,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:l}}function Fu({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:d,setActionLogs:m,isStandalone:f,userName:p,onOpenHistory:h,onConversationChange:g,onClose:C}){const[I,l]=a.useState("split"),[b,y]=a.useState(()=>Lt(t)?"native":t.tabKey),u=a.useRef(null),S=a.useMemo(()=>s||r.find(L=>L.id===t.routeId),[t.routeId,s,r]),_=a.useMemo(()=>Oe((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:N,extensionTabs:x,hasExtensions:w}=Hu({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:Lt(t)?void 0:t.tabKey}),v=a.useMemo(()=>S?Rt(N,S.id):null,[S,N]);a.useEffect(()=>{const L=u.current,$={routeId:t.routeId,tabKey:t.tabKey,streamSource:t.streamSource};if(u.current=$,!(L&&L.routeId===$.routeId&&L.tabKey===$.tabKey&&L.streamSource===$.streamSource)){if(Lt(t)){y("native");return}y(t.tabKey)}},[t.routeId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(b==="native"){if(N.some(L=>L.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!N.some(L=>L.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[N,b,v]);const j=a.useMemo(()=>b==="native"?N.find(L=>L.streamSource==="native")||t:N.find(L=>L.tabKey===b)||t,[t,N,b]),B=go(j),E=a.useMemo(()=>B.status||B.modalMessage||B.modalButtons?{...j,...B.status?{status:B.status}:{},...B.modalMessage!==void 0?{modalMessage:B.modalMessage}:{},...B.modalButtons!==void 0?{modalButtons:B.modalButtons}:{}}:j,[j,B]),W=nr(E),T=pr({sendDaemonCommand:c,activeConv:E,setLocalUserMessages:d,setActionLogs:m,isStandalone:f}),{connScreenshot:G,screenshotUsage:A,handleRemoteAction:k}=To({doId:W,targetSessionId:an(E),connState:E.connectionState||"new",viewMode:I}),K=a.useMemo(()=>o.filter(L=>L.routeId===E.tabKey),[o,E.tabKey]);a.useEffect(()=>{g==null||g(E)},[E,g]),a.useEffect(()=>{const L=$=>{$.key==="Escape"&&C()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[C]);const J=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:C,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:J,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(ut,{size:16})}),e.jsx("span",{className:"truncate",children:mr(j)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:C,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:()=>l(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?e.jsx(Bi,{size:15}):e.jsx(ut,{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(Qr,{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:C,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(Uu,{hasExtensions:w,ideName:_||"IDE",activeChatTab:b,extensionTabs:x,onSelectTab:y}),e.jsx(Oa,{activeConv:E,onModalButton:T.handleModalButton}),e.jsx(zr,{activeConv:E,ideEntry:S,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:K,userName:p})]}),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(Ba,{addLog:()=>{},connState:E.connectionState||"new",connScreenshot:G,screenshotUsage:A,transportType:E.transport,onAction:k})})]})]})})}function Vu({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Qc(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 Gu({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:d,onCloseHistory:m,onNewHistoryChat:f,onSwitchHistorySession:p,onRefreshHistory:h,onResumeSavedHistorySession:g,remoteDialogConv:C,remoteDialogIdeEntry:I,connectionStates:l,actionLogs:b,localUserMessages:y,sendDaemonCommand:u,setLocalUserMessages:S,setActionLogs:_,isStandalone:N,userName:x,onOpenRemoteHistory:w,onRemoteConversationChange:v,onCloseRemoteDialog:j,cliStopDialogOpen:B,cliStopTargetConv:E,onCancelCliStop:W,onStopCliNow:T,onSaveCliAndStop:G,toasts:A,onDismissToast:k,onClickToast:K,showOnboarding:J,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:m,onNewChat:f,onSwitchSession:p,onRefreshHistory:h,onResumeSavedSession:g}),C&&e.jsx(Fu,{activeConv:C,ideEntry:I,ides:r,connectionStates:l,actionLogs:b,localUserMessages:y,sendDaemonCommand:u,setLocalUserMessages:S,setActionLogs:_,isStandalone:N,userName:x,onOpenHistory:w,onConversationChange:v,onClose:j}),B&&E&&(We(E)||$e(E))&&e.jsx(Vu,{activeConv:E,canSaveAndStop:We(E)&&!$e(E)&&!!(($=E.resume)!=null&&$.supported),onCancel:W,onStopNow:T,onSaveAndStop:G}),e.jsx(to,{toasts:A,onDismiss:k,onClickToast:K}),J&&e.jsx(zu,{onClose:L})]})}function qu({daemons:t,targetVersion:s,upgradingDaemons:r,onUpgrade:n,onDismiss:o}){return t.length===0?null:e.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[e.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:"var(--status-warning)"},children:e.jsx(us,{size:14})}),e.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[e.jsxs("span",{children:["Update available",s?e.jsxs(e.Fragment,{children:[": ",e.jsxs("strong",{children:["v",s]})]}):null]}),t.map(i=>{const c=dt(i,{fallbackId:i.id}),d=r[i.id],m=i.version||i.daemonVersion||"unknown";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 15%, transparent)"},children:[e.jsx("span",{className:"font-medium text-text-primary",children:c}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:"var(--status-warning)"},children:"upgrading…"}):d==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>n(i.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},onClick:()=>n(i.id),children:"Upgrade"})]},i.id)})]}),e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:e.jsx(bt,{size:16})})]})}function Yu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function ha(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ju(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 Zu(){var vn,wn,jn,kn,Nn;const{sendCommand:t}=mt(),s=$s(),r=Xr(),n=ds(),[o,i]=bi(),c=o.get("activeTab"),d=((vn=r.state)==null?void 0:vn.openRemoteForTabKey)||null,m=((wn=r.state)==null?void 0:wn.openMachineId)||null,f=((jn=r.state)==null?void 0:jn.mobileSection)||null,p=Xa(),h=p.ides||[],g=p.initialLoaded??!0,{updateRouteChats:C,setToasts:I}=p,[l,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=p.toasts||[],u=p.wsStatus||"connected",S=p.isConnected??!0,_=p.connectionStates||{},N=p.showReconnected||!1,{groupAssignments:x,setGroupAssignments:w,focusedGroup:v,setFocusedGroup:j,groupActiveTabIds:B,setGroupActiveTabIds:E,groupTabOrders:W,setGroupTabOrders:T,groupSizes:G,setGroupSizes:A,isMobile:k,hasHydratedStoredLayout:K,hydrateStoredLayout:J}=Ld(),[L,$]=a.useState(!1),[z,H]=a.useState(!1),[Y,re]=a.useState(null),[pe,O]=a.useState([]),[F,D]=a.useState(!1),[me,ie]=a.useState(null),[X]=a.useState(()=>ho()),[be,ne]=a.useState([]),[le,ae]=a.useState({}),[de,q]=a.useState({}),[se,te]=a.useState(null),[ge,fe]=a.useState(null),[R,xe]=a.useState(null),M=a.useRef(null);Ps("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(x).length,localMessageTabs:Object.keys(le).length,actionLogCount:be.length});const U=h.find(he=>he.type==="adhdev-daemon"),ee=(U==null?void 0:U.detectedIdes)||[],Q=a.useMemo(()=>h.filter(he=>he.type==="adhdev-daemon").sort(sn),[h]),ce=!!U;a.useEffect(()=>{!U||!(!U.detectedIdes||!U.availableProviders||!U.recentLaunches||!U.workspaces)||s(U.id,{minFreshMs:3e4}).catch(()=>{})},[U,s]);const Ne=(U==null?void 0:U.terminalBackend)||null,Pe=U?dt(U,{fallbackId:U.id}):null,De=(U==null?void 0:U.id)||null,{hiddenTabs:Re,hideTab:ot,toggleTab:Qe,showTab:ze,showAllTabs:et}=ud(),{chatIdes:Ke,conversations:Ce,visibleConversations:Ue,visibleTabKeys:Ye,resolveConversationBySessionId:Xe,resolveConversationByTarget:V}=jd({ides:h,connectionStates:_,localUserMessages:le,clearedTabs:de,hiddenTabs:Re}),je=a.useMemo(()=>Rs(h),[h]),Se=a.useRef(null),{containerRef:Te,normalizedGroupAssignments:kt,numGroups:pt,isSplitMode:Et,groupedConvs:Nt,moveTabToGroup:It,closeGroup:St,handleResizeStart:_t,splitTabRelative:ps}=Wd({groupAssignments:x,setGroupAssignments:w,setFocusedGroup:j,setGroupActiveTabIds:E,setGroupTabOrders:T,groupSizes:G,setGroupSizes:A,isMobile:k,visibleConversations:Ue,visibleTabKeys:Ye}),Ae=a.useMemo(()=>{var ke,we;if(!k){if(se){const ve=Ce.find(Me=>Me.tabKey===se);if(ve)return ve}return Ue[0]}const he=B[v];if(he){const ve=Ce.find(Me=>Me.tabKey===he);if(ve)return ve}return((ke=Nt[v])==null?void 0:ke[0])||((we=Nt[0])==null?void 0:we[0])},[se,k,B,v,Ce,Nt,Ue]);a.useEffect(()=>{if(k){Se.current=null;return}if(!(Ae!=null&&Ae.sessionId)){Se.current=null;return}const he=`${Ae.tabKey}:${Ae.sessionId}`;if(Se.current===he)return;const ke=()=>{if(document.visibilityState!=="visible"||Se.current===he)return;Se.current=he;const we=_s(Ae,je),ve=Math.max(Date.now(),Gt(Ae),we.lastUpdated||0);t(Ae.daemonId||Ae.routeId,"mark_session_seen",{sessionId:Ae.sessionId,seenAt:ve}).catch(()=>{})};if(document.visibilityState==="visible"){const we=setTimeout(ke,1500),ve=()=>{document.visibilityState!=="visible"&&clearTimeout(we)};return document.addEventListener("visibilitychange",ve),()=>{clearTimeout(we),document.removeEventListener("visibilitychange",ve)}}else{const we=()=>{document.visibilityState==="visible"&&(setTimeout(ke,800),document.removeEventListener("visibilitychange",we))};return document.addEventListener("visibilitychange",we),()=>{document.removeEventListener("visibilitychange",we)}}},[Ae,k,je,t]);const{requestedDesktopTabKey:Wt,requestedMobileTabKey:ue,consumeRequestedActiveTab:Ee}=kd({isMobile:k,urlActiveTab:c,resolveConversationBySessionId:Xe,setSearchParams:i}),{remoteDialogConv:gt,remoteDialogIdeEntry:At,remoteDialogActiveConv:$t,setRemoteDialogActiveConv:yt,openRemoteDialog:P,closeRemoteDialog:Z}=Ed({isMobile:k,location:r,navigate:n,requestedRemoteTabTarget:d,requestedDesktopTabKey:Wt,conversations:Ce,ides:h,resolveConversationByTarget:V}),oe=$t||gt||Ae,ye=!!oe&&We(oe)&&!$e(oe),_e=a.useMemo(()=>{if(!oe||!ye)return null;const he=oe.daemonId||oe.routeId||"",ke=lt(oe);return`${he}:${ke}`},[oe,ye]),Ie=a.useMemo(()=>Ue,[Ue]),Be=k&&X==="chat",it=a.useMemo(()=>Ce.filter(he=>Re.has(he.tabKey)),[Ce,Re]),at=a.useCallback(he=>{const ke=new URLSearchParams(o);ke.set("activeTab",he),i(ke,{replace:!0})},[o,i]),Je=a.useCallback(async(he,ke)=>xr(t,he,ke),[t]),fs=a.useCallback(async(he,ke)=>{if(!ke.trim())return{ok:!1,error:"Choose a workspace path first."};try{const we=await t(he,"workspace_add",{path:ke.trim()});return we!=null&&we.success?{ok:!0}:{ok:!1,error:(we==null?void 0:we.error)||"Could not save workspace"}}catch(we){return{ok:!1,error:we instanceof Error?we.message:"Could not save workspace"}}},[t]),Wo=a.useCallback(async(he,ke,we)=>{var ve;try{const Me={ideType:ke,enableCdp:!0};(ve=we==null?void 0:we.workspacePath)!=null&&ve.trim()&&(Me.workspace=we.workspacePath.trim());const Ze=await t(he,"launch_ide",Me);return!(Ze!=null&&Ze.success)&&(Ze==null?void 0:Ze.success)!==void 0?{ok:!1,error:(Ze==null?void 0:Ze.error)||"Could not launch IDE"}:(xe({machineId:he,kind:"ide",providerType:ke,workspacePath:(we==null?void 0:we.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Me){return{ok:!1,error:Me instanceof Error?Me.message:"Could not launch IDE"}}},[t]),Oo=a.useCallback(async(he,ke,we,ve)=>{var Ze,xs,ts;const Me=Date.now();try{const vt={cliType:we};(Ze=ve==null?void 0:ve.workspacePath)!=null&&Ze.trim()?vt.dir=ve.workspacePath.trim():ve!=null&&ve.workspaceId&&(vt.workspaceId=ve.workspaceId),(xs=ve==null?void 0:ve.resumeSessionId)!=null&&xs.trim()&&(vt.resumeSessionId=ve.resumeSessionId.trim()),Array.isArray(ve==null?void 0:ve.cliArgs)&&ve.cliArgs.length>0&&(vt.cliArgs=ve.cliArgs),(ts=ve==null?void 0:ve.initialModel)!=null&&ts.trim()&&(vt.initialModel=ve.initialModel.trim());const tt=await t(he,"launch_cli",vt),ct=(tt==null?void 0:tt.result)||tt,hs=(ct==null?void 0:ct.sessionId)||(ct==null?void 0:ct.id);return tt!=null&&tt.success&&hs?(at(hs),{ok:!0}):tt!=null&&tt.success?(xe({machineId:he,kind:ke,providerType:we,workspacePath:(ve==null?void 0:ve.workspacePath)||null,resumeSessionId:(ve==null?void 0:ve.resumeSessionId)||null,startedAt:Me}),{ok:!0}):{ok:!1,error:(tt==null?void 0:tt.error)||(ct==null?void 0:ct.error)||`Could not launch ${ke.toUpperCase()} session`}}catch(vt){return Xu(vt)?(xe({machineId:he,kind:ke,providerType:we,workspacePath:(ve==null?void 0:ve.workspacePath)||null,resumeSessionId:(ve==null?void 0:ve.resumeSessionId)||null,startedAt:Me}),{ok:!0}):{ok:!1,error:vt instanceof Error?vt.message:`Could not launch ${ke.toUpperCase()} session`}}},[at,t]),zo=a.useCallback(async(he,ke)=>{if(!he||!ke)return[];try{const we=await t(he,"list_saved_sessions",{providerType:ke,kind:"cli",limit:30}),ve=(we==null?void 0:we.result)??we;return Array.isArray(ve==null?void 0:ve.sessions)?ve.sessions:[]}catch(we){return console.error("List saved sessions failed",we),[]}},[t]);a.useEffect(()=>{var ve;if(!R)return;const he=ha(R.workspacePath),ke=h.find(Me=>{var tt,ct,hs,Sn;if(!Me||Me.type==="adhdev-daemon"||Yu(Me.daemonId||Me.id)!==R.machineId||(Ms(Me)?"cli":as(Me)?"acp":"ide")!==R.kind||String(Me.agentType||Me.type||"")!==R.providerType)return!1;if(R.resumeSessionId)return String(Me.providerSessionId||"")===R.resumeSessionId;if(he){const yr=ha(Me.workspace||Me.runtimeWorkspaceLabel);return yr?yr===he:!1}return Number(Me.lastUpdated||Me._lastUpdate||Me.timestamp||((Sn=(hs=(ct=(tt=Me.activeChat)==null?void 0:tt.messages)==null?void 0:ct.at)==null?void 0:hs.call(ct,-1))==null?void 0:Sn.timestamp)||0)>=R.startedAt-5e3});if(!ke)return;const we=typeof ke.sessionId=="string"&&ke.sessionId?ke.sessionId:typeof ke.instanceId=="string"&&ke.instanceId?ke.instanceId:(ve=Ce.find(Me=>Me.routeId===ke.id))==null?void 0:ve.sessionId;we&&(xe(null),at(we))},[Ce,at,h,R]),a.useEffect(()=>{if(!R)return;const he=window.setTimeout(()=>{xe(ke=>!ke||ke.startedAt!==R.startedAt?ke:null)},45e3);return()=>window.clearTimeout(he)},[R]),md({visibleConversations:Ue,clearedTabs:de,setClearedTabs:q,setActionLogs:ne}),Nd({ides:h,sendDaemonCommand:t,setToasts:I,setLocalUserMessages:ae,resolveConversationByTarget:V});const{isRefreshingHistory:Uo,handleLaunchIde:Ho,handleRefreshHistory:Fo}=ea({sendDaemonCommand:t,activeConv:Ae,chats:(kn=h.find(he=>he.id===(Ae==null?void 0:Ae.routeId)))==null?void 0:kn.chats,updateRouteChats:C,setToasts:I,setLocalUserMessages:ae,setClearedTabs:q}),{isCreatingChat:Vo,isRefreshingHistory:Go,handleSwitchSession:qo,handleNewChat:Yo,handleRefreshHistory:Xo}=ea({sendDaemonCommand:t,activeConv:oe,chats:(Nn=h.find(he=>he.id===(oe==null?void 0:oe.routeId)))==null?void 0:Nn.chats,updateRouteChats:C,setToasts:I,setLocalUserMessages:ae,setClearedTabs:q}),gr=a.useCallback(async()=>{if(!(!oe||!ye||F)){D(!0);try{const he=oe.daemonId||oe.routeId,ke=lt(oe),we=await t(he,"list_saved_sessions",{agentType:ke,providerType:ke,kind:"cli",limit:50}),ve=(we==null?void 0:we.result)??we;O(Array.isArray(ve==null?void 0:ve.sessions)?ve.sessions:[])}catch(he){console.error("Refresh saved sessions failed",he),O([])}finally{D(!1)}}},[oe,F,ye,t]);a.useEffect(()=>{if(!L){M.current=null;return}if(!ye){M.current=null,O([]),D(!1);return}!_e||F||M.current!==_e&&(M.current=_e,gr())},[gr,L,F,ye,_e]);const Jo=a.useCallback(async he=>{if(!oe||!ye||!he.providerSessionId||!he.workspace)return;const ke=oe.daemonId||oe.routeId,we=lt(oe);try{ie(he.providerSessionId);const ve=await t(ke,"launch_cli",{cliType:we,dir:he.workspace,resumeSessionId:he.providerSessionId,initialModel:he.currentModel}),Me=(ve==null?void 0:ve.result)??ve,Ze=typeof(Me==null?void 0:Me.sessionId)=="string"?Me.sessionId:typeof(Me==null?void 0:Me.id)=="string"?Me.id:"";Ze&&i(xs=>{const ts=new URLSearchParams(xs);return ts.set("activeTab",Ze),ts},{replace:!0}),$(!1)}catch(ve){console.error("Resume saved session failed",ve)}finally{ie(null)}},[oe,ye,t,i]);Rd({urlActiveTab:k&&!Be?c:null,conversations:Ce,resolveConversationBySessionId:Xe,normalizedGroupAssignments:kt,hasHydratedStoredLayout:k&&!Be?K:!0,hydrateStoredLayout:k&&!Be?J:()=>{},setGroupActiveTabIds:E,setFocusedGroup:j,setSearchParams:i,historyModalOpen:L,activeConv:Ae,isRefreshingHistory:Uo,ides:h,handleRefreshHistory:Fo});const bn=a.useCallback(async(he,ke)=>{const we=ke||Y||Ae;if(!we||!We(we)&&!$e(we))return;const ve=lt(we),Me=we.routeId||we.daemonId||"";try{await t(Me,"stop_cli",{cliType:ve,targetSessionId:we.sessionId,mode:he})}catch(Ze){console.error("Stop CLI failed:",Ze)}},[Ae,Y,t]),Zo=a.useCallback(async he=>{const ke=he||Ae;!ke||!We(ke)&&!$e(ke)||(re(ke),H(!0))},[Ae]),Qo=a.useMemo(()=>!Ae||!We(Ae)||$e(Ae)?null:ls(Ae),[Ae]),ei=a.useCallback(async he=>{if(!(!Ae||!We(Ae)||$e(Ae)||ls(Ae)===he))try{await t(Kt(Ae)||Ae.routeId,"set_cli_view_mode",{targetSessionId:Ae.sessionId,cliType:lt(Ae),mode:he})}catch(we){Ju(we)?console.warn("Skipped CLI view mode switch:",we instanceof Error?we.message:String(we)):console.error("Failed to switch CLI view mode:",we)}},[Ae,t]),{versionMismatchDaemons:ti,appVersion:si,versionBannerDismissed:ri,setVersionBannerDismissed:ni,upgradingDaemons:ai,handleBannerUpgrade:oi}=Od({ides:h,sendDaemonCommand:t}),gn=a.useCallback(he=>{te(he.tabKey),i(ke=>{const we=new URLSearchParams(ke),ve=Mc(he);return ve?we.set("activeTab",ve):we.delete("activeTab"),we},{replace:!0})},[i]),yn=a.useCallback(he=>{ze(he.tabKey),gn(he)},[gn,ze]),ii=a.useCallback(he=>{ot(he.tabKey)},[ot]);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(sl,{wsStatus:u,showReconnected:N}),e.jsx(rl,{terminalBackend:Ne,isStandalone:ce,machineLabel:Pe,machineKey:De}),!ri&&e.jsx(qu,{daemons:ti,targetVersion:si,upgradingDaemons:ai,onUpgrade:oi,onDismiss:()=>ni(!0)}),e.jsx(Ou,{showMobileChatMode:Be,isMobile:k,activeConv:Ae,chatIdes:Ke,wsStatus:u,isConnected:S,onOpenHistory:he=>{he&&yt(he),$(!0)},onOpenRemote:P,onStopCli:Zo,activeCliViewMode:Qo,onSetActiveCliViewMode:ei,mobileChatConversations:Ie,ides:h,actionLogs:be,sendDaemonCommand:t,setLocalUserMessages:ae,setActionLogs:ne,isStandalone:ce,initialDataLoaded:g,userName:p.userName,requestedMobileTabKey:ue,onRequestedMobileTabConsumed:Ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:f,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:Te,isSplitMode:Et,numGroups:pt,groupSizes:G,groupedConvs:Nt,clearedTabs:de,focusedGroup:v,setFocusedGroup:j,moveTabToGroup:It,splitTabRelative:ps,closeGroup:St,handleResizeStart:_t,detectedIdes:ee,handleLaunchIde:Ho,groupActiveTabIds:B,setGroupActiveTabIds:E,groupTabOrders:W,setGroupTabOrders:T,toggleHiddenTab:Qe,visibleConversations:Ue,hiddenConversations:it,requestedDesktopTabKey:Wt,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:te,onHideConversation:ii,onShowHiddenConversation:yn,onShowAllHiddenConversations:et,scrollToBottomRequest:ge,machineEntries:Q,onBrowseMachineDirectory:Je,onSaveMachineWorkspace:fs,onLaunchMachineIde:Wo,onLaunchMachineProvider:Oo,onListMachineSavedSessions:zo}),e.jsx("style",{children:`
|
|
45
|
+
`})]})}function Hu({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,u=i.status==="waiting_approval",m=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:u?"var(--status-warning)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"0 0 6px var(--accent-primary)":"none"}}),i.title,u&&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 Uu({ideData:t,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,u]=a.useState(()=>i||"native"),m=a.useMemo(()=>so(s),[s]),f=a.useMemo(()=>t?ln(t,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[t,n,m,r]),p=a.useMemo(()=>f.find(b=>b.streamSource==="native"),[f]),h=a.useMemo(()=>f.filter(b=>b.streamSource==="agent-stream"),[f]),g=a.useMemo(()=>t?Rt(f,t.id):null,[f,t]);a.useEffect(()=>{i&&u(i)},[i]),a.useEffect(()=>{if(i||!g)return;const b=g.streamSource==="native"?"native":g.tabKey;!b||c===b||c==="native"&&u(b)},[c,g,i]),a.useEffect(()=>{var b;c!=="native"&&(h.some(y=>y.tabKey===c)||u(((b=h[0])==null?void 0:b.tabKey)||"native"))},[c,h]),a.useEffect(()=>{c==="native"&&(p||h[0]&&u(h[0].tabKey))},[c,p,h]);const C=a.useMemo(()=>c==="native"&&p?p:h.find(b=>b.tabKey===c)||g||p||h[0],[c,p,g,h]),I=a.useMemo(()=>h.map(b=>({tabKey:b.tabKey,title:eo(b)||o,status:b.status})),[h,o]),d=a.useCallback(b=>{if(b)return f.find(y=>y.sessionId===b||y.routeId===b||y.tabKey===b)},[f]);return{activeChatTab:c,setActiveChatTab:u,activeConv:C,conversations:f,extensionTabs:I,hasExtensions:I.length>0,resolveConversationByTarget:d}}function Fu({activeConv:t,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:u,setActionLogs:m,isStandalone:f,userName:p,onOpenHistory:h,onConversationChange:g,onClose:C}){const[I,d]=a.useState("split"),[b,y]=a.useState(()=>Pt(t)?"native":t.tabKey),l=a.useRef(null),S=a.useMemo(()=>s||r.find(P=>P.id===t.routeId),[t.routeId,s,r]),M=a.useMemo(()=>Oe((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:N,extensionTabs:x,hasExtensions:w}=Uu({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:M||"IDE",preferredTabKey:Pt(t)?void 0:t.tabKey}),v=a.useMemo(()=>S?Rt(N,S.id):null,[S,N]);a.useEffect(()=>{const P=l.current,$={routeId:t.routeId,tabKey:t.tabKey,streamSource:t.streamSource};if(l.current=$,!(P&&P.routeId===$.routeId&&P.tabKey===$.tabKey&&P.streamSource===$.streamSource)){if(Pt(t)){y("native");return}y(t.tabKey)}},[t.routeId,t.streamSource,t.tabKey]),a.useEffect(()=>{if(b==="native"){if(N.some(P=>P.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!N.some(P=>P.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[N,b,v]);const j=a.useMemo(()=>b==="native"?N.find(P=>P.streamSource==="native")||t:N.find(P=>P.tabKey===b)||t,[t,N,b]),B=go(j),E=a.useMemo(()=>B.status||B.modalMessage||B.modalButtons?{...j,...B.status?{status:B.status}:{},...B.modalMessage!==void 0?{modalMessage:B.modalMessage}:{},...B.modalButtons!==void 0?{modalButtons:B.modalButtons}:{}}:j,[j,B]),W=nr(E),T=pr({sendDaemonCommand:c,activeConv:E,setLocalUserMessages:u,setActionLogs:m,isStandalone:f}),{connScreenshot:G,screenshotUsage:_,handleRemoteAction:k}=To({doId:W,targetSessionId:an(E),connState:E.connectionState||"new",viewMode:I}),K=a.useMemo(()=>o.filter(P=>P.routeId===E.tabKey),[o,E.tabKey]);a.useEffect(()=>{g==null||g(E)},[E,g]),a.useEffect(()=>{const P=$=>{$.key==="Escape"&&C()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[C]);const J=a.useCallback(P=>{P.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:C,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:J,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(ut,{size:16})}),e.jsx("span",{className:"truncate",children:mr(j)||"Remote"})]})}),e.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:C,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(P=>{const $=I===P;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:()=>d(P),title:P==="split"?"Split view":"Remote only",children:P==="split"?e.jsx(Bi,{size:15}):e.jsx(ut,{size:15})},P)})}),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(Qr,{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:C,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(Hu,{hasExtensions:w,ideName:M||"IDE",activeChatTab:b,extensionTabs:x,onSelectTab:y}),e.jsx(Oa,{activeConv:E,onModalButton:T.handleModalButton}),e.jsx(zr,{activeConv:E,ideEntry:S,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:K,userName:p})]}),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(Ba,{addLog:()=>{},connState:E.connectionState||"new",connScreenshot:G,screenshotUsage:_,transportType:E.transport,onAction:k})})]})]})})}function Vu({activeConv:t,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Qc(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 Gu({historyModalOpen:t,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:u,onCloseHistory:m,onNewHistoryChat:f,onSwitchHistorySession:p,onRefreshHistory:h,onResumeSavedHistorySession:g,remoteDialogConv:C,remoteDialogIdeEntry:I,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:S,setActionLogs:M,isStandalone:N,userName:x,onOpenRemoteHistory:w,onRemoteConversationChange:v,onCloseRemoteDialog:j,cliStopDialogOpen:B,cliStopTargetConv:E,onCancelCliStop:W,onStopCliNow:T,onSaveCliAndStop:G,toasts:_,onDismissToast:k,onClickToast:K,showOnboarding:J,onCloseOnboarding:P}){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:u,onClose:m,onNewChat:f,onSwitchSession:p,onRefreshHistory:h,onResumeSavedSession:g}),C&&e.jsx(Fu,{activeConv:C,ideEntry:I,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:l,setLocalUserMessages:S,setActionLogs:M,isStandalone:N,userName:x,onOpenHistory:w,onConversationChange:v,onClose:j}),B&&E&&(We(E)||$e(E))&&e.jsx(Vu,{activeConv:E,canSaveAndStop:We(E)&&!$e(E)&&!!(($=E.resume)!=null&&$.supported),onCancel:W,onStopNow:T,onSaveAndStop:G}),e.jsx(to,{toasts:_,onDismiss:k,onClickToast:K}),J&&e.jsx(zu,{onClose:P})]})}function qu({daemons:t,targetVersion:s,upgradingDaemons:r,onUpgrade:n,onDismiss:o}){return t.length===0?null:e.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[e.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:"var(--status-warning)"},children:e.jsx(us,{size:14})}),e.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[e.jsxs("span",{children:["Update available",s?e.jsxs(e.Fragment,{children:[": ",e.jsxs("strong",{children:["v",s]})]}):null]}),t.map(i=>{const c=dt(i,{fallbackId:i.id}),u=r[i.id],m=i.version||i.daemonVersion||"unknown";return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 15%, transparent)"},children:[e.jsx("span",{className:"font-medium text-text-primary",children:c}),e.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u==="upgrading"?e.jsx("span",{className:"text-[10px] animate-pulse",style:{color:"var(--status-warning)"},children:"upgrading…"}):u==="done"?e.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?e.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>n(i.id),children:"retry"}):e.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},onClick:()=>n(i.id),children:"Upgrade"})]},i.id)})]}),e.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:e.jsx(bt,{size:16})})]})}function Yu(t){if(!t)return"";const s=String(t);return s.includes(":")&&s.split(":")[0]||s}function ha(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xu(t){return(t instanceof Error?t.message:String(t||"")).includes("P2P command timeout")}function Ju(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 Zu(){var vn,wn,jn,kn,Nn;const{sendCommand:t}=mt(),s=$s(),r=Xr(),n=ds(),[o,i]=bi(),c=o.get("activeTab"),u=((vn=r.state)==null?void 0:vn.openRemoteForTabKey)||null,m=((wn=r.state)==null?void 0:wn.openMachineId)||null,f=((jn=r.state)==null?void 0:jn.mobileSection)||null,p=Xa(),h=p.ides||[],g=p.initialLoaded??!0,{updateRouteChats:C,setToasts:I}=p,[d,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=p.toasts||[],l=p.wsStatus||"connected",S=p.isConnected??!0,M=p.connectionStates||{},N=p.showReconnected||!1,{groupAssignments:x,setGroupAssignments:w,focusedGroup:v,setFocusedGroup:j,groupActiveTabIds:B,setGroupActiveTabIds:E,groupTabOrders:W,setGroupTabOrders:T,groupSizes:G,setGroupSizes:_,isMobile:k,hasHydratedStoredLayout:K,hydrateStoredLayout:J}=Pd(),[P,$]=a.useState(!1),[z,U]=a.useState(!1),[Y,re]=a.useState(null),[pe,O]=a.useState([]),[F,D]=a.useState(!1),[me,ie]=a.useState(null),[X]=a.useState(()=>ho()),[be,ne]=a.useState([]),[le,ae]=a.useState({}),[de,q]=a.useState({}),[se,te]=a.useState(null),[ge,fe]=a.useState(null),[R,xe]=a.useState(null),A=a.useRef(null);Ls("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(x).length,localMessageTabs:Object.keys(le).length,actionLogCount:be.length});const H=h.find(he=>he.type==="adhdev-daemon"),ee=(H==null?void 0:H.detectedIdes)||[],Q=a.useMemo(()=>h.filter(he=>he.type==="adhdev-daemon").sort(sn),[h]),ce=!!H;a.useEffect(()=>{!H||!(!H.detectedIdes||!H.availableProviders||!H.recentLaunches||!H.workspaces)||s(H.id,{minFreshMs:3e4}).catch(()=>{})},[H,s]);const Ne=(H==null?void 0:H.terminalBackend)||null,Le=H?dt(H,{fallbackId:H.id}):null,De=(H==null?void 0:H.id)||null,{hiddenTabs:Re,hideTab:ot,toggleTab:Qe,showTab:ze,showAllTabs:et}=ud(),{chatIdes:Ke,conversations:Ce,visibleConversations:He,visibleTabKeys:Ye,resolveConversationBySessionId:Xe,resolveConversationByTarget:V}=jd({ides:h,connectionStates:M,localUserMessages:le,clearedTabs:de,hiddenTabs:Re}),je=a.useMemo(()=>Rs(h),[h]),Se=a.useRef(null),{containerRef:Te,normalizedGroupAssignments:kt,numGroups:pt,isSplitMode:Et,groupedConvs:Nt,moveTabToGroup:It,closeGroup:St,handleResizeStart:Mt,splitTabRelative:ps}=Wd({groupAssignments:x,setGroupAssignments:w,setFocusedGroup:j,setGroupActiveTabIds:E,setGroupTabOrders:T,groupSizes:G,setGroupSizes:_,isMobile:k,visibleConversations:He,visibleTabKeys:Ye}),_e=a.useMemo(()=>{var ke,we;if(!k){if(se){const ve=Ce.find(Ae=>Ae.tabKey===se);if(ve)return ve}return He[0]}const he=B[v];if(he){const ve=Ce.find(Ae=>Ae.tabKey===he);if(ve)return ve}return((ke=Nt[v])==null?void 0:ke[0])||((we=Nt[0])==null?void 0:we[0])},[se,k,B,v,Ce,Nt,He]);a.useEffect(()=>{if(k){Se.current=null;return}if(!(_e!=null&&_e.sessionId)){Se.current=null;return}const he=`${_e.tabKey}:${_e.sessionId}`;if(Se.current===he)return;const ke=()=>{if(document.visibilityState!=="visible"||Se.current===he)return;Se.current=he;const we=Ms(_e,je),ve=Math.max(Date.now(),Gt(_e),we.lastUpdated||0);t(_e.daemonId||_e.routeId,"mark_session_seen",{sessionId:_e.sessionId,seenAt:ve}).catch(()=>{})};if(document.visibilityState==="visible"){const we=setTimeout(ke,1500),ve=()=>{document.visibilityState!=="visible"&&clearTimeout(we)};return document.addEventListener("visibilitychange",ve),()=>{clearTimeout(we),document.removeEventListener("visibilitychange",ve)}}else{const we=()=>{document.visibilityState==="visible"&&(setTimeout(ke,800),document.removeEventListener("visibilitychange",we))};return document.addEventListener("visibilitychange",we),()=>{document.removeEventListener("visibilitychange",we)}}},[_e,k,je,t]);const{requestedDesktopTabKey:Wt,requestedMobileTabKey:ue,consumeRequestedActiveTab:Ee}=kd({isMobile:k,urlActiveTab:c,resolveConversationBySessionId:Xe,setSearchParams:i}),{remoteDialogConv:gt,remoteDialogIdeEntry:_t,remoteDialogActiveConv:$t,setRemoteDialogActiveConv:yt,openRemoteDialog:L,closeRemoteDialog:Z}=Ed({isMobile:k,location:r,navigate:n,requestedRemoteTabTarget:u,requestedDesktopTabKey:Wt,conversations:Ce,ides:h,resolveConversationByTarget:V}),oe=$t||gt||_e,ye=!!oe&&We(oe)&&!$e(oe),Me=a.useMemo(()=>{if(!oe||!ye)return null;const he=oe.daemonId||oe.routeId||"",ke=lt(oe);return`${he}:${ke}`},[oe,ye]),Ie=a.useMemo(()=>He,[He]),Be=k&&X==="chat",it=a.useMemo(()=>Ce.filter(he=>Re.has(he.tabKey)),[Ce,Re]),at=a.useCallback(he=>{const ke=new URLSearchParams(o);ke.set("activeTab",he),i(ke,{replace:!0})},[o,i]),Je=a.useCallback(async(he,ke)=>xr(t,he,ke),[t]),fs=a.useCallback(async(he,ke)=>{if(!ke.trim())return{ok:!1,error:"Choose a workspace path first."};try{const we=await t(he,"workspace_add",{path:ke.trim()});return we!=null&&we.success?{ok:!0}:{ok:!1,error:(we==null?void 0:we.error)||"Could not save workspace"}}catch(we){return{ok:!1,error:we instanceof Error?we.message:"Could not save workspace"}}},[t]),Wo=a.useCallback(async(he,ke,we)=>{var ve;try{const Ae={ideType:ke,enableCdp:!0};(ve=we==null?void 0:we.workspacePath)!=null&&ve.trim()&&(Ae.workspace=we.workspacePath.trim());const Ze=await t(he,"launch_ide",Ae);return!(Ze!=null&&Ze.success)&&(Ze==null?void 0:Ze.success)!==void 0?{ok:!1,error:(Ze==null?void 0:Ze.error)||"Could not launch IDE"}:(xe({machineId:he,kind:"ide",providerType:ke,workspacePath:(we==null?void 0:we.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Ae){return{ok:!1,error:Ae instanceof Error?Ae.message:"Could not launch IDE"}}},[t]),Oo=a.useCallback(async(he,ke,we,ve)=>{var Ze,xs,ts;const Ae=Date.now();try{const vt={cliType:we};(Ze=ve==null?void 0:ve.workspacePath)!=null&&Ze.trim()?vt.dir=ve.workspacePath.trim():ve!=null&&ve.workspaceId&&(vt.workspaceId=ve.workspaceId),(xs=ve==null?void 0:ve.resumeSessionId)!=null&&xs.trim()&&(vt.resumeSessionId=ve.resumeSessionId.trim()),Array.isArray(ve==null?void 0:ve.cliArgs)&&ve.cliArgs.length>0&&(vt.cliArgs=ve.cliArgs),(ts=ve==null?void 0:ve.initialModel)!=null&&ts.trim()&&(vt.initialModel=ve.initialModel.trim());const tt=await t(he,"launch_cli",vt),ct=(tt==null?void 0:tt.result)||tt,hs=(ct==null?void 0:ct.sessionId)||(ct==null?void 0:ct.id);return tt!=null&&tt.success&&hs?(at(hs),{ok:!0}):tt!=null&&tt.success?(xe({machineId:he,kind:ke,providerType:we,workspacePath:(ve==null?void 0:ve.workspacePath)||null,resumeSessionId:(ve==null?void 0:ve.resumeSessionId)||null,startedAt:Ae}),{ok:!0}):{ok:!1,error:(tt==null?void 0:tt.error)||(ct==null?void 0:ct.error)||`Could not launch ${ke.toUpperCase()} session`}}catch(vt){return Xu(vt)?(xe({machineId:he,kind:ke,providerType:we,workspacePath:(ve==null?void 0:ve.workspacePath)||null,resumeSessionId:(ve==null?void 0:ve.resumeSessionId)||null,startedAt:Ae}),{ok:!0}):{ok:!1,error:vt instanceof Error?vt.message:`Could not launch ${ke.toUpperCase()} session`}}},[at,t]),zo=a.useCallback(async(he,ke)=>{if(!he||!ke)return[];try{const we=await t(he,"list_saved_sessions",{providerType:ke,kind:"cli",limit:30}),ve=(we==null?void 0:we.result)??we;return Array.isArray(ve==null?void 0:ve.sessions)?ve.sessions:[]}catch(we){return console.error("List saved sessions failed",we),[]}},[t]);a.useEffect(()=>{var ve;if(!R)return;const he=ha(R.workspacePath),ke=h.find(Ae=>{var tt,ct,hs,Sn;if(!Ae||Ae.type==="adhdev-daemon"||Yu(Ae.daemonId||Ae.id)!==R.machineId||(As(Ae)?"cli":as(Ae)?"acp":"ide")!==R.kind||String(Ae.agentType||Ae.type||"")!==R.providerType)return!1;if(R.resumeSessionId)return String(Ae.providerSessionId||"")===R.resumeSessionId;if(he){const yr=ha(Ae.workspace||Ae.runtimeWorkspaceLabel);return yr?yr===he:!1}return Number(Ae.lastUpdated||Ae._lastUpdate||Ae.timestamp||((Sn=(hs=(ct=(tt=Ae.activeChat)==null?void 0:tt.messages)==null?void 0:ct.at)==null?void 0:hs.call(ct,-1))==null?void 0:Sn.timestamp)||0)>=R.startedAt-5e3});if(!ke)return;const we=typeof ke.sessionId=="string"&&ke.sessionId?ke.sessionId:typeof ke.instanceId=="string"&&ke.instanceId?ke.instanceId:(ve=Ce.find(Ae=>Ae.routeId===ke.id))==null?void 0:ve.sessionId;we&&(xe(null),at(we))},[Ce,at,h,R]),a.useEffect(()=>{if(!R)return;const he=window.setTimeout(()=>{xe(ke=>!ke||ke.startedAt!==R.startedAt?ke:null)},45e3);return()=>window.clearTimeout(he)},[R]),md({visibleConversations:He,clearedTabs:de,setClearedTabs:q,setActionLogs:ne}),Nd({ides:h,sendDaemonCommand:t,setToasts:I,setLocalUserMessages:ae,resolveConversationByTarget:V});const{isRefreshingHistory:Ho,handleLaunchIde:Uo,handleRefreshHistory:Fo}=ea({sendDaemonCommand:t,activeConv:_e,chats:(kn=h.find(he=>he.id===(_e==null?void 0:_e.routeId)))==null?void 0:kn.chats,updateRouteChats:C,setToasts:I,setLocalUserMessages:ae,setClearedTabs:q}),{isCreatingChat:Vo,isRefreshingHistory:Go,handleSwitchSession:qo,handleNewChat:Yo,handleRefreshHistory:Xo}=ea({sendDaemonCommand:t,activeConv:oe,chats:(Nn=h.find(he=>he.id===(oe==null?void 0:oe.routeId)))==null?void 0:Nn.chats,updateRouteChats:C,setToasts:I,setLocalUserMessages:ae,setClearedTabs:q}),gr=a.useCallback(async()=>{if(!(!oe||!ye||F)){D(!0);try{const he=oe.daemonId||oe.routeId,ke=lt(oe),we=await t(he,"list_saved_sessions",{agentType:ke,providerType:ke,kind:"cli",limit:50}),ve=(we==null?void 0:we.result)??we;O(Array.isArray(ve==null?void 0:ve.sessions)?ve.sessions:[])}catch(he){console.error("Refresh saved sessions failed",he),O([])}finally{D(!1)}}},[oe,F,ye,t]);a.useEffect(()=>{if(!P){A.current=null;return}if(!ye){A.current=null,O([]),D(!1);return}!Me||F||A.current!==Me&&(A.current=Me,gr())},[gr,P,F,ye,Me]);const Jo=a.useCallback(async he=>{if(!oe||!ye||!he.providerSessionId||!he.workspace)return;const ke=oe.daemonId||oe.routeId,we=lt(oe);try{ie(he.providerSessionId);const ve=await t(ke,"launch_cli",{cliType:we,dir:he.workspace,resumeSessionId:he.providerSessionId,initialModel:he.currentModel}),Ae=(ve==null?void 0:ve.result)??ve,Ze=typeof(Ae==null?void 0:Ae.sessionId)=="string"?Ae.sessionId:typeof(Ae==null?void 0:Ae.id)=="string"?Ae.id:"";Ze&&i(xs=>{const ts=new URLSearchParams(xs);return ts.set("activeTab",Ze),ts},{replace:!0}),$(!1)}catch(ve){console.error("Resume saved session failed",ve)}finally{ie(null)}},[oe,ye,t,i]);Rd({urlActiveTab:k&&!Be?c:null,conversations:Ce,resolveConversationBySessionId:Xe,normalizedGroupAssignments:kt,hasHydratedStoredLayout:k&&!Be?K:!0,hydrateStoredLayout:k&&!Be?J:()=>{},setGroupActiveTabIds:E,setFocusedGroup:j,setSearchParams:i,historyModalOpen:P,activeConv:_e,isRefreshingHistory:Ho,ides:h,handleRefreshHistory:Fo});const bn=a.useCallback(async(he,ke)=>{const we=ke||Y||_e;if(!we||!We(we)&&!$e(we))return;const ve=lt(we),Ae=we.routeId||we.daemonId||"";try{await t(Ae,"stop_cli",{cliType:ve,targetSessionId:we.sessionId,mode:he})}catch(Ze){console.error("Stop CLI failed:",Ze)}},[_e,Y,t]),Zo=a.useCallback(async he=>{const ke=he||_e;!ke||!We(ke)&&!$e(ke)||(re(ke),U(!0))},[_e]),Qo=a.useMemo(()=>!_e||!We(_e)||$e(_e)?null:ls(_e),[_e]),ei=a.useCallback(async he=>{if(!(!_e||!We(_e)||$e(_e)||ls(_e)===he))try{await t(Kt(_e)||_e.routeId,"set_cli_view_mode",{targetSessionId:_e.sessionId,cliType:lt(_e),mode:he})}catch(we){Ju(we)?console.warn("Skipped CLI view mode switch:",we instanceof Error?we.message:String(we)):console.error("Failed to switch CLI view mode:",we)}},[_e,t]),{versionMismatchDaemons:ti,appVersion:si,versionBannerDismissed:ri,setVersionBannerDismissed:ni,upgradingDaemons:ai,handleBannerUpgrade:oi}=Od({ides:h,sendDaemonCommand:t}),gn=a.useCallback(he=>{te(he.tabKey),i(ke=>{const we=new URLSearchParams(ke),ve=Ac(he);return ve?we.set("activeTab",ve):we.delete("activeTab"),we},{replace:!0})},[i]),yn=a.useCallback(he=>{ze(he.tabKey),gn(he)},[gn,ze]),ii=a.useCallback(he=>{ot(he.tabKey)},[ot]);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(sl,{wsStatus:l,showReconnected:N}),e.jsx(rl,{terminalBackend:Ne,isStandalone:ce,machineLabel:Le,machineKey:De}),!ri&&e.jsx(qu,{daemons:ti,targetVersion:si,upgradingDaemons:ai,onUpgrade:oi,onDismiss:()=>ni(!0)}),e.jsx(Ou,{showMobileChatMode:Be,isMobile:k,activeConv:_e,chatIdes:Ke,wsStatus:l,isConnected:S,onOpenHistory:he=>{he&&yt(he),$(!0)},onOpenRemote:L,onStopCli:Zo,activeCliViewMode:Qo,onSetActiveCliViewMode:ei,mobileChatConversations:Ie,ides:h,actionLogs:be,sendDaemonCommand:t,setLocalUserMessages:ae,setActionLogs:ne,isStandalone:ce,initialDataLoaded:g,userName:p.userName,requestedMobileTabKey:ue,onRequestedMobileTabConsumed:Ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:f,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:Te,isSplitMode:Et,numGroups:pt,groupSizes:G,groupedConvs:Nt,clearedTabs:de,focusedGroup:v,setFocusedGroup:j,moveTabToGroup:It,splitTabRelative:ps,closeGroup:St,handleResizeStart:Mt,detectedIdes:ee,handleLaunchIde:Uo,groupActiveTabIds:B,setGroupActiveTabIds:E,groupTabOrders:W,setGroupTabOrders:T,toggleHiddenTab:Qe,visibleConversations:He,hiddenConversations:it,requestedDesktopTabKey:Wt,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:te,onHideConversation:ii,onShowHiddenConversation:yn,onShowAllHiddenConversations:et,scrollToBottomRequest:ge,machineEntries:Q,onBrowseMachineDirectory:Je,onSaveMachineWorkspace:fs,onLaunchMachineIde:Wo,onLaunchMachineProvider:Oo,onListMachineSavedSessions:zo}),e.jsx("style",{children:`
|
|
46
46
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
47
|
-
`}),e.jsx(Gu,{historyModalOpen:
|
|
48
|
-
This will terminate the process.`))try{const
|
|
49
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(
|
|
50
|
-
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[t,s.type,r,o]),x=async()=>{if(m.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,p?`💬 Comment: ${p}`:"",""]),
|
|
51
|
-
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.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:v=>v.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:rm.map(v=>e.jsxs("button",{onClick:()=>d(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),e.jsx("button",{onClick:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ba.map(v=>e.jsxs("button",{onClick:()=>u(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(v)?"☑ ":"☐ ",v]},v))})]}),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:p,onChange:v=>h(v.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:[g.map((v,j)=>e.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},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"&&m.length>0&&`${m.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:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:w,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"),C([]),l("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function am({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var N;const i=s.filter(x=>x.category==="ide"),[c,d]=a.useState(((N=i[0])==null?void 0:N.type)||""),[m,f]=a.useState(""),[p,h]=a.useState(""),[g,C]=a.useState(!1),[I,l]=a.useState(""),[b,y]=a.useState(!1),u=x=>{const w=x.toLowerCase().replace(/[^a-z0-9-]/g,"");f(w),(!p||p===S(m))&&h(S(w))},S=x=>x.split("-").map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join(" "),_=async()=>{if(!(!m||!p||!c)){C(!0),l("");try{const x=await r(t,"provider_clone",{type:m,name:p,category:"ide",location:"user",cloneFrom:c});x!=null&&x.success||x!=null&&x.created?(y(!0),o==null||o(m)):l((x==null?void 0:x.error)||"Failed to create provider")}catch(x){l((x==null?void 0:x.message)||"Connection failed")}C(!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:m})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," 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:m,onChange:x=>u(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/",m||"...","/"]})]})]}),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:p,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:_,disabled:!m||!p||g,className:"machine-btn",style:{background:m&&p?"rgba(34,197,94,0.12)":void 0,borderColor:m&&p?"rgba(34,197,94,0.3)":void 0,color:m&&p?"#86efac":void 0,opacity:!m||!p||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function om({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[d,m]=a.useState(null),[f,p]=a.useState("all"),[h,g]=a.useState(null),[C,I]=a.useState(!1),l=a.useCallback(async()=>{if(t){c(!0);try{const y=await r(t,"get_provider_settings",{}),u=tm(y);if(u){const S=sm(u,s);S.sort((_,N)=>_.category.localeCompare(N.category)||_.displayName.localeCompare(N.displayName)),o(S)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&l()},[]);const b=async(y,u,S)=>{m(`${y}.${u}`),o(_=>_.map(N=>N.type===y?{...N,values:{...N.values,[u]:S}}:N));try{const _=await r(t,"set_provider_setting",{providerType:y,key:u,value:S});_!=null&&_.success||l()}catch{l()}m(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(y=>e.jsx("button",{onClick:()=>p(y),className:`machine-btn text-[10px] px-2 py-0.5 ${f===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),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:l,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(y=>y.category===f).length>1&&(()=>{const y=n.filter(N=>N.category===f),u=new Map;for(const N of y)for(const x of N.schema){if(x.type!=="boolean")continue;const w=u.get(x.key),v=!!(N.values[x.key]??x.default);w?(w.onCount+=v?1:0,w.total+=1):u.set(x.key,{label:x.label||x.key,onCount:v?1:0,total:1})}const S=[...u.entries()].filter(([,N])=>N.total===y.length);if(S.length===0)return null;const _=async(N,x)=>{for(const w of y)await b(w.type,N,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 (",y.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(([N,x])=>{const w=x.onCount===x.total,v=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 _(N,!0),disabled:w,className:`machine-btn text-[9px] px-1.5 py-px ${w?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void _(N,!1),disabled:v,className:`machine-btn text-[9px] px-1.5 py-px ${v?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),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(y=>f==="all"||y.category===f).map(y=>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:y.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:y.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:y.category==="acp"?"rgba(139,92,246,0.08)":y.category==="cli"?"rgba(59,130,246,0.08)":y.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:y.category==="acp"?"#a78bfa":y.category==="cli"?"#60a5fa":y.category==="ide"?"#86efac":"var(--status-warning)"},children:y.category}),y.category==="ide"&&e.jsx("button",{onClick:()=>g(s.find(u=>u.type===y.type)||{type:y.type,name:y.displayName,displayName:y.displayName,icon:y.icon,category:y.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:y.schema.map(u=>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:[u.label||u.key,d===`${y.type}.${u.key}`&&e.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),u.description&&e.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:u.description})]}),e.jsx("div",{className:"shrink-0",children:u.type==="boolean"?e.jsx("button",{onClick:()=>b(y.type,u.key,!(y.values[u.key]??u.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:y.values[u.key]??u.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:y.values[u.key]??u.default?21:3}})}):u.type==="number"?e.jsx("input",{type:"number",value:Number(y.values[u.key]??u.default??0)||0,min:u.min,max:u.max,onChange:S=>{const _=parseInt(S.target.value)||0;u.min!==void 0&&_<u.min||u.max!==void 0&&_>u.max||b(y.type,u.key,_)},className:"machine-input w-20 text-center text-[11px]"}):u.type==="select"&&u.options?e.jsx("select",{value:String(y.values[u.key]??u.default??""),onChange:S=>b(y.type,u.key,S.target.value),className:"machine-input text-[11px]",children:u.options.map(S=>e.jsx("option",{value:S,children:S},S))}):e.jsx("input",{type:"text",value:String(y.values[u.key]??u.default??""),onBlur:S=>b(y.type,u.key,S.target.value),className:"machine-input w-[120px] text-[11px]"})})]},u.key))})]},y.type))}),h&&e.jsx(nm,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),C&&e.jsx(am,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),l()}})]})}function im({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState(0),[c,d]=a.useState(!0),[m,f]=a.useState("debug"),p=a.useRef(null),h=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const g=async()=>{try{const I=await s(t,"get_logs",{count:200,minLevel:m,since:o}),l=(I==null?void 0:I.result)||I;if(I!=null&&I.success&&Array.isArray(l==null?void 0:l.logs)&&l.logs.length>0){n(y=>[...y,...l.logs.map(S=>({timestamp:S.ts,level:S.level,message:`[${S.category}] ${S.message}`}))].slice(-300));const b=Math.max(...l.logs.map(y=>y.ts));i(b)}}catch{}};g();const C=setInterval(g,3e3);return()=>clearInterval(C)},[t,c,o,m,s]),a.useEffect(()=>{if(c&&r.length>0){const g=h.current?"smooth":"instant";setTimeout(()=>{var C;(C=p.current)==null||C.scrollIntoView({behavior:g}),h.current=!0},50)}},[r.length,c]),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-3",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(g=>e.jsx("button",{onClick:()=>{f(g),n([]),i(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${m===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:[r.length," entries"]}),e.jsx("button",{onClick:()=>d(!c),className:`machine-btn ${c?"text-green-500 border-green-500/30":""}`,children:c?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),i(0)},className:"machine-btn",children:"Clear"})]})]}),e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[200px] max-h-[500px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[r.length===0&&e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((g,C)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#475569":"#8b5cf6"},children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:g.message})]},C)),e.jsx("div",{ref:p})]})]})}function Er(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function $r(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ga(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 cm(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function lm(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 dm(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 um(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 mm({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[d,m]=a.useState(!1),f=bo(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),p=f.diagnostics,h=f.loading,g=f.applyDiagnostics,C=a.useMemo(()=>new Map(s.map(x=>[x.sessionId||x.id,x])),[s]),I=a.useCallback(async()=>{if(t){m(!0);try{const x=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),w=Er(x);if(!(w!=null&&w.success))throw new Error((w==null?void 0:w.error)||"Could not load session host diagnostics");g(w.diagnostics||w.result||null),o("")}catch(x){const w=x instanceof Error?x.message:"Could not load session host diagnostics";o(w)}finally{m(!1)}}},[g,t,r]),l=a.useCallback(async(x,w)=>{const v=`${x}:${w.sessionId}`;if(!(x==="session_host_stop_session"&&!window.confirm(`Stop ${w.displayName}?
|
|
47
|
+
`}),e.jsx(Gu,{historyModalOpen:P,historyTargetConv:oe,ides:h,isHistoryCreatingChat:Vo,isHistoryRefreshingHistory:ye?!1:Go,savedHistorySessions:pe,isSavedHistoryLoading:F,isResumingSavedHistorySessionId:me,onCloseHistory:()=>$(!1),onNewHistoryChat:Yo,onSwitchHistorySession:qo,onRefreshHistory:ye?gr:Xo,onResumeSavedHistorySession:Jo,remoteDialogConv:gt,remoteDialogIdeEntry:_t,connectionStates:M,actionLogs:be,localUserMessages:le,sendDaemonCommand:t,setLocalUserMessages:ae,setActionLogs:ne,isStandalone:ce,userName:p.userName,onOpenRemoteHistory:he=>{he&&yt(he),$(!0)},onRemoteConversationChange:yt,onCloseRemoteDialog:Z,cliStopDialogOpen:z,cliStopTargetConv:Y,onCancelCliStop:()=>{U(!1),re(null)},onStopCliNow:async()=>{U(!1),await bn("hard",Y),re(null)},onSaveCliAndStop:async()=>{U(!1),await bn("save",Y),re(null)},toasts:y,onDismissToast:he=>I(ke=>ke.filter(we=>we.id!==he)),onClickToast:he=>{if(he.targetKey){const ke=V(he.targetKey);ke&&(j(kt.get(ke.tabKey)??0),yn(ke),fe({tabKey:ke.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Qu({machineId:t,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[u,m]=a.useState(null),[f,p]=a.useState(null),[h,g]=a.useState(!1),[C,I]=a.useState(null),[d,b]=a.useState(!1),[y,l]=a.useState(""),S=a.useRef(null),M=a.useCallback(P=>{S.current=P},[]),N=a.useCallback((P,$,z=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:P,message:$}]),setTimeout(()=>{var U;return(U=o.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),z&&nt.showToast($,P==="error"||P==="warn"?"warning":"success")},[o]),x=a.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),w=a.useCallback(async(P,$)=>{var z;if(!t||u)return!1;m(P),N("info",`Launching ${Oe(P)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const U={ideType:P,enableCdp:!0};(z=$==null?void 0:$.workspace)!=null&&z.trim()?U.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const Y=await r(t,"launch_ide",U);return N(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${Oe(P)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(U){return N("error",`Launch error: ${U.message}`,!0),!1}finally{m(null)}},[t,u,N,r]),v=a.useCallback(async P=>{if(!t)return{success:!1};const{cliType:$,dir:z,workspaceId:U,useDefaultWorkspace:Y,useHome:re,argsStr:pe,model:O,resumeSessionId:F}=P;if(!$)return N("warn","Select a CLI or ACP provider first",!0),{success:!1};const D=pe?pe.split(/\s+/).filter(Boolean):void 0,me=(z==null?void 0:z.trim())||(U?"(saved id)":Y?"(default workspace)":re?"(home)":"");N("info",`Launching ${$}${me?` in ${me}`:""}${O?` (model: ${O})`:""}...`),p($);try{const ie={cliType:$,cliArgs:D,initialModel:O||void 0};z!=null&&z.trim()?ie.dir=z.trim():U?ie.workspaceId=U:Y?ie.useDefaultWorkspace=!0:re&&(ie.useHome=!0),F&&(ie.resumeSessionId=F);const X=await r(t,"launch_cli",ie),be=(X==null?void 0:X.result)||X;return X!=null&&X.success?(N("info",`${$} launched`,!0),(be==null?void 0:be.launchSource)==="home"?N("info","📂 Running in home directory (explicit choice)"):(be==null?void 0:be.launchSource)==="defaultWorkspace"&&N("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:be==null?void 0:be.sessionId}):(N("error",`Failed: ${(X==null?void 0:X.error)||(be==null?void 0:be.error)}`,!0),(X==null?void 0:X.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&I({cliType:$,argsStr:pe,model:O}),{success:!1,sessionId:be==null?void 0:be.sessionId})}catch(ie){return x(ie)?(N("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(N("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{p(null)}},[t,N,x,r]),j=a.useCallback(async(P,$,z,U)=>t?P?$.trim()?v({cliType:P,dir:$,argsStr:z,model:U}):(I({cliType:P,argsStr:z,model:U}),{success:!1}):(N("warn","Select a provider",!0),{success:!1}):{success:!1},[t,N,v]),B=a.useCallback(async(P,$,z)=>{if(t&&window.confirm(`Stop ${P}?
|
|
48
|
+
This will terminate the process.`))try{const U=await r(t,"stop_cli",{cliType:P,dir:$,targetSessionId:z});U!=null&&U.success?N("info",`${P} stopped`,!0):N("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){N("error",`Stop failed: ${U.message}`,!0)}},[t,N,r]),E=a.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),N("info",`${Oe(P.type)} restart initiated`,!0)}catch($){N("error",`Restart failed: ${$.message}`,!0)}},[N,r]),W=a.useCallback(async P=>{if(window.confirm(`Stop ${Oe(P.type)}?
|
|
49
|
+
This will disconnect CDP and optionally kill the process.`))try{const $=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?N("info",`${Oe(P.type)} stopped`,!0):N("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){N("error",`Stop failed: ${$.message}`,!0)}},[N,r]),T=a.useCallback(async()=>{if(t)try{const P=await r(t,"detect_ides",{});N("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){N("error",`Detection failed: ${P.message}`,!0)}},[t,N,r]),G=a.useCallback(async P=>{if(!t||!P.trim())return!1;g(!0);try{const $=await r(t,"workspace_add",{path:P.trim()});return $!=null&&$.success?(N("info",`Workspace added: ${P.trim()}`),!0):(N("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return N("error",$.message),!1}finally{g(!1)}},[t,N,r]),_=a.useCallback(async P=>{if(!(!t||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const $=await r(t,"workspace_remove",{id:P});$!=null&&$.success?N("info","Workspace removed",!0):N("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){N("error",$.message,!0)}finally{g(!1)}}},[t,N,r]),k=a.useCallback(async P=>{var $;if(t){g(!0);try{const z=await r(t,"workspace_set_default",P===null?{clear:!0}:{id:P});if(z!=null&&z.success){N("info",P?"Default workspace updated":"Default workspace cleared",!0);const U=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";U&&(($=S.current)==null||$.call(S,U))}else N("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){N("error",z.message,!0)}finally{g(!1)}}},[t,N,r]),K=a.useCallback(async P=>{var z;if(!t||!P.trim())return;const $=P.trim();g(!0);try{const U=await r(t,"workspace_set_default",{path:$});U!=null&&U.success?(N("info","Default workspace set from history"),(z=S.current)==null||z.call(S,$)):N("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){N("error",U.message)}finally{g(!1)}},[t,N,r]),J=a.useCallback(async()=>{if(t)try{if(await r(t,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:t,registeredMachineId:s,nickname:y})}catch(P){N("warn",`Live nickname updated, but account sync failed: ${P.message}`)}N("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(P){N("error",`Failed: ${P.message}`)}},[t,y,s,N,n,r]);return{logs:i,launchingIde:u,launchingAgentType:f,workspaceBusy:h,launchPick:C,setLaunchPick:I,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:l,addLog:N,handleLaunchIde:w,runLaunchCliCore:v,handleLaunchCli:j,handleStopCli:B,handleRestartIde:E,handleStopIde:W,handleDetectIdes:T,handleWorkspaceAdd:G,handleWorkspaceRemove:_,handleWorkspaceSetDefault:k,handleWorkspaceResumePath:K,handleSaveNickname:J,setOnDefaultWorkspaceChanged:M}}function em({machineId:t,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var E;const{workspaceBusy:u,handleWorkspaceAdd:m,handleWorkspaceRemove:f,handleWorkspaceSetDefault:p}=i,[h,g]=a.useState(!1),[C,I]=a.useState(""),[d,b]=a.useState([]),[y,l]=a.useState(!1),[S,M]=a.useState(""),N=a.useCallback(async W=>{l(!0),M("");try{const T=await xr(c,t,W);I(T.path),b(T.directories)}catch(T){M(T instanceof Error?T.message:"Could not load folder")}finally{l(!1)}},[t,c]),x=a.useCallback(()=>{var T;g(!0);const W=fr(s.platform,[s.defaultWorkspacePath,(T=s.workspaces[0])==null?void 0:T.path]);N(W)},[N,s.defaultWorkspacePath,s.platform,s.workspaces]),w=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,j=w&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,B=((E=s.loadavg)==null?void 0:E[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(Bs,{icon:e.jsx(Ra,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?gc(s.uptime):"Waiting…"}),e.jsx(Bs,{icon:e.jsx(ut,{size:16}),label:"IDEs",value:`${r.length}`}),e.jsx(Bs,{icon:e.jsx(lr,{size:16}),label:"CLIs",value:`${n.length}`}),e.jsx(Bs,{icon:e.jsx(Wi,{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(Tn,{value:w?Math.min(Math.round(B/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:w?`${B.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),e.jsx(Tn,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:w?`${wr(s.totalMem-v)} / ${wr(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${wr(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(cs,{size:14})," Workspaces"]}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),e.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:u,value:s.defaultWorkspaceId||"",onChange:W=>void p(W.target.value===""?null:W.target.value),children:[e.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(W=>e.jsx("option",{value:W.id,children:W.label||W.path},W.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:u,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(W=>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:[W.id===s.defaultWorkspaceId&&e.jsx("span",{className:"text-[10px]",children:"⭐"}),e.jsx("span",{className:"font-medium text-text-primary truncate",children:ur(W.path,W.label)})]}),e.jsx("div",{className:"font-mono truncate text-[10px]",title:W.path,children:W.path})]}),e.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:u,onClick:()=>void f(W.id),children:"Remove"})]},W.id))})]}),h&&e.jsx(hr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:d,busy:y,error:S,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:W=>{N(W)},onConfirm:W=>{(async()=>{if(!W)return;await m(W)&&g(!1)})()}})]})}function tm(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 sm(t,s,r){const n=[];for(const[o,i]of Object.entries(t.settings)){const c=i;if(c.length===0)continue;const u=s.find(m=>m.type===o);n.push({type:o,displayName:(u==null?void 0:u.displayName)||o,icon:(u==null?void 0:u.icon)||"",category:(u==null?void 0:u.category)||"unknown",schema:c,values:t.values[o]||{}})}return n}const ba=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],rm=[{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 nm({machineId:t,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,u]=a.useState("codex-cli"),[m,f]=a.useState([]),[p,h]=a.useState(""),[g,C]=a.useState([]),[I,d]=a.useState(""),b=a.useRef(null),y=a.useRef(null),l=v=>{f(j=>j.includes(v)?j.filter(B=>B!==v):[...j,v])},S=()=>f([...ba]),M=()=>f([]);a.useEffect(()=>{var v;(v=b.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),a.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const N=a.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(t,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&o==="running"&&(i("done"),C(j=>[...j,`
|
|
50
|
+
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[t,s.type,r,o]),x=async()=>{if(m.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,p?`💬 Comment: ${p}`:"",""]),d("");try{const v=await r(t,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...p?{comment:p}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(C(j=>[...j,"✅ Agent started. Monitoring progress..."]),N()):(i("error"),d((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),d((v==null?void 0:v.message)||"Connection failed")}}},w=async()=>{try{await r(t,"provider_auto_fix_cancel",{providerType:s.type}),C(v=>[...v,`
|
|
51
|
+
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.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:v=>v.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:rm.map(v=>e.jsxs("button",{onClick:()=>u(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[e.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),e.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),e.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),e.jsx("button",{onClick:M,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ba.map(v=>e.jsxs("button",{onClick:()=>l(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(v)?"☑ ":"☐ ",v]},v))})]}),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:p,onChange:v=>h(v.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:[g.map((v,j)=>e.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},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"&&m.length>0&&`${m.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:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.length===0?.4:1},children:"🚀 Start Fix"})]}),o==="running"&&e.jsx("button",{onClick:w,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"),C([]),d("")},className:"machine-btn",children:"← Back"}),e.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function am({machineId:t,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var N;const i=s.filter(x=>x.category==="ide"),[c,u]=a.useState(((N=i[0])==null?void 0:N.type)||""),[m,f]=a.useState(""),[p,h]=a.useState(""),[g,C]=a.useState(!1),[I,d]=a.useState(""),[b,y]=a.useState(!1),l=x=>{const w=x.toLowerCase().replace(/[^a-z0-9-]/g,"");f(w),(!p||p===S(m))&&h(S(w))},S=x=>x.split("-").map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join(" "),M=async()=>{if(!(!m||!p||!c)){C(!0),d("");try{const x=await r(t,"provider_clone",{type:m,name:p,category:"ide",location:"user",cloneFrom:c});x!=null&&x.success||x!=null&&x.created?(y(!0),o==null||o(m)):d((x==null?void 0:x.error)||"Failed to create provider")}catch(x){d((x==null?void 0:x.message)||"Connection failed")}C(!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:m})," has been created at ",e.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),e.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",e.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," 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:()=>u(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:m,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/",m||"...","/"]})]})]}),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:p,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:M,disabled:!m||!p||g,className:"machine-btn",style:{background:m&&p?"rgba(34,197,94,0.12)":void 0,borderColor:m&&p?"rgba(34,197,94,0.3)":void 0,color:m&&p?"#86efac":void 0,opacity:!m||!p||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function om({machineId:t,providers:s,sendDaemonCommand:r}){const[n,o]=a.useState([]),[i,c]=a.useState(!1),[u,m]=a.useState(null),[f,p]=a.useState("all"),[h,g]=a.useState(null),[C,I]=a.useState(!1),d=a.useCallback(async()=>{if(t){c(!0);try{const y=await r(t,"get_provider_settings",{}),l=tm(y);if(l){const S=sm(l,s);S.sort((M,N)=>M.category.localeCompare(N.category)||M.displayName.localeCompare(N.displayName)),o(S)}}catch{}c(!1)}},[t,s,r]);a.useEffect(()=>{n.length===0&&d()},[]);const b=async(y,l,S)=>{m(`${y}.${l}`),o(M=>M.map(N=>N.type===y?{...N,values:{...N.values,[l]:S}}:N));try{const M=await r(t,"set_provider_setting",{providerType:y,key:l,value:S});M!=null&&M.success||d()}catch{d()}m(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(y=>e.jsx("button",{onClick:()=>p(y),className:`machine-btn text-[10px] px-2 py-0.5 ${f===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),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:d,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),f!=="all"&&n.filter(y=>y.category===f).length>1&&(()=>{const y=n.filter(N=>N.category===f),l=new Map;for(const N of y)for(const x of N.schema){if(x.type!=="boolean")continue;const w=l.get(x.key),v=!!(N.values[x.key]??x.default);w?(w.onCount+=v?1:0,w.total+=1):l.set(x.key,{label:x.label||x.key,onCount:v?1:0,total:1})}const S=[...l.entries()].filter(([,N])=>N.total===y.length);if(S.length===0)return null;const M=async(N,x)=>{for(const w of y)await b(w.type,N,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 (",y.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(([N,x])=>{const w=x.onCount===x.total,v=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 M(N,!0),disabled:w,className:`machine-btn text-[9px] px-1.5 py-px ${w?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),e.jsx("button",{onClick:()=>void M(N,!1),disabled:v,className:`machine-btn text-[9px] px-1.5 py-px ${v?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),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(y=>f==="all"||y.category===f).map(y=>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:y.icon}),e.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:y.displayName}),e.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:y.category==="acp"?"rgba(139,92,246,0.08)":y.category==="cli"?"rgba(59,130,246,0.08)":y.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:y.category==="acp"?"#a78bfa":y.category==="cli"?"#60a5fa":y.category==="ide"?"#86efac":"var(--status-warning)"},children:y.category}),y.category==="ide"&&e.jsx("button",{onClick:()=>g(s.find(l=>l.type===y.type)||{type:y.type,name:y.displayName,displayName:y.displayName,icon:y.icon,category:y.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:y.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,u===`${y.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(y.type,l.key,!(y.values[l.key]??l.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:y.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:y.values[l.key]??l.default?21:3}})}):l.type==="number"?e.jsx("input",{type:"number",value:Number(y.values[l.key]??l.default??0)||0,min:l.min,max:l.max,onChange:S=>{const M=parseInt(S.target.value)||0;l.min!==void 0&&M<l.min||l.max!==void 0&&M>l.max||b(y.type,l.key,M)},className:"machine-input w-20 text-center text-[11px]"}):l.type==="select"&&l.options?e.jsx("select",{value:String(y.values[l.key]??l.default??""),onChange:S=>b(y.type,l.key,S.target.value),className:"machine-input text-[11px]",children:l.options.map(S=>e.jsx("option",{value:S,children:S},S))}):e.jsx("input",{type:"text",value:String(y.values[l.key]??l.default??""),onBlur:S=>b(y.type,l.key,S.target.value),className:"machine-input w-[120px] text-[11px]"})})]},l.key))})]},y.type))}),h&&e.jsx(nm,{machineId:t,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),C&&e.jsx(am,{machineId:t,providers:s,sendDaemonCommand:r,onClose:()=>I(!1),onCreated:()=>{I(!1),d()}})]})}function im({machineId:t,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState(0),[c,u]=a.useState(!0),[m,f]=a.useState("debug"),p=a.useRef(null),h=a.useRef(!1);return a.useEffect(()=>{if(!t||!c)return;const g=async()=>{try{const I=await s(t,"get_logs",{count:200,minLevel:m,since:o}),d=(I==null?void 0:I.result)||I;if(I!=null&&I.success&&Array.isArray(d==null?void 0:d.logs)&&d.logs.length>0){n(y=>[...y,...d.logs.map(S=>({timestamp:S.ts,level:S.level,message:`[${S.category}] ${S.message}`}))].slice(-300));const b=Math.max(...d.logs.map(y=>y.ts));i(b)}}catch{}};g();const C=setInterval(g,3e3);return()=>clearInterval(C)},[t,c,o,m,s]),a.useEffect(()=>{if(c&&r.length>0){const g=h.current?"smooth":"instant";setTimeout(()=>{var C;(C=p.current)==null||C.scrollIntoView({behavior:g}),h.current=!0},50)}},[r.length,c]),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-3",children:[e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(g=>e.jsx("button",{onClick:()=>{f(g),n([]),i(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${m===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),e.jsxs("div",{className:"flex gap-1.5 items-center",children:[e.jsxs("span",{className:"text-[10px] text-text-muted",children:[r.length," entries"]}),e.jsx("button",{onClick:()=>u(!c),className:`machine-btn ${c?"text-green-500 border-green-500/30":""}`,children:c?"⏸ Pause":"▶ Resume"}),e.jsx("button",{onClick:()=>{n([]),i(0)},className:"machine-btn",children:"Clear"})]})]}),e.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[200px] max-h-[500px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[r.length===0&&e.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((g,C)=>e.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[e.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#475569":"#8b5cf6"},children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),e.jsx("span",{children:g.message})]},C)),e.jsx("div",{ref:p})]})]})}function Er(t){return t!=null&&t.result&&typeof t.result=="object"&&"success"in t.result?t.result:t}function $r(t){return t?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ga(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 cm(t){return t?t.ownerType==="user"?`user control · ${t.clientId}`:`agent control · ${t.clientId}`:"view only"}function lm(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 dm(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 um(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 mm({machineId:t,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[u,m]=a.useState(!1),f=bo(t,{enabled:!!t,includeSessions:!0,limit:12,intervalMs:8e3}),p=f.diagnostics,h=f.loading,g=f.applyDiagnostics,C=a.useMemo(()=>new Map(s.map(x=>[x.sessionId||x.id,x])),[s]),I=a.useCallback(async()=>{if(t){m(!0);try{const x=await r(t,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),w=Er(x);if(!(w!=null&&w.success))throw new Error((w==null?void 0:w.error)||"Could not load session host diagnostics");g(w.diagnostics||w.result||null),o("")}catch(x){const w=x instanceof Error?x.message:"Could not load session host diagnostics";o(w)}finally{m(!1)}}},[g,t,r]),d=a.useCallback(async(x,w)=>{const v=`${x}:${w.sessionId}`;if(!(x==="session_host_stop_session"&&!window.confirm(`Stop ${w.displayName}?
|
|
52
52
|
This will terminate the hosted runtime.`))){c(v);try{const j=await r(t,x,{sessionId:w.sessionId}),B=Er(j);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Session host action failed");const E=x==="session_host_resume_session"?"resumed":x==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${E}: ${w.displayName}`,"success"),await I()}catch(j){const B=j instanceof Error?j.message:"Session host action failed";nt.showToast(B,"warning"),o(B)}finally{c(j=>j===v?null:j)}}},[t,I,r]),b=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
53
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const w=await r(t,"session_host_prune_duplicate_sessions",{}),v=Er(w);if(!(v!=null&&v.success))throw new Error((v==null?void 0:v.error)||"Duplicate prune failed");const j=v.result||{},B=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,E=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;nt.showToast(`Pruned ${B} duplicate runtime(s) across ${E} group(s)`,"success"),await I()}catch(w){const v=w instanceof Error?w.message:"Duplicate prune failed";nt.showToast(v,"warning"),o(v)}finally{c(w=>w==="session_host_prune_duplicate_sessions"?null:w)}}},[t,I,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((x,w)=>(w.lastActivityAt||0)-(x.lastActivityAt||0)),[p==null?void 0:p.sessions]),u=a.useMemo(()=>um(y),[y]),S=a.useMemo(()=>y.reduce((x,w)=>{var v;return x+(((v=w.attachedClients)==null?void 0:v.length)||0)},0),[y]),_=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),N=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(x=>x.level==="warn"||x.level==="error")||null,[p==null?void 0:p.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(Bt,{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:[u>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 (${u})`}),e.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||d,children:[e.jsx(us,{size:13}),h||d?"Refreshing…":"Refresh"]})]})]}),n&&!p&&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(Xt,{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})]})]})}),p&&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:p.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:S})]}),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:p.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:ga(p.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:$r(p.hostStartedAt)})]})]}),N&&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(Xt,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:N.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[$r(N.timestamp),N.sessionId?` · ${N.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(lr,{size:14})," Hosted Runtimes"]}),y.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:y.map(x=>{var T;const w=i===`session_host_resume_session:${x.sessionId}`,v=i===`session_host_restart_session:${x.sessionId}`,j=i===`session_host_stop_session:${x.sessionId}`,B=lm(x.meta),E=C.get(x.sessionId),W=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||(E==null?void 0:E.cliName)||x.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${dm(x.lifecycle)}`,children:x.lifecycle}),B&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:B})]}),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||(E==null?void 0:E.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:((T=x.writeOwner)==null?void 0:T.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:cm(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(Zr,{size:11})," ",W]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",ga(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:()=>{l("session_host_resume_session",x)},children:w?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{l("session_host_restart_session",x)},children:v?"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:()=>{l("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"}),_.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:_.map(x=>{var v;const w=y.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:(w==null?void 0:w.displayName)||((v=C.get(x.sessionId))==null?void 0:v.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:$r(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:p.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function pm({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 Dr({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 Br({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 fm({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const d=n.slice(0,6),m=r.slice(0,4),f=p=>p==="ide"?"IDE":p==="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(Dr,{icon:e.jsx(Pt,{size:13}),children:"Current Chats"}),e.jsx(Br,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const h=Gr(p);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(p),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Ve(p)}),h>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ka(h)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Qt(p)})]},p.tabKey)})})})]}),m.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Dr,{icon:e.jsx(Ra,{size:13}),children:"Recent Launches"}),e.jsx(Br,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(p=>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(p),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:p.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[f(p.kind),p.subtitle?` · ${p.subtitle}`:""]})]},p.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Dr,{icon:e.jsx(Xt,{size:13}),children:"Daemon Update"}),e.jsx(Br,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),e.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[e.jsx(us,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function xm(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const hm={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 Ys(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bm(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 Kr({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:d,initialWorkspaceId:m,initialWorkspacePath:f}){const p=ds(),{handleLaunchIde:h,handleStopCli:g,handleRestartIde:C,handleStopIde:I,handleDetectIdes:l,launchingIde:b,launchingAgentType:y,addLog:u}=c,[S,_]=a.useState(null),N=a.useCallback(P=>{P&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(P)}`})},[p]),x=hm[t],w=t==="ide",v=t==="acp",j=a.useMemo(()=>n.filter(P=>P.category===t&&(t==="ide"||P.installed!==!1)),[t,n]),B=a.useMemo(()=>new Map(j.map(P=>[P.type,P.displayName||P.type])),[j]),[E,W]=a.useState(""),[T,G]=a.useState(""),[A,k]=a.useState([]),[K,J]=a.useState(""),[L,$]=a.useState(""),[z,H]=a.useState([]),[Y,re]=a.useState(!1),[pe,O]=a.useState(""),[F,D]=a.useState(!1),[me,ie]=a.useState(null),[X,be]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[ne,le]=a.useState(f||""),[ae,de]=a.useState([]),[q,se]=a.useState(!1),[te,ge]=a.useState(""),[fe,R]=a.useState([]),[xe,M]=a.useState(!1),[U,ee]=a.useState(""),Q=a.useRef(null),[ce,Ne]=a.useState(null),Pe=a.useRef("__home__"),[De,Re]=a.useState("__home__"),[ot,Qe]=a.useState(!1),ze=a.useRef(0),et=ae.filter(P=>!o.some(Z=>Z.type===P&&rt(Z.status)!=="stopped")),Ke=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!X&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){be("__custom__"),le(f);return}m&&(be(m),le(""))},[m,f]),a.useEffect(()=>{w||E&&(j.some(P=>P.type===E)||(W(""),$("")))},[j,w,E]);const Ce=(()=>{if(X==="__custom__")return ne.trim();if(!X)return"";const P=(s.workspaces||[]).find(Z=>Z.id===X);return(P==null?void 0:P.path)||""})(),Ue=a.useCallback(P=>{const Z=Ke.current[P];Z&&(clearTimeout(Z),delete Ke.current[P]),de(oe=>oe.includes(P)?oe.filter(ye=>ye!==P):oe)},[]),Ye=a.useRef(new Set),Xe=a.useCallback(async P=>{if(d){M(!0),ee("");try{const Z=await xr(d,r,P);ge(Z.path),le(Z.path),R(Z.directories)}catch(Z){ee(Z instanceof Error?Z.message:"Could not load folder")}finally{M(!1)}}},[r,d]),V=a.useCallback(()=>{var Z;if(!d)return;be("__custom__"),se(!0);const P=fr(s.platform,[ne.trim(),Ce,s.defaultWorkspacePath,(Z=s.workspaces[0])==null?void 0:Z.path]);Xe(P)},[ne,Xe,s.defaultWorkspacePath,s.platform,s.workspaces,Ce,d]),je=a.useCallback(P=>{const Z=String(P.workspace||"").trim();if(!Z)return;const oe=(s.workspaces||[]).find(ye=>Ys(ye.path)===Ys(Z));if(oe){be(oe.id),le("");return}be("__custom__"),le(Z)},[s.workspaces]),Se=a.useCallback(P=>{const Z=String(P.workspace||"").trim();if(!Z)return{workspaceId:null,workspacePath:"",useHome:!0};const oe=(s.workspaces||[]).find(ye=>Ys(ye.path)===Ys(Z));return oe?{workspaceId:oe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Z,useHome:!1}},[s.workspaces]),Te=a.useCallback(async P=>{if(!d||!P||t!=="cli"){H([]),re(!1),O("");return}const Z=ze.current+1;ze.current=Z,re(!0),O("");try{const oe=await d(r,"list_saved_sessions",{providerType:P,kind:"cli",limit:30});if(ze.current!==Z)return;const ye=(oe==null?void 0:oe.result)??oe;H(Array.isArray(ye==null?void 0:ye.sessions)?ye.sessions:[])}catch(oe){if(ze.current!==Z)return;H([]),O(oe instanceof Error?oe.message:"Could not load saved sessions")}finally{ze.current===Z&&re(!1)}},[t,r,d]),kt=a.useMemo(()=>{if(t!=="cli"||!E)return null;const P=B.get(E)||E;return{routeId:r,daemonId:r,providerSessionId:L||void 0,transport:"pty",mode:"chat",agentName:P,agentType:E,status:"idle",title:P,messages:[],ideType:E,workspaceName:Ce,displayPrimary:P,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${E}`}},[t,r,B,Ce,L,E]),pt=a.useCallback(P=>{if(t==="ide"||!P){k([]);return}k($o(r,P))},[t,r]);a.useEffect(()=>{if($(""),pt(E),t!=="cli"||!E){H([]),O(""),re(!1);return}Te(E)},[t,pt,Te,E]),a.useEffect(()=>{if(!L)return;const P=z.find(Z=>Z.providerSessionId===L);P!=null&&P.canResume||$("")},[z,L]);const Et=a.useCallback((P,Z)=>{Q.current=Z,Pe.current=P.selectedWorkspaceKey||"__home__",Re(P.selectedWorkspaceKey||"__home__"),Ne(P)},[]),Nt=a.useCallback(()=>{Q.current&&(Qe(!0),Q.current().finally(()=>{Q.current=null,Qe(!1),Ne(null)}))},[]),It=a.useCallback(P=>{if(!P)return;de(oe=>oe.includes(P)?oe:[...oe,P]);const Z=Ke.current[P];Z&&clearTimeout(Z),Ke.current[P]=setTimeout(()=>{de(oe=>oe.includes(P)?oe.filter(ye=>ye!==P):oe),delete Ke.current[P]},2e4)},[]);a.useEffect(()=>{for(const Z of o)rt(Z.status)!=="stopped"&&(ae.includes(Z.type)&&!Ye.current.has(Z.type)&&(Ye.current.add(Z.type),u("info",`${B.get(Z.type)||Z.type} launched`,!0)),Ue(Z.type));const P=new Set(o.filter(Z=>rt(Z.status)!=="stopped").map(Z=>Z.type));Ye.current.forEach(Z=>{!ae.includes(Z)&&!P.has(Z)&&Ye.current.delete(Z)})},[u,Ue,o,ae,B]),a.useEffect(()=>()=>{Object.values(Ke.current).forEach(clearTimeout),Ke.current={}},[]);const[St,_t]=a.useState({}),[ps,Ae]=a.useState(null);a.useEffect(()=>{if(!w||!r||!d)return;(async()=>{try{const Z=await d(r,"get_ide_extensions",{}),oe=(Z==null?void 0:Z.result)||Z;oe!=null&&oe.success&&(oe!=null&&oe.ideExtensions)&&_t(oe.ideExtensions)}catch{}})()},[w,r,d]);const Wt=P=>w?Oe(P.type):t==="cli"?P.cliName:P.acpName,ue=w?s.detectedIdes||[]:[],Ee=a.useCallback(async P=>{const Z=(P==null?void 0:P.type)||E,oe=(P==null?void 0:P.workspacePath)??Ce;if(w){await h(Z,oe?{workspace:oe}:void 0)&&It(Z);return}const ye=await c.runLaunchCliCore({cliType:Z,dir:P!=null&&P.workspaceId?void 0:oe||void 0,workspaceId:(P==null?void 0:P.workspaceId)||void 0,useHome:(P==null?void 0:P.useHome)||!(P!=null&&P.workspaceId)&&!oe,argsStr:(P==null?void 0:P.argsStr)??(T||void 0),model:(P==null?void 0:P.model)??(v&&K||void 0),resumeSessionId:(P==null?void 0:P.resumeSessionId)||!v&&t==="cli"&&Z===E&&L||void 0});if(ye.success||ye.pending){const _e=(P==null?void 0:P.argsStr)??T;!w&&(_e!=null&&_e.trim())&&(Do(r,Z,_e),pt(Z)),It(Z),ye.success&&ye.sessionId&&N(ye.sessionId)}},[c,h,v,w,T,K,pt,It,r,N,Ce,L,E]),gt=()=>{var ye;const P=w?Oe(E):B.get(E)||E,{options:Z,selectedKey:oe}=qt({machine:s,currentWorkspaceId:X&&X!=="__custom__"?X:null,currentWorkspacePath:Ce});Et({title:`Launch ${P}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:Z,selectedWorkspaceKey:oe,details:[{label:"Mode",value:x.label},{label:"Provider",value:P},...!w&&t==="cli"&&L?[{label:"Resume",value:((ye=z.find(_e=>_e.providerSessionId===L))==null?void 0:ye.title)||L}]:[],...!w&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...v&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const _e=Z.find(Ie=>Ie.key===Pe.current);_e!=null&&_e.workspaceId?(be(_e.workspaceId),le("")):_e!=null&&_e.workspacePath?(be("__custom__"),le(_e.workspacePath)):(be(""),le("")),await Ee({workspaceId:(_e==null?void 0:_e.workspaceId)??null,workspacePath:(_e==null?void 0:_e.workspacePath)??"",useHome:!(_e!=null&&_e.workspaceId)&&!(_e!=null&&_e.workspacePath)})})},At=P=>{w?I(P):g(P.type,P.workspace,P.id)},$t=a.useCallback(async(P,Z,oe=!1)=>{if(P.mode===Z){oe&&P.sessionId&&N(P.sessionId);return}if(!d||!P.sessionId){oe&&P.sessionId&&N(P.sessionId);return}try{await d(r,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:P.type,mode:Z}),oe&&N(P.sessionId)}catch(ye){bm(ye)?console.warn("Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},[r,N,d]),yt=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:X,onChange:P=>{const Z=P.target.value;if(be(Z),Z==="__custom__"&&d){V();return}Z!=="__custom__"&&le("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(P=>e.jsxs("option",{value:P.id,children:[P.id===s.defaultWorkspaceId?"⭐ ":"",ur(P.path,P.label)]},P.id)),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),e.jsx("option",{value:"__custom__",children:d?"📁 Select workspace…":"✏️ Custom path…"})]})}),X==="__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:V,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ne,onChange:P=>le(P.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),e.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:X==="__custom__"?Ce?e.jsx("span",{className:"font-mono truncate block",title:Ce,children:Ce}):d?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ce?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:X===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ce,children:Ce})]}):"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:w?ue.length>0?ue.map(P=>{const Z=o.find(Be=>(Be.type||"").toLowerCase()===(P.type||"").toLowerCase()&&rt(Be.status)!=="stopped"),oe=P.running||!!Z,ye=!!Z&&Z.cdpConnected,_e=ae.includes(P.type||P.id||""),Ie=E===(P.type||"");return e.jsxs("button",{onClick:()=>{if(ye&&Z){const Be=Z.sessionId;Be?p(`/dashboard?activeTab=${encodeURIComponent(Be)}`,{state:{openRemoteForTabKey:Be}}):p("/dashboard",{state:{openRemoteForTabKey:Z.id}});return}_e||W(Be=>Be===(P.type||"")?"":P.type||"")},disabled:!!b||_e,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ye?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ie?"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!==P.type?.4:1},children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(P.type)}),oe&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ye?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:P.name||Oe(P.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-green-400":_e?"text-orange-400":Ie?"text-accent-primary":"text-text-muted"}`,children:ye?"Open Session":_e?"Starting...":Ie?"Configure":"Select"})]})]},P.type)}):e.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",e.jsxs("button",{onClick:l,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(Ei,{size:14})," Scan System"]})]}):j.length>0?j.map(P=>{const Z=E===P.type,oe=ae.includes(P.type),_e=!!o.find(Ie=>Ie.type===P.type&&rt(Ie.status)!=="stopped");return e.jsxs("button",{onClick:()=>W(Ie=>Ie===P.type?"":P.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Z?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:P.icon}),_e&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:P.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${oe?"text-orange-400":Z?"text-accent-primary":"text-text-muted"}`,children:oe?"Starting...":Z?"Configure":"Select"})]})]},P.type)}):e.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",t.toUpperCase()," providers available.",e.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),E&&(w?ue.find(P=>P.type===E):j.find(P=>P.type===E))&&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:w?Oe(E):B.get(E)||E})]}),yt,!w&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&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 Te(E),disabled:!E||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{E&&(D(!0),Te(E))},disabled:!E,children:"Open History"})]})]}),L?(()=>{const P=z.find(Z=>Z.providerSessionId===L);return P?e.jsx("div",{className:"rounded-md border border-[#ffffff1a] bg-bg-primary px-3 py-2 text-[10px] text-text-muted leading-relaxed",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-text-primary text-[11px] font-semibold truncate",children:P.title||P.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:P.providerSessionId}),e.jsx("div",{children:P.workspace||"Workspace unknown"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:()=>$(""),children:"Clear"})]})}):null})():e.jsx("div",{className:"text-[10px] text-text-muted",children:"Start a new CLI session, or choose one from history."}),pe&&e.jsx("div",{className:"text-[10px] text-red-400",children:pe})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:K,onChange:P=>J(P.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:T,onChange:P=>G(P.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),A.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:A.map(P=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>G(P),title:P,children:P},P))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:gt,disabled:!!y||!!b||ae.includes(E),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:y===E||b===E?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ae.filter(P=>!o.some(Z=>Z.type===P&&rt(Z.status)!=="stopped")).length,")"]}),o.length===0&&et.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:[et.map(P=>e.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(P)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?Oe(P):B.get(P)||P}),e.jsx("div",{className:"text-[11px] text-text-muted",children:y===P?"Launching process...":"Waiting for process and session to register..."})]})]}),e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${P}`)),o.map(P=>{const Z=w?P:null,oe=v?P:null,ye=!w&&!v?P:null,_e=rt(P.status);return e.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:i(P.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Wt(P),(Z==null?void 0:Z.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Z.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:P.workspace||"—"}),(oe==null?void 0:oe.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",oe.currentModel]}),(oe==null?void 0:oe.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",oe.currentPlan]}),(ye==null?void 0:ye.mode)&&e.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ye.runtimeKey}`),_(ye.runtimeKey||null),window.setTimeout(()=>{_(Be=>Be===ye.runtimeKey?null:Be)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&e.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:xm(ye.runtimeWriteOwner)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Ie=P.sessionId;if(Ie){p(`/dashboard?activeTab=${encodeURIComponent(Ie)}`,{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:P.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:e.jsx(ut,{size:13})}),e.jsx("button",{onClick:()=>{const Ie=P.workspace||"",{options:Be,selectedKey:it}=qt({machine:s,currentWorkspacePath:Ie});Et({title:`Restart ${Oe(P.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Be,selectedWorkspaceKey:it,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Oe(P.type)}]},async()=>{const at=Be.find(fs=>fs.key===Pe.current),Je=(at==null?void 0:at.workspacePath)??"";if(Je&&Je!==Ie){await Ee({type:P.type,workspacePath:Je});return}await C(P)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:e.jsx(us,{size:14})})]}),v&&e.jsx("button",{onClick:()=>{const Ie=P.sessionId;Ie&&N(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!P.sessionId,children:e.jsx(Pt,{size:14})}),ye&&_e!=="stopped"&&e.jsxs(e.Fragment,{children:[ye.mode&&e.jsx(on,{mode:ye.mode,onChange:Ie=>void $t(ye,Ie,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Ie=P.sessionId;Ie&&N(Ie)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!P.sessionId,children:ye.mode==="chat"?e.jsx(Pt,{size:14}):e.jsx(ut,{size:13})})]}),_e==="stopped"?e.jsx("button",{onClick:()=>{const Ie=P.workspace||"",Be=w?Oe(P.type):Wt(P),{options:it,selectedKey:at}=qt({machine:s,currentWorkspacePath:Ie});Et({title:`Launch ${Be}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:it,selectedWorkspaceKey:at,details:[{label:"Mode",value:x.label},{label:"Provider",value:Be}]},async()=>{const Je=it.find(fs=>fs.key===Pe.current);await Ee({type:P.type,workspaceId:(Je==null?void 0:Je.workspaceId)??null,workspacePath:(Je==null?void 0:Je.workspacePath)??"",useHome:!(Je!=null&&Je.workspaceId)&&!(Je!=null&&Je.workspacePath),model:oe==null?void 0:oe.currentModel})})},disabled:ae.includes(P.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:ae.includes(P.type)?"⏳":e.jsx(en,{size:14})}):e.jsx("button",{onClick:()=>At(P),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:e.jsx(bt,{size:14})})]})]}),Z&&Z.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Z.aiAgents.map(Ie=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${za(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",rt(Ie.status)]},Ie.id))}),Z&&(St[Z.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:(St[Z.type]||[]).map(Ie=>e.jsxs("button",{disabled:ps===`${Z.type}.${Ie.type}`,onClick:async()=>{const Be=`${Z.type}.${Ie.type}`;Ae(Be);try{await d(r,"set_ide_extension",{ideType:Z.type,extensionType:Ie.type,enabled:!Ie.enabled}),_t(it=>({...it,[Z.type]:(it[Z.type]||[]).map(at=>at.type===Ie.type?{...at,enabled:!at.enabled}:at)}))}catch(it){console.error("Extension toggle failed:",it)}finally{Ae(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 ${Ie.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 ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,e.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},P.id)})]}),q&&d&&e.jsx(hr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:te,directories:fe,busy:xe,error:U,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:P=>{Xe(P)},onConfirm:P=>{le(P),be("__custom__"),se(!1)}}),ce&&e.jsx(xn,{title:ce.title,description:ce.description,details:ce.details,workspaceOptions:ce.workspaceOptions,selectedWorkspaceKey:De,onWorkspaceChange:P=>{Pe.current=P,Re(P)},confirmLabel:ce.confirmLabel,busy:ot,onConfirm:Nt,onCancel:()=>{Q.current=null,Ne(null)}}),F&&kt&&e.jsx(cn,{activeConv:kt,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:z,isSavedSessionsLoading:Y,isResumingSavedSessionId:me,onClose:()=>D(!1),onNewChat:()=>{$(""),D(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Te(E)},onResumeSavedSession:P=>{if(!P.canResume||me)return;const Z=Se(P);$(P.providerSessionId),je(P),ie(P.providerSessionId),D(!1),Ee({type:P.providerType,workspaceId:Z.workspaceId,workspacePath:Z.workspacePath,useHome:Z.useHome,resumeSessionId:P.providerSessionId}).finally(()=>{ie(oe=>oe===P.providerSessionId?null:oe)})}})]})}const ya=[{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 gm({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:d,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:p,sendDaemonCommand:h}){var l;const[g,C]=a.useState(m);a.useEffect(()=>{C(m)},[m]);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:ya.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 ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>C(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===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:(l=ya.find(b=>b.id===g))==null?void 0:l.helper})]}),g==="ide"&&e.jsx(Kr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p}),g==="cli"&&e.jsx(Kr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p}),g==="acp"&&e.jsx(Kr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:d,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p})]})}function ym({onNicknameSynced:t}={}){var ne,le,ae,de,q,se,te,ge,fe;const{id:s}=gi(),r=ds(),n=Xr(),{sendCommand:o}=mt(),i=$s(),c=Xa(),d=c.ides||[],m=c.initialLoaded??!0,f=d.find(R=>R.id===s&&R.type==="adhdev-daemon"),p=d.some(R=>R.type==="adhdev-daemon"),[h,g]=a.useState("workspace"),[C,I]=a.useState("ide"),l=a.useRef(null),[b,y]=a.useState(null),u=a.useRef("__home__"),[S,_]=a.useState("__home__"),[N,x]=a.useState(!1),w=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),cd(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=Qu({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:w});a.useEffect(()=>nt.onToast(xe=>{c.setToasts(U=>{if(U.some(ce=>ce.message===xe.message&&xe.timestamp-ce.timestamp<3e3))return U;const Q={id:xe.id,message:xe.message,type:xe.type,timestamp:xe.timestamp,targetKey:xe.targetKey,actions:xe.actions};return[...U.slice(-4),Q]});const M=xe.duration||5e3;setTimeout(()=>c.setToasts(U=>U.filter(ee=>ee.id!==xe.id)),M)}),[c]);const B=(f==null?void 0:f.availableProviders)||[],E={};for(const R of B)E[R.type]=R.icon;const W=R=>E[R]||"",T=f?{id:f.id,hostname:Ua(f,{fallbackId:f.id}),platform:((ne=f.machine)==null?void 0:ne.platform)||"unknown",arch:((le=f.machine)==null?void 0:le.arch)||"",cpus:((ae=f.machine)==null?void 0:ae.cpus)||0,totalMem:((de=f.machine)==null?void 0:de.totalMem)||0,freeMem:(q=f.machine)==null?void 0:q.freeMem,availableMem:(se=f.machine)==null?void 0:se.availableMem,loadavg:(te=f.machine)==null?void 0:te.loadavg,uptime:(ge=f.machine)==null?void 0:ge.uptime,release:((fe=f.machine)==null?void 0:fe.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,G=d.filter(R=>R.daemonId===s&&R.type!=="adhdev-daemon").filter(R=>!Ms(R)&&!as(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,version:R.version||"",instanceId:R.instanceId||"",status:R.status,workspace:R.workspace||null,terminals:R.terminals||0,aiAgents:Nc(R.aiAgents||(R.agents||[]).map(xe=>({id:xe.name,name:xe.name,status:xe.status,version:xe.version}))),activeChat:R.activeChat||null,chats:R.chats||[],childSessions:R.childSessions||[],cdpConnected:R.cdpConnected||!1,daemonId:s})),A=d.filter(R=>R.daemonId===s&&Ms(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,cliName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,mode:R.mode,runtimeKey:R.runtimeKey,runtimeDisplayName:R.runtimeDisplayName,runtimeWorkspaceLabel:R.runtimeWorkspaceLabel,runtimeWriteOwner:R.runtimeWriteOwner||null,runtimeAttachedClients:R.runtimeAttachedClients||[],daemonId:s})),k=d.filter(R=>R.daemonId===s&&as(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,acpName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,currentModel:R.currentModel,currentPlan:R.currentPlan,daemonId:s})),K=f?dt(f,{fallbackId:s}):"",J="workspace",L=n.state,$=L==null?void 0:L.initialMachineTab,z=L==null?void 0:L.initialWorkspaceCategory,H=L==null?void 0:L.initialWorkspaceId,Y=L==null?void 0:L.initialWorkspacePath,re=$==="ides"||$==="clis"||$==="acps"?"workspace":$||J,pe=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":z,O=[...G.map(R=>{var xe,M,U,ee,Q;return{id:`ide:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.type,kind:"ide",providerType:R.type,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,timestamp:((Q=(ee=(U=(M=R.activeChat)==null?void 0:M.messages)==null?void 0:U.at)==null?void 0:ee.call(U,-1))==null?void 0:Q.timestamp)||0}}),...A.map(R=>{var xe,M,U,ee,Q;return{id:`cli:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.cliName,kind:"cli",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,timestamp:((Q=(ee=(U=(M=R.activeChat)==null?void 0:M.messages)==null?void 0:U.at)==null?void 0:ee.call(U,-1))==null?void 0:Q.timestamp)||0}}),...k.map(R=>{var xe,M,U,ee,Q;return{id:`acp:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.acpName,kind:"acp",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:R.currentModel||R.workspace||void 0,workspace:R.workspace||void 0,currentModel:R.currentModel,timestamp:((Q=(ee=(U=(M=R.activeChat)==null?void 0:M.messages)==null?void 0:U.at)==null?void 0:ee.call(U,-1))==null?void 0:Q.timestamp)||0}})].sort((R,xe)=>xe.timestamp-R.timestamp).map(({timestamp:R,...xe})=>xe),F=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(R=>({id:R.id,label:R.title||R.providerName||R.providerType,kind:R.kind,providerType:R.providerType,providerSessionId:R.providerSessionId,subtitle:R.currentModel||R.workspace||void 0,workspace:R.workspace,currentModel:R.currentModel})):O,D=a.useMemo(()=>{var xe;const R=((xe=c.connectionStates)==null?void 0:xe[s||""])||void 0;return d.filter(M=>M.daemonId===s&&M.type!=="adhdev-daemon").flatMap(M=>ln(M,{},{connectionStates:s&&R?{[s]:R}:void 0,defaultConnectionState:R})).filter(M=>!(M.transport==="pty"&&M.mode==="terminal")).sort((M,U)=>Gr(U)-Gr(M))},[d,c.connectionStates,s]),me=a.useCallback(R=>{const xe=R.sessionId||R.tabKey;xe&&r(`/dashboard?activeTab=${encodeURIComponent(xe)}`)},[r]),ie=a.useCallback(()=>{l.current&&(x(!0),l.current().finally(()=>{l.current=null,x(!1),y(null)}))},[]),X=a.useCallback(R=>{if(!T)return;const{options:xe,selectedKey:M}=qt({machine:T,currentWorkspacePath:R.workspace}),U=async()=>{I(R.kind),g("workspace")};l.current=async()=>{const ee=xe.find(Ne=>Ne.key===u.current),Q=(ee==null?void 0:ee.workspacePath)??null,ce=(ee==null?void 0:ee.workspaceId)??null;if(R.kind==="ide"&&R.providerType){await j.handleLaunchIde(R.providerType,Q?{workspace:Q}:void 0);return}if((R.kind==="cli"||R.kind==="acp")&&R.providerType){await j.runLaunchCliCore({cliType:R.providerType,dir:ce?void 0:Q||"",workspaceId:ce||void 0,model:R.kind==="acp"?R.currentModel:void 0,resumeSessionId:R.providerSessionId});return}await U()},u.current=M,_(M),y({title:`Launch ${R.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:xe,details:[{label:"Mode",value:R.kind.toUpperCase()},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]})},[j,T]);if(a.useEffect(()=>{g(re)},[J,re,s]),a.useEffect(()=>{pe&&I(pe)},[pe,s]),!T)return m?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:v,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 be=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{size:14})," Workspace"]}),count:G.length+A.length+k.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(cr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Di,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pi,{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:v,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:R=>j.setNicknameInput(R.target.value),onKeyDown:R=>{R.key==="Enter"&&j.handleSaveNickname(),R.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(T.machineNickname||"")},title:"Click to set nickname",children:K}),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:[T.platform," · ",T.arch]}),e.jsxs("span",{children:[T.cpus," cores"]}),(f==null?void 0:f.version)&&e.jsxs("span",{children:["v",f.version]}),T.p2p.available&&e.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:be.map(R=>e.jsxs("button",{onClick:()=>g(R.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===R.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[R.label,R.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===R.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:R.count})]},R.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(fm,{machineEntry:f,providers:B,recentLaunches:F,currentConversations:D,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:X,onOpenConversation:me}),e.jsx(gm,{machine:T,machineId:s,providers:B,ideSessions:G,cliSessions:A,acpSessions:k,actions:j,getIcon:W,initialCategory:C,initialWorkspaceId:H,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx(om,{machineId:s,providers:B,sendDaemonCommand:o}),h==="overview"&&e.jsx(em,{machineId:s,machine:T,ideSessions:G,cliSessions:A,acpSessions:k,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(mm,{machineId:s,cliSessions:A,sendDaemonCommand:o}),h==="logs"&&e.jsx(im,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&T&&e.jsx(pm,{machine:T,launchPick:j.launchPick,actions:j}),b&&e.jsx(xn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:R=>{u.current=R,_(R)},confirmLabel:b.confirmLabel,busy:N,onConfirm:ie,onCancel:()=>{l.current=null,y(null)}}),e.jsx(to,{toasts:c.toasts||[],onDismiss:R=>c.setToasts(xe=>xe.filter(M=>M.id!==R)),onClickToast:R=>{R.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(R.targetKey)}`)}}),e.jsx("style",{children:`
|
|
53
|
+
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 w=await r(t,"session_host_prune_duplicate_sessions",{}),v=Er(w);if(!(v!=null&&v.success))throw new Error((v==null?void 0:v.error)||"Duplicate prune failed");const j=v.result||{},B=Array.isArray(j.prunedSessionIds)?j.prunedSessionIds.length:0,E=typeof j.duplicateGroupCount=="number"?j.duplicateGroupCount:0;nt.showToast(`Pruned ${B} duplicate runtime(s) across ${E} group(s)`,"success"),await I()}catch(w){const v=w instanceof Error?w.message:"Duplicate prune failed";nt.showToast(v,"warning"),o(v)}finally{c(w=>w==="session_host_prune_duplicate_sessions"?null:w)}}},[t,I,r]),y=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((x,w)=>(w.lastActivityAt||0)-(x.lastActivityAt||0)),[p==null?void 0:p.sessions]),l=a.useMemo(()=>um(y),[y]),S=a.useMemo(()=>y.reduce((x,w)=>{var v;return x+(((v=w.attachedClients)==null?void 0:v.length)||0)},0),[y]),M=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),N=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(x=>x.level==="warn"||x.level==="error")||null,[p==null?void 0:p.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(Bt,{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 ${p?"bg-green-500/[0.08] text-green-500":"bg-amber-500/[0.08] text-amber-400"}`,children:p?"Managed":"Unavailable"}),e.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{I()},disabled:h||u,children:[e.jsx(us,{size:13}),h||u?"Refreshing…":"Refresh"]})]})]}),n&&!p&&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(Xt,{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})]})]})}),p&&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:p.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:S})]}),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:p.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:ga(p.hostStartedAt)}),e.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:$r(p.hostStartedAt)})]})]}),N&&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(Xt,{size:13})," Latest host warning"]}),e.jsx("div",{className:"text-text-primary leading-relaxed",children:N.message}),e.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[$r(N.timestamp),N.sessionId?` · ${N.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(lr,{size:14})," Hosted Runtimes"]}),y.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:y.map(x=>{var T;const w=i===`session_host_resume_session:${x.sessionId}`,v=i===`session_host_restart_session:${x.sessionId}`,j=i===`session_host_stop_session:${x.sessionId}`,B=lm(x.meta),E=C.get(x.sessionId),W=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||(E==null?void 0:E.cliName)||x.providerType}),e.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${dm(x.lifecycle)}`,children:x.lifecycle}),B&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:B})]}),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||(E==null?void 0:E.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:((T=x.writeOwner)==null?void 0:T.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:cm(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(Zr,{size:11})," ",W]}),e.jsx("span",{className:"text-text-muted",children:"·"}),e.jsxs("span",{className:"text-text-primary/85",children:["active ",ga(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:()=>{d("session_host_resume_session",x)},children:w?"Resuming…":"Resume"}),e.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{d("session_host_restart_session",x)},children:v?"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:()=>{d("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"}),M.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:M.map(x=>{var v;const w=y.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:(w==null?void 0:w.displayName)||((v=C.get(x.sessionId))==null?void 0:v.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:$r(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:p.endpoint||"unknown"}),n?e.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function pm({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 Dr({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 Br({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 fm({machineEntry:t,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const u=n.slice(0,6),m=r.slice(0,4),f=p=>p==="ide"?"IDE":p==="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:[u.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Dr,{icon:e.jsx(Lt,{size:13}),children:"Current Chats"}),e.jsx(Br,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(p=>{const h=Gr(p);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(p),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:Ve(p)}),h>0&&e.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ka(h)})]}),e.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Qt(p)})]},p.tabKey)})})})]}),m.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Dr,{icon:e.jsx(Ra,{size:13}),children:"Recent Launches"}),e.jsx(Br,{children:e.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(p=>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(p),children:[e.jsx("span",{className:"text-sm font-semibold text-text-primary truncate w-full group-hover:text-accent-primary transition-colors",children:p.label}),e.jsxs("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:[f(p.kind),p.subtitle?` · ${p.subtitle}`:""]})]},p.id))})})]}),t.versionMismatch&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Dr,{icon:e.jsx(Xt,{size:13}),children:"Daemon Update"}),e.jsx(Br,{className:"border-amber-500/20 bg-amber-500/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Version mismatch detected"}),e.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),e.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[e.jsx(us,{size:13}),e.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function xm(t){return t?t.ownerType==="user"?"you control":"agent controls":"view only"}const hm={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 Ys(t){return String(t||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bm(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 Kr({category:t,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:u,initialWorkspaceId:m,initialWorkspacePath:f}){const p=ds(),{handleLaunchIde:h,handleStopCli:g,handleRestartIde:C,handleStopIde:I,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:l}=c,[S,M]=a.useState(null),N=a.useCallback(L=>{L&&p({pathname:"/",search:`?activeTab=${encodeURIComponent(L)}`})},[p]),x=hm[t],w=t==="ide",v=t==="acp",j=a.useMemo(()=>n.filter(L=>L.category===t&&(t==="ide"||L.installed!==!1)),[t,n]),B=a.useMemo(()=>new Map(j.map(L=>[L.type,L.displayName||L.type])),[j]),[E,W]=a.useState(""),[T,G]=a.useState(""),[_,k]=a.useState([]),[K,J]=a.useState(""),[P,$]=a.useState(""),[z,U]=a.useState([]),[Y,re]=a.useState(!1),[pe,O]=a.useState(""),[F,D]=a.useState(!1),[me,ie]=a.useState(null),[X,be]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[ne,le]=a.useState(f||""),[ae,de]=a.useState([]),[q,se]=a.useState(!1),[te,ge]=a.useState(""),[fe,R]=a.useState([]),[xe,A]=a.useState(!1),[H,ee]=a.useState(""),Q=a.useRef(null),[ce,Ne]=a.useState(null),Le=a.useRef("__home__"),[De,Re]=a.useState("__home__"),[ot,Qe]=a.useState(!1),ze=a.useRef(0),et=ae.filter(L=>!o.some(Z=>Z.type===L&&rt(Z.status)!=="stopped")),Ke=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!X&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){be("__custom__"),le(f);return}m&&(be(m),le(""))},[m,f]),a.useEffect(()=>{w||E&&(j.some(L=>L.type===E)||(W(""),$("")))},[j,w,E]);const Ce=(()=>{if(X==="__custom__")return ne.trim();if(!X)return"";const L=(s.workspaces||[]).find(Z=>Z.id===X);return(L==null?void 0:L.path)||""})(),He=a.useCallback(L=>{const Z=Ke.current[L];Z&&(clearTimeout(Z),delete Ke.current[L]),de(oe=>oe.includes(L)?oe.filter(ye=>ye!==L):oe)},[]),Ye=a.useRef(new Set),Xe=a.useCallback(async L=>{if(u){A(!0),ee("");try{const Z=await xr(u,r,L);ge(Z.path),le(Z.path),R(Z.directories)}catch(Z){ee(Z instanceof Error?Z.message:"Could not load folder")}finally{A(!1)}}},[r,u]),V=a.useCallback(()=>{var Z;if(!u)return;be("__custom__"),se(!0);const L=fr(s.platform,[ne.trim(),Ce,s.defaultWorkspacePath,(Z=s.workspaces[0])==null?void 0:Z.path]);Xe(L)},[ne,Xe,s.defaultWorkspacePath,s.platform,s.workspaces,Ce,u]),je=a.useCallback(L=>{const Z=String(L.workspace||"").trim();if(!Z)return;const oe=(s.workspaces||[]).find(ye=>Ys(ye.path)===Ys(Z));if(oe){be(oe.id),le("");return}be("__custom__"),le(Z)},[s.workspaces]),Se=a.useCallback(L=>{const Z=String(L.workspace||"").trim();if(!Z)return{workspaceId:null,workspacePath:"",useHome:!0};const oe=(s.workspaces||[]).find(ye=>Ys(ye.path)===Ys(Z));return oe?{workspaceId:oe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Z,useHome:!1}},[s.workspaces]),Te=a.useCallback(async L=>{if(!u||!L||t!=="cli"){U([]),re(!1),O("");return}const Z=ze.current+1;ze.current=Z,re(!0),O("");try{const oe=await u(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(ze.current!==Z)return;const ye=(oe==null?void 0:oe.result)??oe;U(Array.isArray(ye==null?void 0:ye.sessions)?ye.sessions:[])}catch(oe){if(ze.current!==Z)return;U([]),O(oe instanceof Error?oe.message:"Could not load saved sessions")}finally{ze.current===Z&&re(!1)}},[t,r,u]),kt=a.useMemo(()=>{if(t!=="cli"||!E)return null;const L=B.get(E)||E;return{routeId:r,daemonId:r,providerSessionId:P||void 0,transport:"pty",mode:"chat",agentName:L,agentType:E,status:"idle",title:L,messages:[],ideType:E,workspaceName:Ce,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${E}`}},[t,r,B,Ce,P,E]),pt=a.useCallback(L=>{if(t==="ide"||!L){k([]);return}k($o(r,L))},[t,r]);a.useEffect(()=>{if($(""),pt(E),t!=="cli"||!E){U([]),O(""),re(!1);return}Te(E)},[t,pt,Te,E]),a.useEffect(()=>{if(!P)return;const L=z.find(Z=>Z.providerSessionId===P);L!=null&&L.canResume||$("")},[z,P]);const Et=a.useCallback((L,Z)=>{Q.current=Z,Le.current=L.selectedWorkspaceKey||"__home__",Re(L.selectedWorkspaceKey||"__home__"),Ne(L)},[]),Nt=a.useCallback(()=>{Q.current&&(Qe(!0),Q.current().finally(()=>{Q.current=null,Qe(!1),Ne(null)}))},[]),It=a.useCallback(L=>{if(!L)return;de(oe=>oe.includes(L)?oe:[...oe,L]);const Z=Ke.current[L];Z&&clearTimeout(Z),Ke.current[L]=setTimeout(()=>{de(oe=>oe.includes(L)?oe.filter(ye=>ye!==L):oe),delete Ke.current[L]},2e4)},[]);a.useEffect(()=>{for(const Z of o)rt(Z.status)!=="stopped"&&(ae.includes(Z.type)&&!Ye.current.has(Z.type)&&(Ye.current.add(Z.type),l("info",`${B.get(Z.type)||Z.type} launched`,!0)),He(Z.type));const L=new Set(o.filter(Z=>rt(Z.status)!=="stopped").map(Z=>Z.type));Ye.current.forEach(Z=>{!ae.includes(Z)&&!L.has(Z)&&Ye.current.delete(Z)})},[l,He,o,ae,B]),a.useEffect(()=>()=>{Object.values(Ke.current).forEach(clearTimeout),Ke.current={}},[]);const[St,Mt]=a.useState({}),[ps,_e]=a.useState(null);a.useEffect(()=>{if(!w||!r||!u)return;(async()=>{try{const Z=await u(r,"get_ide_extensions",{}),oe=(Z==null?void 0:Z.result)||Z;oe!=null&&oe.success&&(oe!=null&&oe.ideExtensions)&&Mt(oe.ideExtensions)}catch{}})()},[w,r,u]);const Wt=L=>w?Oe(L.type):t==="cli"?L.cliName:L.acpName,ue=w?s.detectedIdes||[]:[],Ee=a.useCallback(async L=>{const Z=(L==null?void 0:L.type)||E,oe=(L==null?void 0:L.workspacePath)??Ce;if(w){await h(Z,oe?{workspace:oe}:void 0)&&It(Z);return}const ye=await c.runLaunchCliCore({cliType:Z,dir:L!=null&&L.workspaceId?void 0:oe||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!oe,argsStr:(L==null?void 0:L.argsStr)??(T||void 0),model:(L==null?void 0:L.model)??(v&&K||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!v&&t==="cli"&&Z===E&&P||void 0});if(ye.success||ye.pending){const Me=(L==null?void 0:L.argsStr)??T;!w&&(Me!=null&&Me.trim())&&(Do(r,Z,Me),pt(Z)),It(Z),ye.success&&ye.sessionId&&N(ye.sessionId)}},[c,h,v,w,T,K,pt,It,r,N,Ce,P,E]),gt=()=>{var ye;const L=w?Oe(E):B.get(E)||E,{options:Z,selectedKey:oe}=qt({machine:s,currentWorkspaceId:X&&X!=="__custom__"?X:null,currentWorkspacePath:Ce});Et({title:`Launch ${L}?`,description:"Review the provider and target folder before starting this session.",confirmLabel:"Launch",workspaceOptions:Z,selectedWorkspaceKey:oe,details:[{label:"Mode",value:x.label},{label:"Provider",value:L},...!w&&t==="cli"&&P?[{label:"Resume",value:((ye=z.find(Me=>Me.providerSessionId===P))==null?void 0:ye.title)||P}]:[],...!w&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...v&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Me=Z.find(Ie=>Ie.key===Le.current);Me!=null&&Me.workspaceId?(be(Me.workspaceId),le("")):Me!=null&&Me.workspacePath?(be("__custom__"),le(Me.workspacePath)):(be(""),le("")),await Ee({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},_t=L=>{w?I(L):g(L.type,L.workspace,L.id)},$t=a.useCallback(async(L,Z,oe=!1)=>{if(L.mode===Z){oe&&L.sessionId&&N(L.sessionId);return}if(!u||!L.sessionId){oe&&L.sessionId&&N(L.sessionId);return}try{await u(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Z}),oe&&N(L.sessionId)}catch(ye){bm(ye)?console.warn("Skipped CLI view mode switch:",ye instanceof Error?ye.message:String(ye)):console.error("Failed to switch CLI view mode:",ye)}},[r,N,u]),yt=e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsx("select",{value:X,onChange:L=>{const Z=L.target.value;if(be(Z),Z==="__custom__"&&u){V();return}Z!=="__custom__"&&le("")},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(L=>e.jsxs("option",{value:L.id,children:[L.id===s.defaultWorkspaceId?"⭐ ":"",ur(L.path,L.label)]},L.id)),e.jsx("option",{value:"__custom__",children:u?"📁 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:u?"📁 Select workspace…":"✏️ Custom path…"})]})}),X==="__custom__"&&(u?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:V,children:"Select workspace…"}):e.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ne,onChange:L=>le(L.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:X==="__custom__"?Ce?e.jsx("span",{className:"font-mono truncate block",title:Ce,children:Ce}):u?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ce?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-text-secondary",children:X===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),e.jsx("span",{className:"font-mono truncate block",title:Ce,children:Ce})]}):"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:w?ue.length>0?ue.map(L=>{const Z=o.find(Be=>(Be.type||"").toLowerCase()===(L.type||"").toLowerCase()&&rt(Be.status)!=="stopped"),oe=L.running||!!Z,ye=!!Z&&Z.cdpConnected,Me=ae.includes(L.type||L.id||""),Ie=E===(L.type||"");return e.jsxs("button",{onClick:()=>{if(ye&&Z){const Be=Z.sessionId;Be?p(`/dashboard?activeTab=${encodeURIComponent(Be)}`,{state:{openRemoteForTabKey:Be}}):p("/dashboard",{state:{openRemoteForTabKey:Z.id}});return}Me||W(Be=>Be===(L.type||"")?"":L.type||"")},disabled:!!b||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ye?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ie?"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!==L.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(L.type)}),oe&&e.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${ye?"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:L.name||Oe(L.type)}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-green-400":Me?"text-orange-400":Ie?"text-accent-primary":"text-text-muted"}`,children:ye?"Open Session":Me?"Starting...":Ie?"Configure":"Select"})]})]},L.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:d,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(Ei,{size:14})," Scan System"]})]}):j.length>0?j.map(L=>{const Z=E===L.type,oe=ae.includes(L.type),Me=!!o.find(Ie=>Ie.type===L.type&&rt(Ie.status)!=="stopped");return e.jsxs("button",{onClick:()=>W(Ie=>Ie===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Z?"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:L.icon}),Me&&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:L.displayName}),e.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${oe?"text-orange-400":Z?"text-accent-primary":"text-text-muted"}`,children:oe?"Starting...":Z?"Configure":"Select"})]})]},L.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."})]})}),E&&(w?ue.find(L=>L.type===E):j.find(L=>L.type===E))&&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:w?Oe(E):B.get(E)||E})]}),yt,!w&&e.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&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 Te(E),disabled:!E||Y,children:Y?"Loading…":"Refresh"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>{E&&(D(!0),Te(E))},disabled:!E,children:"Open History"})]})]}),P?(()=>{const L=z.find(Z=>Z.providerSessionId===P);return L?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:L.title||L.providerSessionId}),e.jsx("div",{className:"font-mono break-all",children:L.providerSessionId}),e.jsx("div",{children:L.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."}),pe&&e.jsx("div",{className:"text-[10px] text-red-400",children:pe})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:K,onChange:L=>J(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),e.jsx("input",{type:"text",placeholder:"Optional flags...",value:T,onChange:L=>G(L.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(L=>e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>G(L),title:L,children:L},L))})]})]})]}),e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx("button",{onClick:gt,disabled:!!y||!!b||ae.includes(E),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:y===E||b===E?"⏳ Launching...":"▶ Launch"})})]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ae.filter(L=>!o.some(Z=>Z.type===L&&rt(Z.status)!=="stopped")).length,")"]}),o.length===0&&et.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:[et.map(L=>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(L)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?Oe(L):B.get(L)||L}),e.jsx("div",{className:"text-[11px] text-text-muted",children:y===L?"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:${L}`)),o.map(L=>{const Z=w?L:null,oe=v?L:null,ye=!w&&!v?L:null,Me=rt(L.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(L.type)}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Wt(L),(Z==null?void 0:Z.version)&&e.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Z.version]})]}),e.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[e.jsx("span",{children:L.workspace||"—"}),(oe==null?void 0:oe.currentModel)&&e.jsxs("span",{className:"text-cyan-500",children:["🤖 ",oe.currentModel]}),(oe==null?void 0:oe.currentPlan)&&e.jsxs("span",{style:{color:"var(--status-warning)"},children:["📋 ",oe.currentPlan]}),(ye==null?void 0:ye.mode)&&e.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&e.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.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 ",ye.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 Ie;(Ie=navigator.clipboard)==null||Ie.writeText(`adhdev attach ${ye.runtimeKey}`),M(ye.runtimeKey||null),window.setTimeout(()=>{M(Be=>Be===ye.runtimeKey?null:Be)},1200)},children:S===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&e.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:xm(ye.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 ${Me==="stopped"?"bg-red-500/[0.08] text-red-500":Me==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Me}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{const Ie=L.sessionId;if(Ie){p(`/dashboard?activeTab=${encodeURIComponent(Ie)}`,{state:{openRemoteForTabKey:Ie}});return}p("/dashboard",{state:{openRemoteForTabKey:L.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(ut,{size:13})}),e.jsx("button",{onClick:()=>{const Ie=L.workspace||"",{options:Be,selectedKey:it}=qt({machine:s,currentWorkspacePath:Ie});Et({title:`Restart ${Oe(L.type)}?`,description:"Review or change the target workspace before restarting this IDE.",confirmLabel:"Restart",workspaceOptions:Be,selectedWorkspaceKey:it,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:Oe(L.type)}]},async()=>{const at=Be.find(fs=>fs.key===Le.current),Je=(at==null?void 0:at.workspacePath)??"";if(Je&&Je!==Ie){await Ee({type:L.type,workspacePath:Je});return}await C(L)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:e.jsx(us,{size:14})})]}),v&&e.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&N(Ie)},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:!L.sessionId,children:e.jsx(Lt,{size:14})}),ye&&Me!=="stopped"&&e.jsxs(e.Fragment,{children:[ye.mode&&e.jsx(on,{mode:ye.mode,onChange:Ie=>void $t(ye,Ie,!1),compact:!0}),e.jsx("button",{onClick:()=>{const Ie=L.sessionId;Ie&&N(Ie)},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:!L.sessionId,children:ye.mode==="chat"?e.jsx(Lt,{size:14}):e.jsx(ut,{size:13})})]}),Me==="stopped"?e.jsx("button",{onClick:()=>{const Ie=L.workspace||"",Be=w?Oe(L.type):Wt(L),{options:it,selectedKey:at}=qt({machine:s,currentWorkspacePath:Ie});Et({title:`Launch ${Be}?`,description:"Review or change the target workspace before launching this stopped session again.",confirmLabel:"Launch",workspaceOptions:it,selectedWorkspaceKey:at,details:[{label:"Mode",value:x.label},{label:"Provider",value:Be}]},async()=>{const Je=it.find(fs=>fs.key===Le.current);await Ee({type:L.type,workspaceId:(Je==null?void 0:Je.workspaceId)??null,workspacePath:(Je==null?void 0:Je.workspacePath)??"",useHome:!(Je!=null&&Je.workspaceId)&&!(Je!=null&&Je.workspacePath),model:oe==null?void 0:oe.currentModel})})},disabled:ae.includes(L.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:ae.includes(L.type)?"⏳":e.jsx(en,{size:14})}):e.jsx("button",{onClick:()=>_t(L),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(bt,{size:14})})]})]}),Z&&Z.aiAgents.length>0&&e.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Z.aiAgents.map(Ie=>e.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${za(Ie.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ie.name," · ",rt(Ie.status)]},Ie.id))}),Z&&(St[Z.type]||[]).length>0&&u&&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:(St[Z.type]||[]).map(Ie=>e.jsxs("button",{disabled:ps===`${Z.type}.${Ie.type}`,onClick:async()=>{const Be=`${Z.type}.${Ie.type}`;_e(Be);try{await u(r,"set_ide_extension",{ideType:Z.type,extensionType:Ie.type,enabled:!Ie.enabled}),Mt(it=>({...it,[Z.type]:(it[Z.type]||[]).map(at=>at.type===Ie.type?{...at,enabled:!at.enabled}:at)}))}catch(it){console.error("Extension toggle failed:",it)}finally{_e(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 ${Ie.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 ${Ie.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ie.name,e.jsx("span",{className:"text-[9px] font-normal",children:Ie.enabled?"ON":"OFF"})]},Ie.type))})]})]},L.id)})]}),q&&u&&e.jsx(hr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:te,directories:fe,busy:xe,error:H,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:L=>{Xe(L)},onConfirm:L=>{le(L),be("__custom__"),se(!1)}}),ce&&e.jsx(xn,{title:ce.title,description:ce.description,details:ce.details,workspaceOptions:ce.workspaceOptions,selectedWorkspaceKey:De,onWorkspaceChange:L=>{Le.current=L,Re(L)},confirmLabel:ce.confirmLabel,busy:ot,onConfirm:Nt,onCancel:()=>{Q.current=null,Ne(null)}}),F&&kt&&e.jsx(cn,{activeConv:kt,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:z,isSavedSessionsLoading:Y,isResumingSavedSessionId:me,onClose:()=>D(!1),onNewChat:()=>{$(""),D(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Te(E)},onResumeSavedSession:L=>{if(!L.canResume||me)return;const Z=Se(L);$(L.providerSessionId),je(L),ie(L.providerSessionId),D(!1),Ee({type:L.providerType,workspaceId:Z.workspaceId,workspacePath:Z.workspacePath,useHome:Z.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{ie(oe=>oe===L.providerSessionId?null:oe)})}})]})}const ya=[{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 gm({machine:t,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:u,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:p,sendDaemonCommand:h}){var d;const[g,C]=a.useState(m);a.useEffect(()=>{C(m)},[m]);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:ya.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 ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>C(b.id),children:[e.jsx("span",{children:b.label}),e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===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:(d=ya.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&e.jsx(Kr,{category:"ide",machine:t,machineId:s,providers:r,managedEntries:n,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p}),g==="cli"&&e.jsx(Kr,{category:"cli",machine:t,machineId:s,providers:r,managedEntries:o,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p}),g==="acp"&&e.jsx(Kr,{category:"acp",machine:t,machineId:s,providers:r,managedEntries:i,getIcon:u,actions:c,sendDaemonCommand:h,initialWorkspaceId:f,initialWorkspacePath:p})]})}function ym({onNicknameSynced:t}={}){var ne,le,ae,de,q,se,te,ge,fe;const{id:s}=gi(),r=ds(),n=Xr(),{sendCommand:o}=mt(),i=$s(),c=Xa(),u=c.ides||[],m=c.initialLoaded??!0,f=u.find(R=>R.id===s&&R.type==="adhdev-daemon"),p=u.some(R=>R.type==="adhdev-daemon"),[h,g]=a.useState("workspace"),[C,I]=a.useState("ide"),d=a.useRef(null),[b,y]=a.useState(null),l=a.useRef("__home__"),[S,M]=a.useState("__home__"),[N,x]=a.useState(!1),w=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),cd(s&&h==="overview"?[s]:[],{enabled:h==="overview",intervalMs:15e3});const v=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},j=Qu({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:t,logsEndRef:w});a.useEffect(()=>nt.onToast(xe=>{c.setToasts(H=>{if(H.some(ce=>ce.message===xe.message&&xe.timestamp-ce.timestamp<3e3))return H;const Q={id:xe.id,message:xe.message,type:xe.type,timestamp:xe.timestamp,targetKey:xe.targetKey,actions:xe.actions};return[...H.slice(-4),Q]});const A=xe.duration||5e3;setTimeout(()=>c.setToasts(H=>H.filter(ee=>ee.id!==xe.id)),A)}),[c]);const B=(f==null?void 0:f.availableProviders)||[],E={};for(const R of B)E[R.type]=R.icon;const W=R=>E[R]||"",T=f?{id:f.id,hostname:Ha(f,{fallbackId:f.id}),platform:((ne=f.machine)==null?void 0:ne.platform)||"unknown",arch:((le=f.machine)==null?void 0:le.arch)||"",cpus:((ae=f.machine)==null?void 0:ae.cpus)||0,totalMem:((de=f.machine)==null?void 0:de.totalMem)||0,freeMem:(q=f.machine)==null?void 0:q.freeMem,availableMem:(se=f.machine)==null?void 0:se.availableMem,loadavg:(te=f.machine)==null?void 0:te.loadavg,uptime:(ge=f.machine)==null?void 0:ge.uptime,release:((fe=f.machine)==null?void 0:fe.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,G=u.filter(R=>R.daemonId===s&&R.type!=="adhdev-daemon").filter(R=>!As(R)&&!as(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,version:R.version||"",instanceId:R.instanceId||"",status:R.status,workspace:R.workspace||null,terminals:R.terminals||0,aiAgents:Nc(R.aiAgents||(R.agents||[]).map(xe=>({id:xe.name,name:xe.name,status:xe.status,version:xe.version}))),activeChat:R.activeChat||null,chats:R.chats||[],childSessions:R.childSessions||[],cdpConnected:R.cdpConnected||!1,daemonId:s})),_=u.filter(R=>R.daemonId===s&&As(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,cliName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,mode:R.mode,runtimeKey:R.runtimeKey,runtimeDisplayName:R.runtimeDisplayName,runtimeWorkspaceLabel:R.runtimeWorkspaceLabel,runtimeWriteOwner:R.runtimeWriteOwner||null,runtimeAttachedClients:R.runtimeAttachedClients||[],daemonId:s})),k=u.filter(R=>R.daemonId===s&&as(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,acpName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,currentModel:R.currentModel,currentPlan:R.currentPlan,daemonId:s})),K=f?dt(f,{fallbackId:s}):"",J="workspace",P=n.state,$=P==null?void 0:P.initialMachineTab,z=P==null?void 0:P.initialWorkspaceCategory,U=P==null?void 0:P.initialWorkspaceId,Y=P==null?void 0:P.initialWorkspacePath,re=$==="ides"||$==="clis"||$==="acps"?"workspace":$||J,pe=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":z,O=[...G.map(R=>{var xe,A,H,ee,Q;return{id:`ide:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.type,kind:"ide",providerType:R.type,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,timestamp:((Q=(ee=(H=(A=R.activeChat)==null?void 0:A.messages)==null?void 0:H.at)==null?void 0:ee.call(H,-1))==null?void 0:Q.timestamp)||0}}),..._.map(R=>{var xe,A,H,ee,Q;return{id:`cli:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.cliName,kind:"cli",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,timestamp:((Q=(ee=(H=(A=R.activeChat)==null?void 0:A.messages)==null?void 0:H.at)==null?void 0:ee.call(H,-1))==null?void 0:Q.timestamp)||0}}),...k.map(R=>{var xe,A,H,ee,Q;return{id:`acp:${R.type}:${R.workspace||""}`,label:((xe=R.activeChat)==null?void 0:xe.title)||R.acpName,kind:"acp",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:R.currentModel||R.workspace||void 0,workspace:R.workspace||void 0,currentModel:R.currentModel,timestamp:((Q=(ee=(H=(A=R.activeChat)==null?void 0:A.messages)==null?void 0:H.at)==null?void 0:ee.call(H,-1))==null?void 0:Q.timestamp)||0}})].sort((R,xe)=>xe.timestamp-R.timestamp).map(({timestamp:R,...xe})=>xe),F=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(R=>({id:R.id,label:R.title||R.providerName||R.providerType,kind:R.kind,providerType:R.providerType,providerSessionId:R.providerSessionId,subtitle:R.currentModel||R.workspace||void 0,workspace:R.workspace,currentModel:R.currentModel})):O,D=a.useMemo(()=>{var xe;const R=((xe=c.connectionStates)==null?void 0:xe[s||""])||void 0;return u.filter(A=>A.daemonId===s&&A.type!=="adhdev-daemon").flatMap(A=>ln(A,{},{connectionStates:s&&R?{[s]:R}:void 0,defaultConnectionState:R})).filter(A=>!(A.transport==="pty"&&A.mode==="terminal")).sort((A,H)=>Gr(H)-Gr(A))},[u,c.connectionStates,s]),me=a.useCallback(R=>{const xe=R.sessionId||R.tabKey;xe&&r(`/dashboard?activeTab=${encodeURIComponent(xe)}`)},[r]),ie=a.useCallback(()=>{d.current&&(x(!0),d.current().finally(()=>{d.current=null,x(!1),y(null)}))},[]),X=a.useCallback(R=>{if(!T)return;const{options:xe,selectedKey:A}=qt({machine:T,currentWorkspacePath:R.workspace}),H=async()=>{I(R.kind),g("workspace")};d.current=async()=>{const ee=xe.find(Ne=>Ne.key===l.current),Q=(ee==null?void 0:ee.workspacePath)??null,ce=(ee==null?void 0:ee.workspaceId)??null;if(R.kind==="ide"&&R.providerType){await j.handleLaunchIde(R.providerType,Q?{workspace:Q}:void 0);return}if((R.kind==="cli"||R.kind==="acp")&&R.providerType){await j.runLaunchCliCore({cliType:R.providerType,dir:ce?void 0:Q||"",workspaceId:ce||void 0,model:R.kind==="acp"?R.currentModel:void 0,resumeSessionId:R.providerSessionId});return}await H()},l.current=A,M(A),y({title:`Launch ${R.label}?`,description:"Recent launches now require one more confirmation before they start.",confirmLabel:"Launch",workspaceOptions:xe,details:[{label:"Mode",value:R.kind.toUpperCase()},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]})},[j,T]);if(a.useEffect(()=>{g(re)},[J,re,s]),a.useEffect(()=>{pe&&I(pe)},[pe,s]),!T)return m?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:v,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 be=[{id:"workspace",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{size:14})," Workspace"]}),count:G.length+_.length+k.length},{id:"session-host",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{size:14})," Session Host"]})},{id:"providers",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(cr,{size:14})," Providers"]})},{id:"overview",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Di,{size:14})," System"]})},{id:"logs",label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Li,{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:v,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:R=>j.setNicknameInput(R.target.value),onKeyDown:R=>{R.key==="Enter"&&j.handleSaveNickname(),R.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(T.machineNickname||"")},title:"Click to set nickname",children:K}),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:[T.platform," · ",T.arch]}),e.jsxs("span",{children:[T.cpus," cores"]}),(f==null?void 0:f.version)&&e.jsxs("span",{children:["v",f.version]}),T.p2p.available&&e.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&e.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),e.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:be.map(R=>e.jsxs("button",{onClick:()=>g(R.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===R.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[R.label,R.count!==void 0&&e.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===R.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:R.count})]},R.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(fm,{machineEntry:f,providers:B,recentLaunches:F,currentConversations:D,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:X,onOpenConversation:me}),e.jsx(gm,{machine:T,machineId:s,providers:B,ideSessions:G,cliSessions:_,acpSessions:k,actions:j,getIcon:W,initialCategory:C,initialWorkspaceId:U,initialWorkspacePath:Y,sendDaemonCommand:o})]}),h==="providers"&&e.jsx(om,{machineId:s,providers:B,sendDaemonCommand:o}),h==="overview"&&e.jsx(em,{machineId:s,machine:T,ideSessions:G,cliSessions:_,acpSessions:k,actions:j,sendDaemonCommand:o}),h==="session-host"&&e.jsx(mm,{machineId:s,cliSessions:_,sendDaemonCommand:o}),h==="logs"&&e.jsx(im,{machineId:s,sendDaemonCommand:o})]})})}),j.launchPick&&T&&e.jsx(pm,{machine:T,launchPick:j.launchPick,actions:j}),b&&e.jsx(xn,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:R=>{l.current=R,M(R)},confirmLabel:b.confirmLabel,busy:N,onConfirm:ie,onCancel:()=>{d.current=null,y(null)}}),e.jsx(to,{toasts:c.toasts||[],onDismiss:R=>c.setToasts(xe=>xe.filter(A=>A.id!==R)),onClickToast:R=>{R.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(R.targetKey)}`)}}),e.jsx("style",{children:`
|
|
54
54
|
@keyframes toast-in {
|
|
55
55
|
from { opacity: 0; transform: translateX(40px); }
|
|
56
56
|
to { opacity: 1; transform: translateX(0); }
|
|
57
57
|
}
|
|
58
|
-
`})]})}class vm{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,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 Mt=new vm;function wm(){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 Xs=wm(),va=3e3,jm=3e4;let Ct=null,km=0;const ir=new Map;let Ut=null,Cs=null;function wa(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function ws(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function Nm(t){return t==="connected"?"connected":t}async function tr(t,s,r){const n=ul(t,r||{}),o=Ct;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++km}_${Date.now()}`;return new Promise((c,d)=>{const m=setTimeout(()=>{ir.delete(i),d(new Error(`WS command timeout: ${s}`))},3e4);ir.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),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 Yr(t,s){const r=Ct;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Sm{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ct==null?void 0:Ct.readyState)===WebSocket.OPEN}get connectionState(){return(Ct==null?void 0:Ct.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return tr(this.daemonId,s,r)}async sendInput(s,r){return tr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Ut&&(clearInterval(Ut),Ut=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await tr(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());Mt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Ut=setInterval(r,2e3)}stopScreenshots(s){Ut&&(clearInterval(Ut),Ut=null)}}let ht=null;function Cm(t){return(!ht||ht.daemonId!==t)&&(ht=new Sm(t)),ht}function Im({children:t}){const s=a.useRef(rr()),r=rr();s.current=r;const{setUserName:n}=Yt(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,d]=a.useState("disconnected"),m=a.useCallback((l,b)=>{d(l),Cs==null||Cs(l,b)},[]),f=a.useRef(null),p=a.useRef(),h=a.useRef(va),g=a.useRef(!0),C=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{g.current=!0,C.current=!1;function l(){var u,S;if(!g.current||((u=f.current)==null?void 0:u.readyState)===WebSocket.OPEN||((S=f.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${Xs}...`),ws("connect_attempt",{url:Xs,reason:I.current,delayMs:h.current});let y;try{y=new WebSocket(Xs)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}f.current=y,y.onopen=()=>{if(!g.current){y.close();return}m("connected"),h.current=va,ws("open",{url:Xs,reason:I.current}),Dt.resubscribeAll({sendData:Yr}),console.log("[Standalone WS] Connected")},Ct=y,y.onmessage=_=>{var N,x;try{const w=JSON.parse(_.data);if((w.type==="command_result"||w.type==="error")&&w.requestId){const v=ir.get(w.requestId);v&&(ir.delete(w.requestId),w.type==="error"?v.reject(new Error(((N=w.data)==null?void 0:N.message)||"Command failed")):v.resolve(w.data));return}if(w.type==="session_output"){const v=w.sessionId||w.cliId||w.cliType;v&&Mt.emitSessionOutput(v,typeof w.data=="string"?w.data:"",typeof w.seq=="number"?w.seq:void 0);return}if(w.type==="runtime_snapshot"){Mt.emitRuntimeSnapshot(w.sessionId,typeof w.text=="string"?w.text:"",typeof w.seq=="number"?w.seq:0,!!w.truncated);return}if(w.type==="topic_update"){const v=w.update;v&&Dt.publish(v);return}if(w.type==="status"||w.type==="initial_state"){const v=w.data;if(!v)return;const{injectEntries:j,markLoaded:B,getIdes:E}=s.current,W=v.instanceId||"standalone",T=E().find(k=>k.id===W),G=Cm(W);Mt.register(W,G),Mt.setState(W,"connected"),m("connected",W),Mt.emitStatus(W,v);const A=ar(v,{daemonId:W,existingDaemon:T,existingEntries:E()});wa("ws_status",{type:w.type,daemonId:W,sessions:(v.sessions||[]).map(k=>({id:k.id,parentId:k.parentId,providerType:k.providerType,kind:k.kind,transport:k.transport,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,title:k.title})),recentLaunches:(v.recentLaunches||[]).map(k=>({id:k.id,providerType:k.providerType,kind:k.kind,workspace:k.workspace,lastLaunchedAt:k.lastLaunchedAt}))}),wa("entries",{daemonId:W,entries:A.filter(k=>k.type!=="adhdev-daemon").map(k=>({id:k.id,type:k.type,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,sessionId:k.sessionId}))}),A.length>0&&j(A,{authoritativeDaemonIds:[W]}),B(),c.current!==W&&((x=i.current)==null||x.call(i),c.current=W,i.current=Dt.subscribe({sendData:Yr},W,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${W}`,params:{includeSessions:!0}},k=>{if(k.topic!=="daemon.metadata")return;const K=s.current.getIdes(),J=K.find($=>$.id===W),L=ar(k.status,{daemonId:W,existingDaemon:J,existingEntries:K,timestamp:k.timestamp});L.length>0&&s.current.injectEntries(L),k.userName&&o.current&&o.current(k.userName)}))}}catch(w){console.error("[Standalone WS] Parse error:",w)}},y.onclose=_=>{g.current&&(ht==null||ht.stopScreenshots(),ht&&Mt.setState(ht.daemonId,"disconnected"),m("disconnected"),f.current=null,I.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,ws("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{C.current||!g.current||(I.current="error",ws("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!g.current)return;clearTimeout(p.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),ws("schedule_reconnect",{reason:I.current,delayMs:y}),p.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,jm),l()},y)}return l(),()=>{var y;g.current=!1,C.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Ct=null),ht&&(ht.stopScreenshots(),Mt.unregister(ht.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function _m({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Cs=(c,d)=>{r(c),d&&o(d)},()=>{Cs=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",d=Nm(s),m={};return n&&(m[n]=d),m.standalone=d,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return e.jsx(Si,{connectionOverrides:i,children:e.jsx(Im,{children:t})})}const Am=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Ma,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(cr,{}),label:"Settings"}];function Mm({children:t}){const s=ds(),r=Xr(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),d=p=>{s(p),o(!1)},m=()=>{c(p=>{const h=!p;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},f=p=>`nav-item${r.pathname.startsWith(p)?" 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:p=>p.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:Am.map(p=>e.jsxs("div",{className:f(p.path),id:`nav-${p.id}`,onClick:()=>d(p.path),title:i?p.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.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(Ta,{})}),!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(La,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.37"]}),e.jsx(Ul,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,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 Tm=[{icon:e.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Pt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(Pa,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(ut,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Is,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Ta,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Lm=[{icon:e.jsx(Ea,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Ma,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(dr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(Li,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(Zr,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Ri,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Pm=[{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 Rm(){return e.jsxs(lo,{icon:e.jsx(La,{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.37"]}),children:[e.jsx(wt,{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(wt,{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:Tm.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(wt,{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:no.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:oo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:ao.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(wt,{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(wt,{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:Pm.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(uo,{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(Yi,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Em(){const{ides:t}=Yt(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=mt(),{userName:o}=Yt(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const d=h=>{const g=h.target.value.trim();s!=null&&s.id&&g!==o&&n(s.id,"set_user_name",{userName:g}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=h=>{f(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(lo,{icon:e.jsx(cr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(Dl,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(wt,{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.37"]}),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(wt,{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(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Vl,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(wt,{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(Xl,{})]}),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(nd,{})]}),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(od,{})]})]})}),e.jsx(wt,{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(Hl,{}),e.jsx(Ht,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(qi,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),e.jsx(wt,{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(Ti,{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()}})]})})})]})}zl();sd();const $m=_a({baseUrl:""});function ja(){const{ides:t,initialLoaded:s}=Yt();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(Wr,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Wr,{to:"/dashboard",replace:!0})}function Dm(){return e.jsx(yi,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(_i,{client:$m,children:e.jsx(_m,{children:e.jsx(Mi,{value:{sendCommand:tr,sendData:Yr},children:e.jsx(Mm,{children:e.jsxs(vi,{children:[e.jsx(Ot,{path:"/dashboard",element:e.jsx(Zu,{})}),e.jsx(Ot,{path:"/machine",element:e.jsx(ja,{})}),e.jsx(Ot,{path:"/machines/:id",element:e.jsx(ym,{})}),e.jsx(Ot,{path:"/machines",element:e.jsx(ja,{})}),e.jsx(Ot,{path:"/about",element:e.jsx(Rm,{})}),e.jsx(Ot,{path:"/settings",element:e.jsx(Em,{})}),e.jsx(Ot,{path:"*",element:e.jsx(Wr,{to:"/dashboard",replace:!0})})]})})})})})})}Yc({connectionManager:Mt});wi(document.getElementById("root")).render(e.jsx(Dm,{}));
|
|
58
|
+
`})]})}class vm{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,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 At=new vm;function wm(){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 Xs=wm(),va=3e3,jm=3e4;let Ct=null,km=0;const ir=new Map;let Ht=null,Cs=null;function wa(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${t}`,s)}catch{}}function ws(t,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${t}`,s)}catch{}}function Nm(t){return t==="connected"?"connected":t}async function tr(t,s,r){const n=ul(t,r||{}),o=Ct;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++km}_${Date.now()}`;return new Promise((c,u)=>{const m=setTimeout(()=>{ir.delete(i),u(new Error(`WS command timeout: ${s}`))},3e4);ir.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),u(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Yr(t,s){const r=Ct;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Sm{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Ct==null?void 0:Ct.readyState)===WebSocket.OPEN}get connectionState(){return(Ct==null?void 0:Ct.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return tr(this.daemonId,s,r)}async sendInput(s,r){return tr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Ht&&(clearInterval(Ht),Ht=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await tr(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());At.emitScreenshot(this.daemonId,o)}}catch{}};r(),Ht=setInterval(r,2e3)}stopScreenshots(s){Ht&&(clearInterval(Ht),Ht=null)}}let ht=null;function Cm(t){return(!ht||ht.daemonId!==t)&&(ht=new Sm(t)),ht}function Im({children:t}){const s=a.useRef(rr()),r=rr();s.current=r;const{setUserName:n}=Yt(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,u]=a.useState("disconnected"),m=a.useCallback((d,b)=>{u(d),Cs==null||Cs(d,b)},[]),f=a.useRef(null),p=a.useRef(),h=a.useRef(va),g=a.useRef(!0),C=a.useRef(!1),I=a.useRef("initial_connect");return a.useEffect(()=>{g.current=!0,C.current=!1;function d(){var l,S;if(!g.current||((l=f.current)==null?void 0:l.readyState)===WebSocket.OPEN||((S=f.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${Xs}...`),ws("connect_attempt",{url:Xs,reason:I.current,delayMs:h.current});let y;try{y=new WebSocket(Xs)}catch(M){console.error("[Standalone WS] Failed to create WebSocket:",M),b();return}f.current=y,y.onopen=()=>{if(!g.current){y.close();return}m("connected"),h.current=va,ws("open",{url:Xs,reason:I.current}),Dt.resubscribeAll({sendData:Yr}),console.log("[Standalone WS] Connected")},Ct=y,y.onmessage=M=>{var N,x;try{const w=JSON.parse(M.data);if((w.type==="command_result"||w.type==="error")&&w.requestId){const v=ir.get(w.requestId);v&&(ir.delete(w.requestId),w.type==="error"?v.reject(new Error(((N=w.data)==null?void 0:N.message)||"Command failed")):v.resolve(w.data));return}if(w.type==="session_output"){const v=w.sessionId||w.cliId||w.cliType;v&&At.emitSessionOutput(v,typeof w.data=="string"?w.data:"",typeof w.seq=="number"?w.seq:void 0);return}if(w.type==="runtime_snapshot"){At.emitRuntimeSnapshot(w.sessionId,typeof w.text=="string"?w.text:"",typeof w.seq=="number"?w.seq:0,!!w.truncated);return}if(w.type==="topic_update"){const v=w.update;v&&Dt.publish(v);return}if(w.type==="status"||w.type==="initial_state"){const v=w.data;if(!v)return;const{injectEntries:j,markLoaded:B,getIdes:E}=s.current,W=v.instanceId||"standalone",T=E().find(k=>k.id===W),G=Cm(W);At.register(W,G),At.setState(W,"connected"),m("connected",W),At.emitStatus(W,v);const _=ar(v,{daemonId:W,existingDaemon:T,existingEntries:E()});wa("ws_status",{type:w.type,daemonId:W,sessions:(v.sessions||[]).map(k=>({id:k.id,parentId:k.parentId,providerType:k.providerType,kind:k.kind,transport:k.transport,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,title:k.title})),recentLaunches:(v.recentLaunches||[]).map(k=>({id:k.id,providerType:k.providerType,kind:k.kind,workspace:k.workspace,lastLaunchedAt:k.lastLaunchedAt}))}),wa("entries",{daemonId:W,entries:_.filter(k=>k.type!=="adhdev-daemon").map(k=>({id:k.id,type:k.type,unread:k.unread,inboxBucket:k.inboxBucket,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,sessionId:k.sessionId}))}),_.length>0&&j(_,{authoritativeDaemonIds:[W]}),B(),c.current!==W&&((x=i.current)==null||x.call(i),c.current=W,i.current=Dt.subscribe({sendData:Yr},W,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${W}`,params:{includeSessions:!0}},k=>{if(k.topic!=="daemon.metadata")return;const K=s.current.getIdes(),J=K.find($=>$.id===W),P=ar(k.status,{daemonId:W,existingDaemon:J,existingEntries:K,timestamp:k.timestamp});P.length>0&&s.current.injectEntries(P),k.userName&&o.current&&o.current(k.userName)}))}}catch(w){console.error("[Standalone WS] Parse error:",w)}},y.onclose=M=>{g.current&&(ht==null||ht.stopScreenshots(),ht&&At.setState(ht.daemonId,"disconnected"),m("disconnected"),f.current=null,I.current=`close:${M.code}${M.wasClean?":clean":":unclean"}`,ws("close",{code:M.code,reason:M.reason||"",wasClean:M.wasClean}),b())},y.onerror=M=>{C.current||!g.current||(I.current="error",ws("error",{message:M instanceof Event?"event":String(M),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",M))}}function b(){if(!g.current)return;clearTimeout(p.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),ws("schedule_reconnect",{reason:I.current,delayMs:y}),p.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,jm),d()},y)}return d(),()=>{var y;g.current=!1,C.current=!0,(y=i.current)==null||y.call(i),i.current=null,c.current=null,clearTimeout(p.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Ct=null),ht&&(ht.stopScreenshots(),At.unregister(ht.daemonId))}},[]),e.jsx(e.Fragment,{children:t})}function Mm({children:t}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Cs=(c,u)=>{r(c),u&&o(u)},()=>{Cs=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",u=Nm(s),m={};return n&&(m[n]=u),m.standalone=u,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return e.jsx(Si,{connectionOverrides:i,children:e.jsx(Im,{children:t})})}const _m=[{id:"dashboard",path:"/dashboard",icon:e.jsx(Aa,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:e.jsx(Bt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:e.jsx(cr,{}),label:"Settings"}];function Am({children:t}){const s=ds(),r=Xr(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),u=p=>{s(p),o(!1)},m=()=>{c(p=>{const h=!p;try{localStorage.setItem("sidebar-collapsed",h?"1":"0")}catch{}return h})},f=p=>`nav-item${r.pathname.startsWith(p)?" 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:p=>p.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:_m.map(p=>e.jsxs("div",{className:f(p.path),id:`nav-${p.id}`,onClick:()=>u(p.path),title:i?p.label:void 0,children:[e.jsx("span",{className:"nav-icon",children:p.icon}),!i&&p.label]},p.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(Ta,{})}),!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(Pa,{})}),!i&&"About"]}),!i&&e.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.39"]}),e.jsx(Hl,{collapsed:i}),e.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,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 Tm=[{icon:e.jsx(Bt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:e.jsx(Lt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:e.jsx(La,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:e.jsx(ut,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:e.jsx(Is,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:e.jsx(Ta,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Pm=[{icon:e.jsx(Ea,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:e.jsx(Aa,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:e.jsx(dr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:e.jsx(Pi,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:e.jsx(Zr,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:e.jsx(Ri,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Lm=[{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 Rm(){return e.jsxs(lo,{icon:e.jsx(Pa,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:e.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.39"]}),children:[e.jsx(wt,{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(wt,{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:Tm.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(wt,{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:no.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:oo.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:ao.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(wt,{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:Pm.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(wt,{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:Lm.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(uo,{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(Yi,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Em(){const{ides:t}=Yt(),s=t.find(h=>h.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=mt(),{userName:o}=Yt(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const u=h=>{const g=h.target.value.trim();s!=null&&s.id&&g!==o&&n(s.id,"set_user_name",{userName:g}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),p=h=>{f(h);try{localStorage.setItem("adhdev_sound",h?"1":"0")}catch{}};return e.jsxs(lo,{icon:e.jsx(cr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[e.jsx(Dl,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),e.jsx(wt,{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.39"]}),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(wt,{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(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:e.jsx(Vl,{ides:t,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),e.jsx(wt,{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(Xl,{})]}),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(nd,{})]}),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(od,{})]})]})}),e.jsx(wt,{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(Ul,{}),e.jsx(Ut,{label:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(qi,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:p})]})}),e.jsx(wt,{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(Ti,{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:u,onKeyDown:h=>{h.key==="Enter"&&h.currentTarget.blur()}})]})})})]})}zl();sd();const $m=Ma({baseUrl:""});function ja(){const{ides:t,initialLoaded:s}=Yt();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(Wr,{to:`/machines/${r.id}`,replace:!0}):e.jsx(Wr,{to:"/dashboard",replace:!0})}function Dm(){return e.jsx(yi,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:e.jsx(Mi,{client:$m,children:e.jsx(Mm,{children:e.jsx(Ai,{value:{sendCommand:tr,sendData:Yr},children:e.jsx(Am,{children:e.jsxs(vi,{children:[e.jsx(Ot,{path:"/dashboard",element:e.jsx(Zu,{})}),e.jsx(Ot,{path:"/machine",element:e.jsx(ja,{})}),e.jsx(Ot,{path:"/machines/:id",element:e.jsx(ym,{})}),e.jsx(Ot,{path:"/machines",element:e.jsx(ja,{})}),e.jsx(Ot,{path:"/about",element:e.jsx(Rm,{})}),e.jsx(Ot,{path:"/settings",element:e.jsx(Em,{})}),e.jsx(Ot,{path:"*",element:e.jsx(Wr,{to:"/dashboard",replace:!0})})]})})})})})})}Yc({connectionManager:At});wi(document.getElementById("root")).render(e.jsx(Dm,{}));
|