@adhdev/daemon-standalone 0.8.59 → 0.8.61
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 +498 -345
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/public/assets/index-BO4uW4q9.css +1 -0
- package/public/assets/index-C772_8TV.js +72 -0
- package/public/index.html +2 -2
- package/public/assets/index-DY0zxjVr.css +0 -1
- package/public/assets/index-DeYeBflN.js +0 -73
|
@@ -0,0 +1,72 @@
|
|
|
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 xc=Object.defineProperty;var hc=(e,s,r)=>s in e?xc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var ct=(e,s,r)=>hc(e,typeof s!="symbol"?s+"":s,r);import{r as a,j as t,M as $n,a as Bn,b as No,c as So,u as Cs,R as et,d as zs,t as bc,e as gc,D as yc,f as kn,g as Nn,h as Wn,i as vc,k as wc,B as jc,l as kc,m as Yt,N as Sn,n as Nc}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();function Sc(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const o={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(o),r.length>s&&r.splice(0,r.length-s),o},list(n={}){const o=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-o).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const as=Sc();function ja(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}const Co=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}),Io=a.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ka(e){var r,n;let s=0;return"activeChat"in e&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function Qr(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},o=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,l=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,m=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return o&&(n.version=o),i&&(n.serverVersion=i),m&&(n.versionUpdateReason=m),o&&i&&o===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&o&&i&&o!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Ir(e){return Array.isArray(e)?e.map(Ir):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,Ir(r)]))}function Cc(e,s){try{return JSON.stringify(Ir(e))===JSON.stringify(Ir(s))}catch{return!1}}function sr(e,s,r){return Cc(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Ic(e,s,r){var m,f,u,x,w,C,L;const n=Date.now(),o=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of e){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const k=ka(d),p=ka(b);if(k>p){const N=(m=d.chats)!=null&&m.length?d.chats:b.chats,R=Qr(b,d,{...b,...d,chats:N,_lastUpdate:n});i.set(d.id,sr(b,R,n))}else if(k<p){const N={};if(d.status&&d.status!==b.status&&(N.status=d.status),d.cdpConnected!==void 0&&(N.cdpConnected=d.cdpConnected),(f=d.chats)!=null&&f.length&&!((u=b.chats)!=null&&u.length)&&(N.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(N.machineNickname=d.machineNickname),d.version!==void 0&&(N.version=d.version),d.serverVersion!==void 0&&(N.serverVersion=d.serverVersion),d.versionMismatch===!0&&(N.versionMismatch=!0),Object.keys(N).length>0){const R=Qr(b,d,{...b,...N,_lastUpdate:b._lastUpdate});i.set(d.id,sr(b,R,n))}else sr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const N=d.timestamp||n,R=b._lastUpdate||b.timestamp||0;if(N>=R){const y=(x=d.chats)!=null&&x.length?d.chats:b.chats,v=Qr(b,d,{...b,...d,chats:y,_lastUpdate:n});i.set(d.id,sr(b,v,n))}else(w=d.chats)!=null&&w.length&&!((C=b.chats)!=null&&C.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const b=d.daemonId||((L=d.id)==null?void 0:L.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const k=b.daemonId||d.split(":")[0];if(!l.has(k))continue;if(o.has(k)&&!c.has(d)){i.delete(d);continue}const p=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&p>1e4||b.transport==="acp"&&!c.has(d)&&p>1e4||b.transport==="cdp-page"&&!c.has(d)&&p>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 Tc(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Ac({children:e,connectionOverrides:s}){const[r,n]=a.useState([]),[o,i]=a.useState(!1),[c,l]=a.useState([]),[m,f]=a.useState(void 0),u=a.useRef(r);a.useEffect(()=>{u.current=r},[r]);const x=a.useCallback((k,p)=>{n(N=>{let R=!1;const y=N.map(v=>v.id!==k||v.chats===p?v:(R=!0,{...v,chats:p}));return R?y:N})},[]),w=a.useCallback((k,p)=>{n(N=>{const R=N.length===0?k:Ic(k,N,p),y=!Tc(N,R);return y&&as.record({kind:"dashboard.entries_applied",payload:{incoming:ja(k),next:ja(R)}}),y?R:N})},[]),C=a.useCallback(()=>i(!0),[]),L=a.useMemo(()=>({injectEntries:w,markLoaded:C,getIdes:()=>u.current}),[w,C]),d=s,b=a.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:o,toasts:c,setToasts:l,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,x,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 t.jsx(Io.Provider,{value:L,children:t.jsx(Co.Provider,{value:b,children:e})})}function os(){return a.useContext(Co)}function Tr(){return a.useContext(Io)}function To(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function o(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const m=r==null?void 0:r(),f=o(l),u=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return m&&u.searchParams.set("token",m),!l.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,m={}){const f={"Content-Type":"application/json",...m.headers||{}},u=r==null?void 0:r();u&&(f.Authorization=`Bearer ${u}`);const x=o(l),w=new AbortController,C=setTimeout(()=>w.abort(),15e3);try{const L=await fetch(x,{...m,headers:f,signal:w.signal});if(L.status===401)throw n==null||n(),new Error("Unauthorized");if(!L.ok){const d=await L.json().catch(()=>({error:L.statusText}));throw new Error(d.error||`API Error: ${L.status}`)}return L.json()}finally{clearTimeout(C)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,m,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),execTerminal:(l,m,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:f})}),sendAgentMessage:(l,m,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,m,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:m,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,m,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Mc=To({baseUrl:"http://localhost:3847"}),Lc=a.createContext(Mc);function _c({client:e,children:s}){return t.jsx(Lc.Provider,{value:e,children:s})}const Rc={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ao=a.createContext(Rc);function Pc({value:e,children:s}){return t.jsx(Ao.Provider,{value:e,children:s})}function _t(){return a.useContext(Ao)}const Ee={size:18};function Mo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Kn({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ht({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function On({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Dc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Ec({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Lo({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.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"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function $c({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function $r({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.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 _o({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Bc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ut({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 It({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Hn({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Wc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function vs({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Is({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function is({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Fs({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Ro({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Po({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Do({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Kc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Br({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Oc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Un({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Hc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function kt({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Uc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function zc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Fc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Vc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.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 Wr({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Gc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function qc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Yc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Xc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Qc({size:e=Ee.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Jc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.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 Zc({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.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 el({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function tl({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function sl({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function rl({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Na({size:e=Ee.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Sa(e){return!!e&&typeof e=="object"&&"text"in e}function zn(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(i=>typeof i=="string"?i:Sa(i)?String(i.text||""):"").join(r):Sa(e)?o=String(e.text||""):o=String(e||""),n?o.replace(/\s+/g," ").trim():o}function Vs(e){return zn(e,{normalizeWhitespace:!0})}const Jr=new Map;function Eo(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function nl(e,s,r){return Number(e.receivedAt||r[hs(e,s)]||0)||0}function $o(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function al(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function rr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function Zr(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Ca(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):$o(e)?t.jsx($n,{remarkPlugins:[Bn,No,So],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function nr({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:Ca(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const o=Zr(r);return o?t.jsx("img",{src:o,alt:rr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const o=Zr(r);return o?t.jsx("audio",{controls:!0,src:o,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const o=Zr(r);return o?t.jsx("video",{controls:!0,src:o,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:rr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||rr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const o=rr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:o}),Ca(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${n}`)}return null})})}function hs(e,s){const r=e,n=zn(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const ol=a.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx($n,{remarkPlugins:[Bn],children:s.text}),t.jsx("span",{className:"action-time",children:Eo(s.timestamp)})]})},(e,s)=>e.log===s.log),il=a.memo(function({message:s,receivedAt:r,agentName:n,userName:o,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var v,j,g;const m=(s.role||"").toLowerCase(),f=m==="user"||m==="human",u=s.kind||(m==="tool"?"tool":"standard"),x=al(s.content)?s.content:null,w=!!(x!=null&&x.some(h=>h.type!=="text")),C=zn(s.content,{joiner:`
|
|
4
|
+
`});if(u==="thought"){const h=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Fc,{size:13}),t.jsx("span",{children:h})]}),t.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),w&&x?t.jsx("div",{className:"tool-text w-full",children:t.jsx(nr,{parts:x,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const h=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",K=typeof((g=s.meta)==null?void 0:g.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:h}),t.jsx("span",{children:K})]}),w&&x?t.jsx("div",{className:"chat-msg-body",children:t.jsx(nr,{parts:x,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:w&&x?t.jsx(nr,{parts:x,renderAsPreformatted:!1}):C.slice(0,100)});const L=s.meta,b=(typeof(L==null?void 0:L.renderMode)=="string"?L.renderMode.trim():"")==="preformatted",k=C,p=!1,N=k,R=b,y=!R&&$o(N);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(k||w||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${k||w?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?o||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Eo(r)})]}),(k||w)&&t.jsx("div",{className:"chat-markdown",children:w&&x?t.jsx(nr,{parts:x,renderAsPreformatted:R}):R?t.jsx("pre",{className:"chat-preformatted",children:N}):y?t.jsx($n,{remarkPlugins:[Bn,No,So],children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),p]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),cl=a.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:o,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:m={},emptyState:f,onLoadMore:u,isLoadingMore:x,hasMoreHistory:w,hiddenLiveCount:C=0,loadError:L,scrollToBottomRequestNonce:d},b){var ve;const k=a.useRef(null),p=a.useRef(null),N=a.useRef(null),R=a.useRef(0),y=a.useRef(""),v=a.useRef(!1),j=a.useRef(null),g=a.useRef(!1),h=a.useRef(null),K=a.useRef(!1),[I,A]=a.useState(new Set),M=a.useRef(!1),O=a.useRef(!1),_=()=>{const te=k.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},S=a.useCallback((te="auto")=>{const ne=k.current;ne&&ne.scrollTo({top:ne.scrollHeight,behavior:te})},[]),H=a.useCallback(()=>{const te=k.current;!te||!l||Jr.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight)})},[l]),q=a.useCallback(()=>{var re;const te=k.current,ne=(re=window.getSelection)==null?void 0:re.call(window);if(!te||!ne||ne.rangeCount===0||ne.isCollapsed){K.current=!1;return}const V=ne.anchorNode,ie=ne.focusNode;K.current=!!(V&&ie&&te.contains(V)&&te.contains(ie))},[]),T=a.useCallback((te="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,S(te)})},[S]),D=s.length>0?`${s.length}:${(((ve=s[s.length-1])==null?void 0:ve.content)||"").length}`:"0:0";a.useEffect(()=>{const te=!v.current,ne=y.current!==l;if(y.current=l,te||ne){if(v.current=!0,M.current=!1,g.current=!0,!K.current){const ie=l?Jr.get(l):null;ie?requestAnimationFrame(()=>{const re=k.current;if(!re)return;const Z=Math.max(0,re.scrollHeight-re.clientHeight-ie.fromBottom);re.scrollTop=Number.isFinite(Z)?Z:ie.top,O.current=!0}):T("auto")}R.current=s.length;return}s.length>R.current?!M.current&&!K.current&&T("auto"):_()&&!M.current&&!K.current&&T("auto"),R.current=s.length},[D,l,c,s.length,T]),a.useEffect(()=>{d&&(M.current=!1,g.current=!0,O.current=!0,h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{g.current=!1,h.current=null},180),K.current||T("auto"))},[T,d]),a.useEffect(()=>()=>{H(),j.current!=null&&cancelAnimationFrame(j.current),h.current!=null&&window.clearTimeout(h.current)},[H]),a.useEffect(()=>{const te=p.current;if(!te)return;const ne=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{g.current=!1,h.current=null},180)},V=new ResizeObserver(()=>{g.current&&(K.current||(T("auto"),ne()))});return V.observe(te),()=>{V.disconnect(),h.current!=null&&(window.clearTimeout(h.current),h.current=null)}},[T,l]),a.useImperativeHandle(b,()=>({scrollToBottom:(te="smooth")=>{S(te)}}),[S]),a.useEffect(()=>{const te=k.current;if(!te)return;let ne;const V=()=>{clearTimeout(ne),ne=setTimeout(()=>{M.current=!_(),H()},50)};return te.addEventListener("scroll",V,{passive:!0}),()=>{te.removeEventListener("scroll",V),clearTimeout(ne)}},[H]),a.useEffect(()=>(document.addEventListener("selectionchange",q),()=>document.removeEventListener("selectionchange",q)),[q]);const W=a.useRef(0),z=a.useRef(!1);a.useEffect(()=>{const te=k.current;if(!te||!z.current||W.current===0)return;const ne=te.scrollHeight-W.current;ne>0&&(te.scrollTop=ne),H(),W.current=0,z.current=!1},[s.length,H]),a.useEffect(()=>{if(O.current||!l)return;const te=Jr.get(l),ne=k.current;if(!te||!ne)return;const V=Math.max(0,ne.scrollHeight-ne.clientHeight-te.fromBottom);ne.scrollTop=Number.isFinite(V)?V:te.top,O.current=!0},[l,s.length]);const X=()=>{const te=k.current;te&&(W.current=te.scrollHeight),z.current=!0,u==null||u()},he=a.useMemo(()=>{const te=s.map((re,Z)=>({type:"message",data:re,index:Z,ts:nl(re,Z,m)}));if(!r||r.length===0)return te;const ne=[...r].sort((re,Z)=>re.timestamp-Z.timestamp).map((re,Z)=>({type:"action",data:re,index:Z,ts:re.timestamp})),V=[];let ie=0;for(const re of te){for(;ie<ne.length&&re.ts>0&&ne[ie].ts<re.ts;)V.push(ne[ie++]);V.push(re)}for(;ie<ne.length;)V.push(ne[ie++]);return V},[s,r,m]),Te=C>0||!!w,je=C>0?`↑ Show ${Math.min(C,80)} earlier messages${C>80?` (${C} hidden)`:""}`:L?`↻ ${L}`:"↑ Load older messages";return t.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:p,className:"chat-container-content",children:[x&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Te&&!x&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:X,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${L&&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:je})}),he.length===0&&!Te&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),he.map(te=>{if(te.type==="action"){const se=te.data;return t.jsx(ol,{log:se},`action-${te.index}`)}const ne=te.data,V=te.index,ie=hs(ne,V),re=ne.receivedAt||m[ie],Z=`${l}-${ie}`,me=I.has(Z);return t.jsx(il,{message:ne,receivedAt:re,agentName:n,userName:o,isCliMode:i,isTextExpanded:me,onToggleTextExpanded:()=>A(se=>{const ce=new Set(se);return me?ce.delete(Z):ce.add(Z),ce})},`msg-${ie}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:N})]})})}),ll=a.memo(cl,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),dl="modulepreload",ul=function(e){return"/"+e},Ia={},ml=function(s,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=Promise.allSettled(r.map(m=>{if(m=ul(m),m in Ia)return;Ia[m]=!0;const f=m.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${u}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":dl,f||(x.as="script"),x.crossOrigin="",x.href=m,l&&x.setAttribute("nonce",l),document.head.appendChild(x),f)return new Promise((w,C)=>{x.addEventListener("load",w),x.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return o.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Ta=!1;const Bo=a.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},o)=>{const i=a.useRef(null),[c,l]=a.useState(null),m=a.useRef([]),f=a.useRef(!1),u=a.useRef(!1),x=a.useRef(!1),w=()=>{const C=i.current;if(C){f.current&&(C.clear(),f.current=!1);for(const L of m.current)C.write(L);m.current=[],u.current&&(C.fit(),u.current=!1),x.current&&(C.bumpResize(),x.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,L)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(C,L)},fit:()=>{i.current?i.current.fit():u.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():x.current=!0}}),[]),a.useEffect(()=>{if(!c)return;const C=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(C)},[c]),a.useEffect(()=>{let C=!1;return ml(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(L=>{Ta||(Ta=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),C||l(()=>L.GhosttyTerminalView)}).catch(L=>{console.error("[CliTerminal] failed to load terminal renderer",L)}),()=>{C=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Bo.displayName="CliTerminal";function ar({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Aa({value:e,max:s,label:r,color:n="#8b5cf6",detail:o,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),o&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function pl({cursorPos:e,viewportRef:s,imgRef:r}){var p;if(!e||!r.current)return null;const n=r.current,o=n.getBoundingClientRect(),i=(p=s.current)==null?void 0:p.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||o.width,l=n.naturalHeight||o.height,m=c/l,f=o.width/o.height;let u,x,w,C;m>f?(u=o.width,x=o.width/m,w=0,C=(o.height-x)/2):(x=o.height,u=o.height*m,w=(o.width-u)/2,C=0);const L=o.left-i.left+w+u*e.nx,d=o.top-i.top+C+x*e.ny,b=Math.max(8,Math.min(i.width-8,L)),k=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:k-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.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 fl({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:o,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:m,isConnActive:f,zoom:u,isMobile:x,mobileFillZoom:w,onZoomOut:C,onZoomReset:L,onZoomIn:d,transportType:b,screenshotUsage:k,lastActionStatus:p}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.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:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{m(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(N=>!N),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.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:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),b==="direct"&&t.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"&&t.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"}),k&&k.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:k.budgetExhausted?"TURN blocked":`TURN ${k.dailyUsedMinutes}/${k.dailyBudgetMinutes}m`}),p&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:p})]})]}),o&&t.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(x?w:1)+.01?x?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:N=>{N.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:"−"}),t.jsx("button",{onClick:N=>{N.stopPropagation(),L()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:x?"FILL":"FIT"}),t.jsx("button",{onClick:N=>{N.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 xl({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.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:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function hl(){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 Ma(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function Js(e,s){const r=a.useRef(null),n=a.useRef(0);a.useEffect(()=>{if(!hl())return;n.current+=1;const o=r.current;if(!o){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,Ma(l)]))}),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] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Ma(s[c])]))}),r.current=s})}function bl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:o,minZoom:i,zoomRef:c,panXRef:l,panYRef:m,setPanX:f,setPanY:u,setZoom:x,lastWheelTimeRef:w,onAction:C,setLastActionStatus:L,spawnRippleFromNormalized:d,clampPan:b,isMobile:k,mobileFillZoom:p}){const[N,R]=a.useState(null),y=a.useRef(null),v=a.useRef(null),j=a.useRef(null),g=a.useRef(!1),h=a.useRef(null),K=a.useRef(0),I=a.useRef(null),A=a.useRef(1),M=a.useRef({x:0,y:0}),O=a.useRef(!1),_=a.useRef(n),S=a.useRef(C),H=30,q=550,T=18,D=60,W=400,z=12,X=()=>{if(y.current)return;const je={nx:.5,ny:.5};y.current=je,R(je)};return a.useEffect(()=>{_.current=n,n==="mouse"&&X()},[n]),a.useEffect(()=>{S.current=C},[C]),a.useEffect(()=>{const je=e.current;if(!je)return;const ve=Z=>{if(!r.current)return null;const me=r.current.getBoundingClientRect();return!me.width||!me.height?null:{nx:Math.max(0,Math.min(1,(Z.clientX-me.left)/me.width)),ny:Math.max(0,Math.min(1,(Z.clientY-me.top)/me.height))}},te=(Z,me)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,ce=se.getBoundingClientRect(),ee=se.naturalWidth||ce.width,pe=se.naturalHeight||ce.height,ae=ee/pe,Se=ce.width/ce.height;let ge,P;return ae>Se?(ge=ce.width,P=ce.width/ae):(P=ce.height,ge=ce.height*ae),{dnx:Z/ge,dny:me/P}},ne=(Z,me,se)=>{if(se<=1.05)return;const ce=-(Z-.5)*100,ee=-(me-.5)*100,pe=b(ce,ee,se);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-m.current)>.1)&&(f(pe.x),u(pe.y),l.current=pe.x,m.current=pe.y)},V=Z=>{const me=s.current;if(me&&Z.target instanceof Node&&me.contains(Z.target))Z.preventDefault();else return;if(Z.touches.length===1){const se=Z.touches[0];v.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},O.current||(g.current=!1),h.current=setTimeout(()=>{if(!g.current&&!O.current)if(g.current=!0,_.current==="mouse"){const ce=y.current||{nx:.5,ny:.5};L("Right Click"),d(ce.nx,ce.ny,"right"),S.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=ve(se);ce&&(L("Right Click"),d(ce.nx,ce.ny,"right"),S.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(Z.touches.length===2){h.current&&clearTimeout(h.current),g.current=!0,O.current=!0;const se=Z.touches[1].clientX-Z.touches[0].clientX,ce=Z.touches[1].clientY-Z.touches[0].clientY;I.current=Math.sqrt(se*se+ce*ce),A.current=c.current,M.current={x:(Z.touches[0].clientX+Z.touches[1].clientX)/2,y:(Z.touches[0].clientY+Z.touches[1].clientY)/2}}},ie=Z=>{const me=s.current;if(me&&Z.target instanceof Node&&me.contains(Z.target)&&Z.preventDefault(),Z.touches.length===1&&j.current){const se=Z.touches[0],ce=se.clientX-j.current.x,ee=se.clientY-j.current.y;if(!g.current&&v.current){const pe=se.clientX-v.current.x,ae=se.clientY-v.current.y;Math.sqrt(pe*pe+ae*ae)>8&&(g.current=!0,h.current&&clearTimeout(h.current))}if(g.current)if(_.current==="mouse"){const pe=te(ce,ee),ae=y.current||{nx:.5,ny:.5},Se=Math.max(0,Math.min(1,ae.nx+pe.dnx)),ge=Math.max(0,Math.min(1,ae.ny+pe.dny));y.current={nx:Se,ny:ge},R({nx:Se,ny:ge}),L(`Cursor: ${Math.round(Se*100)}%, ${Math.round(ge*100)}%`),ne(Se,ge,c.current);const P=Date.now();P-w.current>=30&&(w.current=P,S.current("input_mouseMoved",{nx:Se,ny:ge}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const ae=pe.clientWidth,Se=pe.clientHeight,ge=l.current+ce/ae*100,P=m.current+ee/Se*100,fe=b(ge,P,c.current);f(fe.x),u(fe.y),l.current=fe.x,m.current=fe.y}}else{const pe=ve(se);if(pe){const ae=Date.now();ae-w.current>=40&&(w.current=ae,L("Scroll"),S.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-ee*2.5)}).catch(()=>{}))}}j.current={x:se.clientX,y:se.clientY};return}if(Z.touches.length===2&&I.current!==null){const se=Z.touches[1].clientX-Z.touches[0].clientX,ce=Z.touches[1].clientY-Z.touches[0].clientY,pe=Math.sqrt(se*se+ce*ce)/I.current,ae=(Z.touches[0].clientX+Z.touches[1].clientX)/2,Se=(Z.touches[0].clientY+Z.touches[1].clientY)/2,ge=ae-M.current.x,P=Se-M.current.y,fe=Math.abs(pe-1)>.03;if(_.current==="mouse"){if(fe){const Y=Math.max(i,Math.min(5,A.current*pe));x(Y),c.current=Y}else if(Math.abs(ge)>2||Math.abs(P)>2){const Y=y.current||{nx:.5,ny:.5},ue=Date.now();ue-w.current>=30&&(w.current=ue,L("Scroll"),S.current("input_wheel",{nx:Y.nx,ny:Y.ny,deltaX:Math.round(-ge*3),deltaY:Math.round(-P*3)}).catch(()=>{}))}}else{const Y=Math.max(i,Math.min(5,A.current*pe));x(Y),c.current=Y;const ue=s.current;if(ue&&Y>1){const Ie=ue.clientWidth,Pe=ue.clientHeight,Be=l.current+ge/Ie*100,qe=m.current+P/Pe*100,We=b(Be,qe,Y);f(We.x),u(We.y),l.current=We.x,m.current=We.y}}M.current={x:ae,y:Se}}},re=Z=>{var me;if(h.current&&clearTimeout(h.current),I.current=null,Z.touches.length===1&&O.current){const se=Z.touches[0];v.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},g.current=!0;return}if(Z.touches.length===0){if(O.current){O.current=!1,g.current=!1;return}if(Z.changedTouches.length===1){const se=Z.changedTouches[0],ce=Date.now(),ee=ce-(((me=v.current)==null?void 0:me.time)||0),pe=v.current?se.clientX-v.current.x:0,ae=v.current?se.clientY-v.current.y:0,Se=Math.sqrt(pe*pe+ae*ae);if(_.current==="mouse"){if(ee<H||ee>q||Se>T){g.current=!1;return}const ge=y.current||ve(se);ge&&(L(`Click: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),d(ge.nx,ge.ny,"left"),S.current("input_click",{...ge}).catch(()=>{}))}else{if(g.current){g.current=!1;return}if(ee<D||ee>W||Se>z){g.current=!1;return}const ge=ve(se);if(!ge)return;ce-K.current<300?(L("Double tap"),d(ge.nx,ge.ny,"double"),S.current("input_click",{...ge,clickCount:2}).catch(()=>{}),K.current=0):(L(`Tap: ${Math.round(ge.nx*100)}%, ${Math.round(ge.ny*100)}%`),d(ge.nx,ge.ny,"left"),S.current("input_click",{...ge}).catch(()=>{}),K.current=ce)}}g.current=!1}};return je.addEventListener("touchstart",V,{passive:!1}),je.addEventListener("touchmove",ie,{passive:!1}),je.addEventListener("touchend",re,{passive:!1}),()=>{je.removeEventListener("touchstart",V),je.removeEventListener("touchmove",ie),je.removeEventListener("touchend",re),h.current&&clearTimeout(h.current)}},[e,s,r,i,c,l,m,f,u,x,w,L,d,b]),{cursorPos:N,cursorPosRef:y,handleToggleInputMode:()=>{o(je=>{const ve=je==="touch"?"mouse":"touch";return ve==="mouse"&&X(),ve})},handleZoomReset:()=>{const je=k?p:1;x(je),c.current=je,f(0),u(0),l.current=0,m.current=0}}}function Wo({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:o,transportType:i}){const c=a.useRef(null),l=a.useRef(null),m=a.useRef(null),[f,u]=a.useState(null),[x,w]=a.useState(""),[,C]=a.useState(!1),[L,d]=a.useState([]),b=a.useRef(0),[k,p]=a.useState(!1),[N,R]=a.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,j]=a.useState(y?"mouse":"touch"),[g,h]=a.useState(1),K=a.useRef(!1),[I,A]=a.useState(1),[M,O]=a.useState(0),[_,S]=a.useState(0);Js("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:v,zoom:I,panX:M,panY:_,isMenuOpen:k,isImeOpen:N});const H=a.useRef(0),q=a.useRef(I),T=a.useRef(M),D=a.useRef(_);a.useEffect(()=>{q.current=I},[I]),a.useEffect(()=>{T.current=M},[M]),a.useEffect(()=>{D.current=_},[_]),a.useEffect(()=>{var ee;(ee=c.current)==null||ee.focus()},[]);const W=r==="connected",z=n,X=W?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=W?"The remote stream is warming up":"Waiting for the remote stream to catch up";a.useEffect(()=>{if(!y||K.current||!z)return;const ee=m.current,pe=l.current;if(!ee||!pe)return;const ae=()=>{const Se=pe.clientWidth,ge=pe.clientHeight,P=ee.naturalWidth,fe=ee.naturalHeight;if(!P||!fe||!Se||!ge)return;const Y=Math.min(Se/P,ge/fe),Ie=Math.max(Se/P,ge/fe)/Y;Ie>1.01&&(h(Ie),A(Ie),q.current=Ie),K.current=!0};ee.complete&&ee.naturalWidth?ae():ee.addEventListener("load",ae,{once:!0})},[z,y]);const Te=.5;a.useEffect(()=>{I<=Te&&(O(0),S(0))},[I,Te]);const je=(ee,pe,ae)=>{if(ae<=Te)return{x:0,y:0};const Se=(ae-1)/(2*ae)*100,ge=(ae-1)/(2*ae)*100;return{x:Math.max(-Se,Math.min(Se,ee)),y:Math.max(-ge,Math.min(ge,pe))}},ve=(ee,pe)=>{if(!m.current)return null;const ae=m.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(ee-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(pe-ae.top)/ae.height))}},te=(ee,pe,ae)=>{const Se=l.current;if(!Se)return;const ge=Se.getBoundingClientRect(),P=++b.current;d(fe=>[...fe,{id:P,x:ee-ge.left,y:pe-ge.top,type:ae}]),setTimeout(()=>d(fe=>fe.filter(Y=>Y.id!==P)),600)},ne=(ee,pe,ae)=>{const Se=m.current,ge=l.current;if(!Se||!ge)return;const P=Se.getBoundingClientRect(),fe=ge.getBoundingClientRect(),Y=Se.naturalWidth||P.width,ue=Se.naturalHeight||P.height,Ie=Y/ue,Pe=P.width/P.height;let Be,qe,We,Fe;Ie>Pe?(Be=P.width,qe=P.width/Ie,We=0,Fe=(P.height-qe)/2):(qe=P.height,Be=P.height*Ie,We=(P.width-Be)/2,Fe=0);const Ye=P.left-fe.left+We+Be*ee,pt=P.top-fe.top+Fe+qe*pe,Ke=++b.current;d(lt=>[...lt,{id:Ke,x:Ye,y:pt,type:ae}]),setTimeout(()=>d(lt=>lt.filter(nt=>nt.id!==Ke)),600)},V=async ee=>{var ae;const pe=ve(ee.clientX,ee.clientY);if(pe){u(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),te(ee.clientX,ee.clientY,"left"),(ae=c.current)==null||ae.focus();try{const Se=await e("input_click",{nx:pe.nx,ny:pe.ny});Se!=null&&Se.success||s(`❌ Click failed: ${Se==null?void 0:Se.error}`)}catch(Se){s(`❌ Click error: ${Se.message||Se}`)}}},ie=async(ee,pe,ae,Se=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:ee,code:pe,text:ae?ee:void 0,unmodifiedText:ae?ee:void 0,modifiers:Se})}catch(ge){s(`❌ Key error: ${ge.message||ge}`)}},re=async ee=>{if(ee.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ee.key)&&ee.preventDefault();let ae=0;ee.altKey&&(ae|=1),ee.ctrlKey&&(ae|=2),ee.metaKey&&(ae|=4),ee.shiftKey&&(ae|=8),u(`Key: ${ee.key}`),await ie(ee.key,ee.code,ee.key.length===1,ae)},Z=async ee=>{if(ee.key==="Enter"){if(ee.nativeEvent.isComposing)return;if(x){const pe=x;w(""),u(`IME Sent: ${pe}`);try{const ae=await e("input_type",{text:pe});ae!=null&&ae.success||s(`❌ IME error: ${ae==null?void 0:ae.error}`)}catch(ae){s(`❌ IME error: ${ae.message}`)}}else u("Key: Enter"),await ie("Enter","Enter",!1)}};a.useEffect(()=>{const ee=c.current;if(!ee)return;const pe=ae=>{var Se;if((Se=m.current)!=null&&Se.contains(ae.target)){ae.preventDefault();const ge=Date.now();if(ge-H.current<40)return;H.current=ge;const P=ve(ae.clientX,ae.clientY);if(!P)return;u(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return ee.addEventListener("wheel",pe,{passive:!1}),()=>ee.removeEventListener("wheel",pe)},[e]);const{cursorPos:me,handleToggleInputMode:se,handleZoomReset:ce}=bl({containerRef:c,viewportRef:l,imgRef:m,inputMode:v,setInputMode:j,minZoom:Te,zoomRef:q,panXRef:T,panYRef:D,setPanX:O,setPanY:S,setZoom:A,lastWheelTimeRef:H,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:ne,clampPan:je,isMobile:y,mobileFillZoom:g});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:re,onContextMenu:ee=>ee.preventDefault(),onFocus:()=>C(!0),onBlur:()=>C(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[z?t.jsx("img",{ref:m,src:z,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${I}) translate(${M}%, ${_}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:V,onContextMenu:ee=>ee.preventDefault(),onDragStart:ee=>ee.preventDefault()}):t.jsx(xl,{waitingLabel:X,waitingHint:he,transportType:i}),v==="mouse"&&z&&t.jsx(pl,{cursorPos:me,viewportRef:l,imgRef:m}),L.map(ee=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ee.type];return t.jsxs("div",{style:{position:"absolute",left:ee.x,top:ee.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ae}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ae}, 0.9)`,boxShadow:`0 0 12px rgba(${ae}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ee.id)})]}),t.jsx(fl,{inputMode:v,onToggleInputMode:se,isImeOpen:N,setIsImeOpen:R,isMenuOpen:k,setIsMenuOpen:p,imeText:x,setImeText:w,handleImeSubmit:Z,isConnActive:W,zoom:I,isMobile:y,mobileFillZoom:g,onZoomOut:()=>A(ee=>Math.max(.5,ee-.25)),onZoomReset:ce,onZoomIn:()=>A(ee=>Math.min(5,ee+.25)),transportType:i,screenshotUsage:o,lastActionStatus:f}),t.jsx("style",{children:`
|
|
5
|
+
@keyframes slideUp {
|
|
6
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
7
|
+
to { opacity: 1; transform: translateY(0); }
|
|
8
|
+
}
|
|
9
|
+
@keyframes slideUpSidebar {
|
|
10
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
+
to { opacity: 1; transform: translateY(0); }
|
|
12
|
+
}
|
|
13
|
+
@keyframes click-ripple-ring {
|
|
14
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
15
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
16
|
+
}
|
|
17
|
+
@keyframes click-ripple-dot {
|
|
18
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
19
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
20
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
21
|
+
}
|
|
22
|
+
@keyframes remote-float {
|
|
23
|
+
0% { transform: translateY(0px); }
|
|
24
|
+
50% { transform: translateY(-7px); }
|
|
25
|
+
100% { transform: translateY(0px); }
|
|
26
|
+
}
|
|
27
|
+
`})]})}function Kr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:o=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<o)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const m=Math.floor(l/60);if(m<24)return`${m}h${r}`;const f=Math.floor(m/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Ko=e=>Kr(e);function gl(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Ts(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",o=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:o}}function Zs(e){const s=new Map,r=(n,o)=>{n&&s.set(n,{sessionId:n,...gl(o)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const o of n.childSessions||[])r(o.id,o)}return s}function Gs(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function qs(e,s,r){const n=Gs(e,s),o=Ts(e),i=o.isReconnecting,c=o.isConnecting,l=o.isGenerating,m=o.isWaiting,f=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||m,u=n.inboxBucket==="working"||l,x=n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:x,requiresAction:f,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:m,inboxBucket:f?"needs_attention":u?"working":x?"task_complete":"idle"}}function yl(e,s,r){return qs(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function vl(e,s,r){return Gs(e,r||new Map).surfaceHidden}function Oo({activeConv:e,onModalButton:s}){const[r,n]=a.useState(null);if(a.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ts(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.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:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(is,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,m)=>{const f=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),w=r===l,C=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:C,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${C&&!w?"opacity-40":"opacity-100"} ${C?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(l)},m)})})]})]})}var wl=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function jl(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if(jl(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":wl.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 Ho(e){return jt(e)==="generating"}function tt(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"IDE"}function kl(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/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 en(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Or(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const o=n.replace(/[\\/]+$/,""),i=o.split(/[\\/]/).filter(Boolean);return i[i.length-1]||o}function Nl(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Sl(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Cl(e){return Nl(e.trim().replace(/\.local$/i,""))}function Il(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Uo(e,s={}){var o,i;const r=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Sl(c));if(r&&r!=="Unknown")return Cl(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Ct(e,s={}){return Il(e)||Uo(e,s)}function zo(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function Fo(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const o=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return o?String(r.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function cs(e,s){return zo(e).join(" · ")}function Ys(e){return e.transport==="pty"}function bs(e){return e.transport==="acp"}function La(e,s){return tt(e)}function _a(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const o=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=tt(r||"").trim().toLowerCase();return n===o||n===i||n===c}function Tl(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Al(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const o=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(o),c=jt(n.status);if(!i){s.set(o,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),m=r.indexOf(c||"idle");m>=0&&(l<0||m<l)&&s.set(o,{...n,status:c})}return Array.from(s.values())}function Ml(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Ll(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Ml(s.receivedAt)||0}function _l(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Cn(e){return Math.max(_l(e),Ll(e.activeChat))}function Rl(e,s,r,n,o,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:o.localeCompare(i)}function Fn(e,s){return Rl(Cn(e),Cn(s),Ct(e,{fallbackId:e.id}),Ct(s,{fallbackId:s.id}),e.id,s.id)}const Vo="adhdev_notification_prefs",Ra={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Pl(){try{const e=localStorage.getItem(Vo);if(e){const s=JSON.parse(e);return{...Ra,...s}}}catch{}return{...Ra}}function Dl(e){try{localStorage.setItem(Vo,JSON.stringify(e))}catch{}}let Kt=Pl(),wr=[];function El(){wr.forEach(e=>e())}function $l(e){Kt={...Kt,...e},Dl(Kt),El()}function Bl(){const[,e]=a.useState(0);a.useEffect(()=>{const r=()=>e(n=>n+1);return wr.push(r),()=>{wr=wr.filter(n=>n!==r)}},[]);const s=a.useCallback(r=>{$l(r)},[]);return[{...Kt},s]}function Ws(e){if(!Kt.globalEnabled)return!1;switch(e){case"disconnect":return Kt.disconnectAlert;case"completion":return Kt.completionAlert;case"approval":return Kt.approvalAlert;case"browser":return Kt.browserNotifications;default:return!0}}const Wl={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Kl(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Go(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function Ol(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function In(e,s,r){if(Go())try{const n=new Notification(e,{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 Hl(e,s={}){const r={...Wl,...s},n=a.useRef(new Map),o=a.useRef(0),i=a.useRef(null);a.useEffect(()=>{Ol().then(l=>{i.current=l})},[]);const c=a.useCallback((l,m,f)=>{const u=Date.now();u-o.current<r.throttleMs||(o.current=u,In(l,m,f))},[r.throttleMs]);a.useEffect(()=>{var l;if(!(!r.enabled||!Go())&&Ws("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of e)n.current.set(m.id,jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const f=n.current.get(m.id),u=jt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&Ws("approval")&&u==="waiting_approval"&&f!=="waiting_approval"){const w=((l=m.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ws("completion")&&Ho(f)&&u==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&u==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,u)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Ul=/^(run|approve|accept|yes|allow|always)/,zl=/^(run|approve|accept|yes|allow|always|proceed|save)/,Fl=/^(reject|deny|delete|remove|abort|cancel|no)/;function Vn(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Vl(e){const s=Vn(e).toLowerCase();return Ul.test(s)?"primary":Fl.test(s)?"danger":"default"}function Gl(e){return zl.test(Vn(e).toLowerCase())?"approve":"reject"}function ql(e){return e.map((s,r)=>({label:Vn(s),variant:Vl(s),action:Gl(s),button:s,buttonIndex:r}))}function Yl(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(o=>`[${o}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
28
|
+
${n}`}function Xl(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Ql(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(o=>n==null?void 0:n("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(o=>n==null?void 0:n("reject",o))}}]}class Jl{constructor(){ct(this,"dedupMap",new Map);ct(this,"DEDUP_WINDOW_MS",5e3);ct(this,"DEDUP_MAX_SIZE",50);ct(this,"DEDUP_CLEANUP_AGE_MS",1e4);ct(this,"toastCallbacks",[]);ct(this,"systemMessageCallbacks",[]);ct(this,"clearSystemMessageCallbacks",[]);ct(this,"resolveActionFn",null);ct(this,"viewRequestRespondFn",null);ct(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 L,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),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(m==null?void 0:m.type)||"";let u=tt(f);const x=this.resolveOwningDaemon(s);if(x){const b=Ct(x,{fallbackId:x.id});b&&(u=!f||f==="adhdev-daemon"?b:`${b}/${u}`)}let w="",C="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${u} 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(w=`⚡ ${u} approval needed`,C="warning",n&&!((L=s.modalButtons)!=null&&L.length)&&this.emitSystemMessage(n,{role:"system",timestamp:o,content:Yl(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 k=this.resolveActionFn,p=ql(s.modalButtons).map(y=>({label:y.label,variant:y.variant,onClick:()=>{k(b,"resolve_action",{action:y.action,button:y.button,buttonIndex:y.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),N=Xl(u,s.modalMessage,w),R=Date.now();this.emitToast({id:R,message:N,type:C,timestamp:R,targetKey:n||b,actions:p,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${u} agent is taking a long time${b}`,C="warning",Ws("browser")&&!document.hasFocus()&&In(`⚠️ ${u} — 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",k=s.requestId,p=s.orgId;if(w=`👁️ ${b} wants to view your session`,C="warning",k&&p&&this.viewRequestRespondFn){const N=Date.now(),R=Ql(p,k,this.viewRequestRespondFn,(y,v)=>console.error(`[EventManager] ${y} view request failed:`,v));this.emitToast({id:N,message:w,type:C,timestamp:N,actions:R,duration:3e4}),w=""}Ws("browser")&&!document.hasFocus()&&In("👁️ View Request",`${b} wants to view your session`,`view-request-${k}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",C="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,C="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:C,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const st=new Jl,Pa=new Map;function ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qo(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Zl(e){return!ws(e)||!ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function or(e){return!ws(e)||!ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function _s(e){if(!(!ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function ir(e){return ws(e)&&e.success===!1}function ed(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const o=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";st.showToast(n.toast.message,o);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const o=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";st.showToast(n.notification.body,o)}}}function td(e,s){return e&&qo(e.currentValue)?e.currentValue:s}function jr(e,s){return e.options||s[e.id]||[]}function tn(e,s){return{value:s}}function sd(e,s,r){var o;return r?((o=jr(e,s).find(i=>i.value===r))==null?void 0:o.label)||r:""}const rd={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function nd({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:o,controls:i,controlValues:c}){const{sendCommand:l}=_t(),m=`${e}:${s||n}`,f=rd[n]||"#94a3b8",[u,x]=a.useState({}),w=a.useRef(0),C={};for(const _ of i||[])_.defaultValue!==void 0&&(C[_.id]=_.defaultValue);const L={...C,...c||{},...Date.now()<w.current?u:{}};a.useEffect(()=>{c&&Date.now()>w.current&&x({})},[c]);const[d,b]=a.useState(Pa.get(m)||{}),[k,p]=a.useState(null),[N,R]=a.useState(null),y=a.useCallback(async(_,S={})=>{const H={...S,...s&&{targetSessionId:s}};return await l(e,_,H)},[e,s,l]),v=a.useCallback(async(_,S={})=>{const H=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await y("invoke_provider_script",{...H,scriptName:_,...S})},[y,n,r,s]),j=a.useCallback((_,S,H)=>{const q=td(H,S);x(T=>({...T,[_.id]:q})),ed(H==null?void 0:H.effects)},[]),g=a.useCallback((_,S)=>{x(H=>{const q={...H};return S===void 0?delete q[_.id]:q[_.id]=S,q}),w.current=0},[]);if(!i||i.length===0)return null;const h=i.filter(_=>_.placement==="bar"&&_.hidden!==!0).sort((_,S)=>(_.order??50)-(S.order??50));if(h.length===0)return null;const K=async _=>{if(k===_.id){p(null);return}if(jr(_,d).length>0){p(_.id);return}if(_.dynamic&&_.listScript){R(_.id);try{const H=await v(_.listScript,{}),q=Zl(H);if(!q){const D=_s(H);D&&st.showToast(D,"warning");return}const T=q.options;if(b(D=>{const W={...D,[_.id]:T};return Pa.set(m,W),W}),qo(q.currentValue)){const D=q.currentValue;x(W=>({...W,[_.id]:D}))}p(_.id)}catch(H){const q=H instanceof Error?H.message:`Could not load ${_.label}`;st.showToast(q,"warning")}finally{R(null)}}},I=async(_,S)=>{p(null);const H=(c==null?void 0:c[_.id])??C[_.id];x(q=>({...q,[_.id]:S})),w.current=Date.now()+5e3;try{if(!_.setScript)return;const q=await v(_.setScript,tn(_,S)),T=or(q);if(T&&!T.ok||ir(q))throw new Error((T==null?void 0:T.error)||_s(q)||`Could not update ${_.label}`);j(_,S,T)}catch(q){g(_,H);const T=q instanceof Error?q.message:`Could not update ${_.label}`;st.showToast(T,"warning")}},A=async _=>{const S=jr(_,d).map(z=>z.value);if(S.length===0)return;const H=String(L[_.id]||""),T=(S.indexOf(H)+1)%S.length,D=S[T];if(typeof D!="string")return;const W=(c==null?void 0:c[_.id])??C[_.id];x(z=>({...z,[_.id]:D})),w.current=Date.now()+5e3;try{if(!_.setScript)return;const z=await v(_.setScript,tn(_,D)),X=or(z);if(X&&!X.ok||ir(z))throw new Error((X==null?void 0:X.error)||_s(z)||`Could not update ${_.label}`);j(_,D,X)}catch(z){g(_,W);const X=z instanceof Error?z.message:`Could not update ${_.label}`;st.showToast(X,"warning")}},M=async _=>{const H=!L[_.id],q=(c==null?void 0:c[_.id])??C[_.id];x(T=>({...T,[_.id]:H})),w.current=Date.now()+5e3;try{if(!_.setScript)return;const T=await v(_.setScript,tn(_,H)),D=or(T);if(D&&!D.ok||ir(T))throw new Error((D==null?void 0:D.error)||_s(T)||`Could not update ${_.label}`);j(_,H,D)}catch(T){g(_,q);const D=T instanceof Error?T.message:`Could not update ${_.label}`;st.showToast(D,"warning")}},O=async _=>{if(!_.invokeScript)return;if(_.confirmMessage){const H=[_.confirmTitle,_.confirmMessage,_.confirmLabel].filter(T=>typeof T=="string"&&T.trim().length>0);if(!window.confirm(H.join(`
|
|
29
|
+
|
|
30
|
+
`)))return}const S=(c==null?void 0:c[_.id])??C[_.id];try{const H=await v(_.invokeScript),q=or(H);if(q&&!q.ok||ir(H))throw new Error((q==null?void 0:q.error)||_s(H)||`Could not run ${_.label}`);q&&j(_,S??!0,q)}catch(H){g(_,S);const q=H instanceof Error?H.message:`Could not run ${_.label}`;st.showToast(q,"warning")}};return t.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:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:f},children:o}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),h.map(_=>{const S=String(L[_.id]||""),H=sd(_,d,S),q=k===_.id,T=N===_.id,D=jr(_,d);switch(_.type){case"select":return t.jsxs("div",{className:"relative",children:[t.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:q?`${f}55`:"transparent",border:"1px solid",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),T?"...":H||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),q&&D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>p(null)}),t.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:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:_.label.toUpperCase()}),D.map(W=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W.value===S?`${f}18`:"transparent",color:W.value===S?f:"var(--text-secondary)",fontWeight:W.value===S?600:400,borderLeft:W.value===S?`2px solid ${f}`:"2px solid transparent"},title:W.description||W.label,onMouseEnter:z=>{z.currentTarget.style.background=`${f}12`},onMouseLeave:z=>{z.currentTarget.style.background=W.value===S?`${f}18`:"transparent"},onClick:()=>I(_,W.value),children:W.label},W.value))]})]})]},_.id);case"cycle":return t.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:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>A(_),title:`Click to cycle: ${D.map(W=>W.label).join(" → ")}`,children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),H||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},_.id);case"toggle":return t.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:S?`${f}44`:"transparent",background:S?`${f}14`:"var(--surface-tertiary)",color:S?f:"var(--text-muted)"},onClick:()=>M(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.label]},_.id);case"action":return t.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:()=>O(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.resultDisplay==="inline"&&S?`${_.label}: ${S}`:_.label]},_.id);case"display":return t.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:S?"var(--text-primary)":"var(--text-muted)"},children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),S?`${_.label}: ${S}`:_.label]},_.id);default:return null}})]})}const ad=a.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:o,isActive:i=!0}){const c=a.useRef(null),[l,m]=a.useState("");a.useEffect(()=>{m("")},[s]),a.useEffect(()=>{var u;i&&((u=c.current)==null||u.focus())},[s,i]);const f=()=>{const u=l.trim();!u||n||(m(""),o(u))};return t.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:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:l,onChange:u=>m(u.target.value),onPaste:u=>{const x=u.clipboardData.getData("text");x&&m(w=>w+x),u.preventDefault()},onKeyDown:u=>{if(u.key==="Enter"){if(u.nativeEvent.isComposing){u.preventDefault();return}u.preventDefault(),f()}},onBlur:u=>{if(window.innerWidth<768){const x=u.relatedTarget;if((x==null?void 0:x.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:f,disabled:!l.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${l.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:l.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:l.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),Xe=e=>e.transport==="pty",js=(e,s)=>Xe(e)?e.mode||"terminal":"chat",Yo=(e,s)=>Xe(e)&&js(e)==="terminal",Ge=e=>e.transport==="acp";function Ot(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Xo(e){return e.machineName||""}function Ar(e){return qt(e)}function St(e){return e.agentType||""}function Gn(e){return e.hostIdeType||""}function Hr(e){return e.displayPrimary||e.agentName||"Agent"}function qn(e){return[e.displaySecondary,Xo(e)].filter(Boolean)}function er(e){return e.agentName||tt(St(e))}function od(e){var s,r;if(!Ot(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return tt(Gn(e)||St(e))}function Yn(e){return Ot(e)?e.sessionId:e.nativeSessionId}function Da(e){return Ot(e)?"native":e.tabKey}function id(e){return e.sessionId}function cd(e,s){if(s)return Ot(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function ld(e,s){const r=St(e),n=Ot(e)?s!=null&&s.type?tt(s.type):tt(Gn(e)||r):er(e);return{isNativeConversation:Ot(e),isCli:Xe(e),isAcp:Ge(e),isCliTerminal:Yo(e),providerType:r,displayLabel:n,targetEntry:cd(e,s)}}function Qo({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:o=!0}){const i=Cs(),c=qt(e),l=Xo(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,u=!f&&(e.transport==="pty"||e.transport==="acp"),x=er(e),w=od(e),C=a.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),L=a.useCallback(()=>{if(r){r();return}const d=Yn(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:L,title:w,children:[t.jsx(It,{size:12}),t.jsx("span",{children:w})]}):t.jsxs("span",{className:"conversation-meta-chip",title:w,children:[t.jsx(It,{size:12}),t.jsx("span",{children:w})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Fs,{size:12}),t.jsx("span",{children:x})]}),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(Fs,{size:12}),t.jsx("span",{children:x})]}),l&&(o?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:l,children:[t.jsx(Ht,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ht,{size:12}),t.jsx("span",{children:l})]}))]})}function Ea(e,s){return`${e}:${s}`}function dd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function cr(e,s){dd()&&console.debug(`[subscription-manager] ${e}`,s)}class ud{constructor(){ct(this,"active",new Map)}subscribe(s,r,n,o){var f;const i=Ea(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(o),c.lastUpdate&&o(c.lastUpdate);else{const u={daemonId:r,request:n,handlers:new Set([o])};this.active.set(i,u),cr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const m=()=>{var w;const u=this.active.get(i);if(!u||(u.handlers.delete(o),u.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};cr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,x)};return m.initialSendAccepted=l,m}publish(s){const r=Ea(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,as.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(o=>{o(s),as.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}resubscribeAll(s){var r;cr("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);cr("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 Vt=new ud;function md(e,s){const r=new Map;for(const n of e||[])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,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,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 lr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash)}}function pd(e){const s=[],r=new Map;for(const n of e)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 Mr(e,s){const r=[],{daemonId:n,existingDaemon:o,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:f,childrenByParent:u}=pd(m),x=md(i,n),w=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,C=f.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),L=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:l,...e.version&&{version:e.version},...w&&{machine:w,platform:w.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:C.some(b=>!!b.cdpConnected)});for(const b of C){const k=x.get(b.id),p=lr(b,k),N=(u.get(b.id)||[]).map(R=>lr(R,x.get(R.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,status:p.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:p.workspace,terminals:0,childSessions:N,agents:N.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.status})),activeChat:p.activeChat,chats:[],cdpConnected:p.cdpConnected,...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},timestamp:l})}for(const b of L){const k=x.get(b.id),p=lr(b,k);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:b.id,cliName:p.providerName||p.providerType,mode:p.mode||(k==null?void 0:k.mode)||"terminal",workspace:p.workspace||"",activeChat:p.activeChat,...p.resume!==void 0&&{resume:p.resume},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const k=x.get(b.id),p=lr(b,k);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:b.id,cliName:p.providerName||p.providerType,mode:"chat",workspace:p.workspace||"",activeChat:p.activeChat,...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const sn=new Map,rn=new Map,nn=new Set,Ks=new Map,fd=1200;function xd(e){if(!e||typeof e!="object")return null;const s=e,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 $a(e,s){const r=Ks.get(e);!r||r.size===0||(Ks.delete(e),r.forEach(n=>n(s)))}function hd(e,s){return new Promise(r=>{const n=Ks.get(e)||new Set;Ks.set(e,n);const o=c=>{clearTimeout(i),n.delete(o),n.size===0&&Ks.delete(e),r(c)},i=setTimeout(()=>o(!1),s);n.add(o)})}function tr(){const{sendCommand:e,sendData:s}=_t(),{injectEntries:r,getIdes:n}=Tr();return a.useCallback(async(o,i)=>{if(!o)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=rn.get(o)||0;if(!(i!=null&&i.force)&&nn.has(o)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const m=sn.get(o);if(m)return m;const f=(async()=>{if(s&&!nn.has(o)&&(nn.add(o),Vt.subscribe({sendData:s},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},d=>{const b=n(),k=b.find(N=>N.id===o),p=Mr(d.status,{daemonId:o,existingDaemon:k,existingEntries:b,timestamp:d.timestamp});p.length>0&&r(p),rn.set(o,Date.now()),$a(o,!0)}),!(i!=null&&i.force)&&await hd(o,fd)))return;const u=await e(o,"get_status_metadata"),x=xd(u);if(!x)return;const w=n(),C=w.find(d=>d.id===o),L=Mr(x,{daemonId:o,existingDaemon:C,existingEntries:w,timestamp:x.timestamp||Date.now()});L.length>0&&r(L,{authoritativeDaemonIds:[o]}),rn.set(o,Date.now()),$a(o,!0)})().finally(()=>{sn.delete(o)});return sn.set(o,f),f},[n,r,e,s])}function zt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Xn(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const o=Vs(e.content),i=Vs(s.content);if(!o||o!==i)return!1;const c=zt(e),l=zt(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function Ba(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),zt(e)&&(s+=1),s}function ks(e){return Vs(e==null?void 0:e.content)}function Tn(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function bd(e,s){const r=ks(e),n=ks(s);return!r||!n||r===n?null:Tn(r,n)?e:Tn(n,r)?s:null}function gd(e,s){const r=bd(e,s);if(r)return r;const n=Ba(e),o=Ba(s);return o!==n?o>n?s:e:ks(s).length>=ks(e).length?s:e}function Xs(e){const s=[];for(const r of e){const n=s.findIndex(o=>Xn(o,r));if(n>=0){s.splice(n,1,gd(s[n],r));continue}s.push(r)}return s}function yd(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:Xs([...r,...n])}function Wa(e){return[...e].sort((s,r)=>{const n=zt(s),o=zt(r);return n&&o&&n!==o?n-o:0})}function Ka(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const o=r.findIndex(i=>Xn(i,n));return o>=0?(r.splice(o,1),!1):!0})}function vd(e,s){return e.filter(r=>{const n=ks(r),o=String((r==null?void 0:r.role)||"").toLowerCase(),i=zt(r);return!s.some(c=>{if(Xn(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!o||o!==l)return!1;const m=ks(c);if(!Tn(m,n)&&m!==n)return!1;const f=zt(c);return i&&f?Math.abs(i-f)<=15e3:!0})})}const wd=60,jd=200;function kd(e={}){return e.isCliLike?jd:wd}function Nd(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Sd(e){let s=2166136261;for(const r of e){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 Oa(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Jo(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return Sd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function Cd(e){return{knownMessageCount:e.length,lastMessageSignature:Jo(e[e.length-1])}}function Id(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Xs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Xs([...e.slice(0,n),...r])}case"full":default:return r}}const Ha=60;function An({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:o,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:m=!1,scrollToBottomRequestNonce:f,isInputActive:u=!0}){var ve,te;const x=a.useRef(new Map),w=a.useRef(new Map),C=a.useRef(new Map),{sendCommand:L,sendData:d}=_t(),b=tr();Js("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const k=et.useMemo(()=>Ts(e),[e.status,e.connectionState]),p=a.useMemo(()=>ld(e,s),[e,s]),N=kd({isCliLike:p.isCli||p.isAcp}),R=a.useRef(new Map),y=a.useCallback(ne=>(R.current.has(ne)||R.current.set(ne,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:N}),R.current.get(ne)),[N]),v=a.useCallback((ne,V)=>{const ie=y(ne);R.current.set(ne,{...ie,...V}),j(re=>re+1)},[y]),[,j]=a.useState(0),g=e.tabKey,h=y(g),K=h.messages,I=h.hasMore,A=h.error,M=w.current.get(g),O=yd(M,e.messages);a.useEffect(()=>{h.visibleLiveCount>=N||v(g,{visibleLiveCount:N})},[N,h.visibleLiveCount,g,v]);const _=Math.max(0,O.length-h.visibleLiveCount),S=Hr(e),H=Ar(e),q=e.sessionId||"",T=e.providerSessionId||q,[D,W]=a.useState(!1);a.useEffect(()=>{const ne=p.targetEntry;H&&(!ne||ne.providerControls===void 0||ne.controlValues===void 0)&&b(H,{minFreshMs:3e4}).catch(()=>{})},[H,p.isAcp,(ve=p.targetEntry)==null?void 0:ve.providerControls,(te=p.targetEntry)==null?void 0:te.controlValues,b]),a.useEffect(()=>{if(!H||!q||!d)return;const ne=w.current.get(g)||[],V=C.current.get(g),ie=V&&V.knownMessageCount?V:Cd(ne),re=`daemon:${H}:session:${q}`;return Vt.subscribe({sendData:d},H,{type:"subscribe",topic:"session.chat_tail",key:re,params:{targetSessionId:q,historySessionId:T,knownMessageCount:ie.knownMessageCount,lastMessageSignature:ie.lastMessageSignature,...ie.knownMessageCount?{}:{tailLimit:Ha}}},me=>{const se=w.current.get(g)||[],ce=Id(se,me),ee=Math.max(ce.length,Number(me.totalMessages||0));C.current.set(g,{knownMessageCount:ee,lastMessageSignature:typeof me.lastMessageSignature=="string"?me.lastMessageSignature:Jo(ce[ce.length-1])}),Oa(se)!==Oa(ce)&&(w.current.set(g,ce),as.record({interactionId:me.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:q,syncMode:me.syncMode,previousCount:se.length,nextCount:ce.length}}),j(ae=>ae+1))})},[H,T,d,q,g]);const z=a.useCallback(async()=>{if(D)return;const ne=e.tabKey,V=y(ne);if(O.length>V.visibleLiveCount){v(ne,{visibleLiveCount:Math.min(O.length,V.visibleLiveCount+Ha),error:null});return}W(!0),v(ne,{error:null});try{const ie=Ar(e);if(!ie){v(ne,{hasMore:!1});return}const re=St(e),Z=await L(ie,"chat_history",{agentType:re,offset:V.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),me=Nd(Z),se=me.messages||[];if(se.length>0){const ce=y(ne);v(ne,{messages:[...se,...ce.messages],offset:ce.offset+se.length,hasMore:!!me.hasMore})}else v(ne,{hasMore:!!me.hasMore})}catch(ie){const re=(ie==null?void 0:ie.message)||"";re.includes("P2P not available")||re.includes("channel not open")||re.includes("P2P not connected")||re.includes("timeout")?v(ne,{error:"Connection not ready — tap to retry"}):v(ne,{hasMore:!1,error:"Failed to load history"})}finally{W(!1)}},[D,e,O.length,L,y,v]),{allMessages:X,receivedAtMap:he}=a.useMemo(()=>{const ne=_>0?O.slice(-h.visibleLiveCount):O;if(K.length===0){const Z=Wa(Xs(ne)),me={};return Z.forEach((se,ce)=>{const ee=`${e.tabKey}:${hs(se,ce)}`;let pe=zt(se)||x.current.get(ee)||0;pe||(pe=Date.now(),x.current.set(ee,pe)),me[hs(se,ce)]=pe}),{allMessages:Z,receivedAtMap:me}}const V=vd(K,ne),ie=Wa(Xs([...V,...ne])),re={};return ie.forEach((Z,me)=>{const se=`${e.tabKey}:${hs(Z,me)}`;let ce=zt(Z)||x.current.get(se)||0;ce||(ce=Date.now(),x.current.set(se,ce)),re[hs(Z,me)]=ce}),{allMessages:ie,receivedAtMap:re}},[e.tabKey,_,K,O,h.visibleLiveCount]),Te=a.useMemo(()=>c.filter(ne=>ne.routeId===e.tabKey).sort((ne,V)=>ne.timestamp-V.timestamp),[c,e.tabKey]),je=a.useMemo(()=>{if(O.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.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:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((k.isGenerating||e.status==="streaming")&&W(!1),e.status==="not_monitored")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Fs,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vs,{size:14})," Open ",S," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ro,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vs,{size:14})," Open ",S," Panel"]})}),t.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(e.status==="idle"&&!D)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,o,i,D,O.length,S,k.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(Qo,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(ll,{messages:X,actionLogs:Te,agentName:er(e)||S||"Agent",userName:l,isCliMode:p.isCli||p.isAcp,isWorking:k.isGenerating,contextKey:e.tabKey,receivedAtMap:he,onLoadMore:z,isLoadingMore:D,hasMoreHistory:I,hiddenLiveCount:_,loadError:A??void 0,emptyState:je,scrollToBottomRequestNonce:f}),u&&!p.isCliTerminal&&(()=>{var ne,V;return t.jsx(nd,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:p.providerType,displayLabel:p.displayLabel,controls:(ne=p.targetEntry)==null?void 0:ne.providerControls,controlValues:(V=p.targetEntry)==null?void 0:V.controlValues})})(),!p.isCliTerminal&&t.jsx(ad,{contextKey:e.tabKey,panelLabel:S,isSending:n,onSend:r,isActive:u})]})}let Zo=os;function ei(){return Zo()}class Td{constructor(){ct(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 ti=new Td;class Ad{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 it=new Ad;function Md(e){e.dashboardWS&&(ti=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(Zo=e.useDaemonsHook)}function rt(e){return Hr(e)}function ls(e){return qn(e).join(" · ")}function si(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=Vs(s==null?void 0:s.content);return r||(e.title?e.title:ls(e)||"No messages yet")}function ri(e,s){const{isReconnecting:r,isConnecting:n}=Ts(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Ld(e,s){const r=["Chat",...qn(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function Zt(e){return ri(e)||ls(e)}function _d(e){return`${rt(e)} · ${si(e)}`}function Rd(e){const s=Gn(e)||St(e);return`${rt(e)} — ${tt(s)}`}function Pd(e){return er(e)||"CLI"}function ni(e){return e.title||er(e)||e.routeId}function ai(e){return e?`Remote · ${rt(e)||e.workspaceName||"Session"}`:"Remote"}function Dd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:o=!1,isVisible:i=!0}){var D;const{ides:c}=os(),l=a.useRef(null),{sendCommand:m,sendData:f}=_t(),[u,x]=a.useState(""),[w,C]=a.useState(!1),[L,d]=a.useState(1),b=a.useRef(!1),k=a.useRef(0),p=a.useRef(!1),N=a.useRef(""),R=a.useRef(null),y=a.useRef(!1),v=a.useRef(null),j=e.tabKey,g=e.sessionId||"",h=e.daemonId||((D=e.routeId)==null?void 0:D.split(":")[0])||e.routeId||"",K=c.find(W=>W.id===h&&W.type==="adhdev-daemon"),I=(K==null?void 0:K.terminalSizingMode)==="fit"?"fit":"measured",A=.6,M=1.15,O=()=>{if(typeof window>"u")return 1;const W=window.innerWidth||0;return W<=360?.68:W<=390?.74:W<=430?.82:W<=480?.9:1},_=()=>{var W,z;k.current=0,p.current=!1,N.current="",R.current=null,y.current=!1,v.current!==null&&(cancelAnimationFrame(v.current),v.current=null),C(!1),(z=(W=r.current)==null?void 0:W.reset)==null||z.call(W)},S=()=>{var W,z;k.current=0,p.current=!1,N.current="",R.current=null,y.current=!1,v.current!==null&&(cancelAnimationFrame(v.current),v.current=null),C(!0),(z=(W=r.current)==null?void 0:W.reset)==null||z.call(W)},H=()=>{var z;if(v.current=null,!i)return;const W=N.current;W&&(N.current="",(z=r.current)==null||z.write(W))},q=W=>{W&&(N.current+=W,i&&v.current===null&&(v.current=requestAnimationFrame(H)))},T=(W,z=0,X,he)=>{var Te,je,ve,te,ne;z>0&&k.current>=z||z===0&&p.current||(k.current=z,C(!0),typeof X=="number"&&typeof he=="number"&&X>0&&he>0&&((je=(Te=r.current)==null?void 0:Te.resize)==null||je.call(Te,X,he)),(te=(ve=r.current)==null?void 0:ve.reset)==null||te.call(ve),W&&((ne=r.current)==null||ne.write(W)))};return a.useEffect(()=>{_()},[g]),a.useEffect(()=>{var z;if(!g)return;const W=((z=it.onRuntimeEvent)==null?void 0:z.call(it,g,X=>{if(!(!X||X.sessionId!==g)){if(X.type==="runtime_snapshot"){if(!i){R.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}T(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){p.current=!0,typeof X.seq=="number"&&(k.current=Math.max(k.current,X.seq)),w||C(!0),typeof X.data=="string"&&q(X.data);return}if(X.type==="session_cleared"){if(!i){y.current=!0,N.current="",R.current=null;return}S()}}}))||(()=>{});return()=>{W()}},[h,g,r,i,w]),a.useEffect(()=>{var z,X,he;if(!g)return;h&&((z=it.getState)==null?void 0:z.call(it,h))==="connected"&&(C(!0),(X=it.requestRuntimeSnapshot)==null||X.call(it,h,g).catch(()=>{}));const W=(he=it.onStateChange)==null?void 0:he.call(it,(Te,je)=>{var ve;Te!==h||je!=="connected"||(C(!0),(ve=it.requestRuntimeSnapshot)==null||ve.call(it,h,g).catch(()=>{}))});return()=>{W==null||W()}},[h,g,r]),a.useEffect(()=>{s&&_()},[s,j,r]),a.useEffect(()=>{x("")},[e.tabKey]),a.useEffect(()=>{const W=()=>{b.current||d(O())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),a.useEffect(()=>{var z;if(!i){(z=l.current)==null||z.blur();return}y.current&&(y.current=!1,S());const W=R.current;W&&(R.current=null,T(W.text,W.seq,W.cols,W.rows)),N.current&&v.current===null&&(v.current=requestAnimationFrame(H)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),a.useEffect(()=>()=>{v.current!==null&&(cancelAnimationFrame(v.current),v.current=null)},[]),a.useEffect(()=>{const W=z=>{var he;const X=z.detail;X!=null&&X.sessionId&&X.sessionId!==g||w&&((he=r.current)==null||he.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[w,g,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.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(W=>Math.max(A,Number((W-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.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(W=>Math.min(M,Number((W+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/L}%`,height:`${100/L}%`,transform:`scale(${L})`,transformOrigin:"top left"},children:t.jsx(Bo,{ref:r,readOnly:!w||!i,sizingMode:I,onInput:W=>{w&&(f!=null&&f(h,{type:"pty_input",sessionId:g,targetSessionId:g,data:W})||m(h,"pty_input",{targetSessionId:g,data:W}).catch(console.error))}})})}),!w&&t.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"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:l,type:"text",placeholder:`Send message to ${rt(e)}...`,value:u,disabled:!w||!i||o,onChange:W=>x(W.target.value),onPaste:W=>{const z=W.clipboardData.getData("text");z&&x(X=>X+z),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const z=u.trim();!w||!z||o||(x(""),n(z))},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))"}})}),t.jsx("button",{onClick:()=>{const W=u.trim();!w||!W||o||(x(""),n(W))},disabled:!w||!i||!u.trim()||o,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.trim()&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:u.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function Ed({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",o=e==="auth_failed"?"red":e==="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)"},l={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.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:l[o]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.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:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function $d({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const o=a.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=a.useState(!1);if(a.useEffect(()=>{if(!o){c(!1);return}try{c(localStorage.getItem(o)==="1")}catch{c(!1)}},[o]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",m=()=>{if(o)try{localStorage.setItem(o,"1")}catch{}c(!0)};return t.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:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.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 Qn({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Br,{size:n}):t.jsx(Ut,{size:n})})}function Bd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Gt(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Bd(s==null?void 0:s.receivedAt)||0}function Mn(e,s=0){return Gt(e)||e.lastUpdated||s||0}function oi(e){return Gt(e)||e.lastUpdated||0}function Lr(e,s,r=oi){const n=r(s)-r(e);if(n!==0)return n;const o=(e.machineName||"").localeCompare(s.machineName||"");if(o!==0)return o;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function Ln(e){var r;const s=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Wd(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Ln(e)&&!e.title.trim()}function Kd(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Ln(r))-Number(Ln(s));if(n!==0)return n;const o=r.messages.length-s.messages.length;return o!==0?o:Lr(s,r)})[0]||null}function Bt(e,s){const r=e.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=Kd(o);return n?i&&Wd(n)?i:n:i||r[0]||null}function Ua({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function za({conversation:e,isAttention:s,shortcutIndex:r,onClick:n}){const o=qn(e),i=Kr(Gt(e)),c=[...o,i].filter(Boolean);return t.jsxs("button",{type:"button",className:`dashboard-header-inbox-item ${s?"is-attention":""}`.trim(),onClick:n,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:Hr(e)}),(r||c.length>0)&&t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[r?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",r]}):null,c.join(" · ")]})]})}function Od({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:o,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:m,onSetCliViewMode:f,onOpenConversation:u,onHideConversation:x,hiddenConversations:w=[],onShowConversation:C,onShowAllHidden:L,onResetPanelsToMain:d,inboxOpen:b,onInboxOpenChange:k,hiddenOpen:p,onHiddenOpenChange:N,onOpenNewSession:R,actionShortcuts:y}){const{ides:v,p2pStates:j={}}=os(),g=!!e&&Xe(e)&&!Ge(e),h=!!e&&Ge(e),K=m||(e?Yo(e)?"terminal":"chat":null),[I,A]=a.useState(!1),M=a.useRef(null),O=a.useRef(null),_=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",S=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",H=v.filter(V=>V.type==="adhdev-daemon"),q=a.useMemo(()=>Zs(v),[v]),T=Object.values(j),D=T.filter(V=>V==="connected").length,W=T.filter(V=>V==="connecting"||V==="new"||V==="checking").length,X=r!=="connected"||H.length===0?null:W>0&&D===0?"P2P connecting...":D>0&&s===0?"Waiting for IDE...":null,he=a.useMemo(()=>o.filter(V=>!vl(V,o,q)),[o,q]),Te=a.useMemo(()=>he.filter(V=>qs(V,q).requiresAction).sort(Lr),[he,q]),je=a.useMemo(()=>he.filter(V=>{const ie=(e==null?void 0:e.tabKey)===V.tabKey;return qs(V,q,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ie}).unread}).sort(Lr),[e,he,q]),ve=a.useMemo(()=>[...Te,...je].slice(0,9),[Te,je]),te=Te.length+je.length;a.useEffect(()=>{if(!b)return;const V=ie=>{var re;(re=M.current)!=null&&re.contains(ie.target)||k(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[b,k]),a.useEffect(()=>{if(!p)return;const V=ie=>{var re;(re=O.current)!=null&&re.contains(ie.target)||N(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[p,N]),a.useEffect(()=>{if(!p&&!b)return;const V=ie=>{if(!ie.altKey)return;const re=ie.code.match(/^Digit([1-9])$/);if(!re)return;const Z=Number(re[1])-1,me=p?w[Z]:void 0,se=b?ve[Z]:void 0,ce=me||se;if(ce){if(ie.preventDefault(),ie.stopPropagation(),me){C==null||C(me),N(!1);return}u==null||u(ce),k(!1)}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[w,p,b,ve,N,k,u,C]);const ne=V=>{if(!V)return;const ie=o.find(re=>re.tabKey===V);ie&&(x==null||x(ie))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Ut,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?rt(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:_,boxShadow:S}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:_,boxShadow:S}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),R&&t.jsx("button",{type:"button",onClick:R,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Hc,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(g||h||!Ge(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ls(e)||rt(e),children:rt(e)}),(g||h)&&l&&t.jsxs(t.Fragment,{children:[g&&f&&K&&t.jsx(Qn,{mode:K,onChange:f,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:h?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(kt,{size:14})})]}),!Ge(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Hn,{size:14})}),!g&&!Ge(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(It,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:M,children:[t.jsxs("div",{className:`dashboard-header-hidden${I?" is-drop-target":""}`,ref:O,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),A(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",A(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||A(!1)},onDrop:V=>{const ie=V.dataTransfer.getData("text/tab-key");V.preventDefault(),A(!1),ne(ie)},children:[t.jsxs("button",{type:"button",onClick:()=>N(!p),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Po,{size:16}),w.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:w.length})]}),p&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Ua,{value:y==null?void 0:y.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[d&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d,children:"Reset panels"}),w.length>0&&L&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{L(),N(!1)},children:"Restore all"})]})]}),e&&x&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>x(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Ua,{value:y==null?void 0:y.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:rt(e)})]}),w.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:w.map(V=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{C==null||C(V),N(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:rt(V)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[w.indexOf(V)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",w.indexOf(V)+1]}):null,ls(V)]})]},V.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>k(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Wr,{size:16}),te>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:te})]}),b&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Needs attention"}),Te.map(V=>t.jsx(za,{conversation:V,isAttention:!0,shortcutIndex:ve.indexOf(V)>=0?ve.indexOf(V)+1:void 0,onClick:()=>{u==null||u(V),k(!1)}},V.tabKey))]}),je.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Task complete"}),je.map(V=>t.jsx(za,{conversation:V,shortcutIndex:ve.indexOf(V)>=0?ve.indexOf(V)+1:void 0,onClick:()=>{u==null||u(V),k(!1)}},V.tabKey))]}),te===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function bt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Hd(e,s){return String(e||"")!==String(s||"")}function Ud(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),o=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!o&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(m=>String(m||"").toLowerCase()).join(`
|
|
31
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||o&&!zo(c.summaryMetadata).map(m=>m.toLowerCase()).join(`
|
|
32
|
+
`).includes(o)))}function zd(e,s="recent"){const r=e.slice();return r.sort((n,o)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(s==="messages"){const i=(Number(o.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(o.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ii(e,s={}){return zd(Ud(e,s),s.sortMode||"recent")}function _r(e){return e?"Resume saved history":"Start fresh"}function Jn(e){return e?"Resuming saved history…":"Starting fresh…"}function Fd(){return"Start fresh"}function ci(e,s=!1){return e==="cli"?_r(s):e==="ide"?"Start IDE":"Start ACP session"}function li(e,s=!1){return e==="cli"?Jn(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Vd(){return"Recover hosted runtime"}function Gd(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function qd(){return"Open saved history"}function Yd(){return"Saved History"}function Zn(){return"Use saved history when you want continuity in the same provider conversation."}function Xd(){return"No saved history found yet."}function Qd(){return"Refresh saved history"}function Jd(){return"Refreshing saved history…"}function es(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ts(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ns(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ss(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ea(e){return`Resume saved history with ${e}?`}function ta(){return"Review or change the target workspace before resuming saved history."}function Zd(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function sa({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:o=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:m,onClose:f,onNewChat:u,onSwitchSession:x,onRefreshHistory:w,onResumeSavedSession:C}){var g;const L=s.find(h=>h.id===e.routeId),d=(L==null?void 0:L.chats)||[],b=(g=L==null?void 0:L.activeChat)==null?void 0:g.id,k=Xe(e)&&!Ge(e),[p,N]=a.useState(()=>bt()),R=l||p,y=h=>{if(m){m(h);return}N(h)},v=a.useMemo(()=>ii(o,{textQuery:R.textQuery,workspaceQuery:R.workspaceQuery,modelQuery:R.modelQuery,resumableOnly:R.resumableOnly,sortMode:R.sortMode}),[R.modelQuery,R.resumableOnly,R.sortMode,R.textQuery,R.workspaceQuery,o]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-center justify-center",children:[t.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.jsxs("div",{className:"px-6 py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)]",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:k?Yd():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Rd(e)}),k&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Zn()})]}),t.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-3 bg-bg-primary",children:[!k&&t.jsx("button",{onClick:u,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"}),k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:R.textQuery,onChange:h=>y({...R,textQuery:h.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:R.workspaceQuery,onChange:h=>y({...R,workspaceQuery:h.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:R.modelQuery,onChange:h=>y({...R,modelQuery:h.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:R.sortMode,onChange:h=>y({...R,sortMode:h.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:R.resumableOnly,onChange:h=>y({...R,resumableOnly:h.target.checked})}),"Resume-ready only"]})]}),v.map(h=>{const K=e.providerSessionId===h.providerSessionId,I=K||!h.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!C||C(h)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${K?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${I?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${K?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:h.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Zd(h.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:h.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[h.workspace||"Workspace unknown",cs(h.summaryMetadata)?` · ${cs(h.summaryMetadata)}`:"",h.messageCount>0?` · ${h.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:K?"ACTIVE":h.canResume?c===h.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},h.id)})]}):d.map(h=>t.jsxs("div",{onClick:()=>{x(e.routeId,h.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===h.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${b===h.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:h.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[h.id.substring(0,12),"..."]}),b===h.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},h.id)),(k&&!i&&v.length===0||!k&&d.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(Vc,{size:32})}),t.jsx("div",{className:"text-[13px]",children:k?o.length>0?"No saved history matches these filters.":Xd():"No recent chat sessions found."})]}),k&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Jd()})})]}),t.jsx("div",{className:"px-5 py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right",children:t.jsx("button",{onClick:w,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Is,{size:13})," ",k?Qd():"Refresh History"]})})})]})]});return typeof document>"u"?j:zs.createPortal(j,document.body)}const Fa={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 di({toasts:e,onDismiss:s,onClickToast:r}){return t.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:e.map(n=>{const o=Fa[n.type]||Fa.info;return t.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:[t.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))`}}),t.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:t.jsx(kt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.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:l=>{l.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const eu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function tu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function su(e){return e.sessionId||e.instanceId||e.agentType}function an(e,s){return e||s}function Va(e,s){const r=new Set,n=[];for(const o of s)if(o)for(const i of e[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 ui(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function mi(e,s={}){var n,o;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((o=s.machineNames)==null?void 0:o[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function ra(e,s,r={}){return ru(e,s,mi(e,r))}function ru(e,s,r={}){var w,C,L,d,b,k;const n=[],o=r.machineName,i=r.connectionState,c=tu(e),l=tt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(p=>{var N,R;return{sessionId:p.id,instanceId:p.id,providerSessionId:p.providerSessionId,transport:p.transport,agentType:p.providerType,agentName:p.providerName||tt(p.providerType),status:p.status,title:p.title,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,messages:((N=p.activeChat)==null?void 0:N.messages)||[],activeModal:((R=p.activeChat)==null?void 0:R.activeModal)||void 0,unread:p.unread,lastSeenAt:p.lastSeenAt,lastUpdated:p.lastUpdated,inboxBucket:p.inboxBucket,surfaceHidden:p.surfaceHidden}}):[],f=eu(e),u=e.activeChat||{title:""},x=u.title&&String(u.title).trim()?String(u.title).trim():"";if(f){const p=e.sessionId||e.instanceId,N=La(e.type),R=(w=e.activeChat)==null?void 0:w.activeModal,y=R&&Array.isArray(R.buttons)&&R.buttons.length>0,v=jt((C=e.activeChat)==null?void 0:C.status,{activeModal:(L=e.activeChat)==null?void 0:L.activeModal})||jt((b=(d=e.agents)==null?void 0:d[0])==null?void 0:b.status)||"idle",j=e.activeChat||{title:"",messages:[]};let g=j.title&&String(j.title).trim()?String(j.title).trim():"";const h=(k=e.activeChat)==null?void 0:k.id,K=e.chats;if(h&&Array.isArray(K)&&K.length>0){const S=K.find(H=>H.id===h||H.id&&String(H.id)===String(h));S!=null&&S.title&&String(S.title).trim()&&(g=String(S.title).trim())}const I=(Xe(e)||Ge(e),e.type),A=(Xe(e)||Ge(e))&&_a(g,N,I)?"":g,M=j.messages||[],O=Va(s,[e.id,p]),_=Ka(M,O);n.push({routeId:e.id,sessionId:p,providerSessionId:e.providerSessionId,nativeSessionId:p,transport:e.transport,daemonId:e.daemonId||void 0,mode:Xe(e)?e.mode||"terminal":"chat",agentName:N,agentType:I,status:v,title:A,messages:[...M,..._],resume:e.resume,hostIdeType:!Xe(e)&&!Ge(e)?e.type:void 0,workspaceName:c,displayPrimary:c||A||(Xe(e)?e.mode==="chat"?N:"Terminal":N),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:y?R.buttons:void 0,modalMessage:y?R.message:void 0,streamSource:"native",tabKey:an(p,e.id),machineName:o,connectionState:i})}if(f&&(Xe(e)||Ge(e)))return n;for(const p of m){const N=p.activeModal&&Array.isArray(p.activeModal.buttons)&&p.activeModal.buttons.length>0,R=Tl(p),y=su(p),v=`${e.id}:${y}`,j=p.title&&String(p.title).trim()||"",g=_a(j,p.agentName,p.agentType)?"":j,h=p.messages||[],K=Va(s,[v,p.sessionId,p.instanceId]),I=Ka(h,K);(p.transport==="cdp-webview"||p.sessionId||p.providerSessionId||h.length>0||I.length>0||N||g||!["idle","panel_hidden","disconnected","not_monitored"].includes(R))&&n.push({routeId:e.id,sessionId:p.sessionId||p.instanceId,providerSessionId:p.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:p.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:p.agentName,agentType:p.agentType,status:R,title:g,messages:[...h,...I],hostIdeType:e.type,workspaceName:c,displayPrimary:c||x||g||l,displaySecondary:`${l} · ${p.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,lastUpdated:p.lastUpdated||e.lastUpdated,modalButtons:N?p.activeModal.buttons:void 0,modalMessage:N?p.activeModal.message:void 0,streamSource:"agent-stream",tabKey:an(p.sessionId||p.instanceId,v),machineName:o,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,mode:"chat",agentName:La(e.type),agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:an(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function nu(e){const s=e.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:e}}function au(e,s){const r=nu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const pi=[{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:"🏄"}],fi=[{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:"🧩"}],xi=[{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:"🟠"}],ou=pi,iu=fi,cu=xi;function ds(...e){return bc(gc(e))}function lu({icon:e,title:s,subtitle:r,badge:n,actions:o,className:i}){return t.jsxs("div",{className:ds("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),o&&t.jsx("div",{className:"flex gap-2",children:o})]})}function hi({icon:e,title:s,subtitle:r,badge:n,actions:o,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(lu,{icon:e,title:s,subtitle:r,badge:n,actions:o}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ds("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Dt({title:e,icon:s,description:r,accentColor:n,className:o,children:i}){return t.jsxs("div",{className:ds("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:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function bi({icon:e,title:s,description:r,action:n,className:o}){return t.jsxs("div",{className:ds("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const du={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"},uu={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function mu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ds("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",du[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:uu[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const pu={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"},fu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function xu({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ds("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",pu[e],r),children:[t.jsx("span",{className:ds("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",fu[e])}),n]})}const _n="adhdev:themechange";function hu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function fs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?hu():e}function gi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function kr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(_n,{detail:{preference:e,theme:s}}))}function bu(){const e=fs(),s=xs(e);gi(s),kr(e,s)}function na(){const[e,s]=a.useState(fs),[r,n]=a.useState(()=>xs(fs()));a.useEffect(()=>{gi(r)},[r]),a.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=m=>{if(e==="system"){const f=m.matches?"light":"dark";n(f),kr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),a.useEffect(()=>{const c=m=>{const f=m.detail||{},u=f.preference,x=f.theme;s(u==="dark"||u==="light"||u==="system"?u:fs()),n(x==="dark"||x==="light"?x:xs(fs()))},l=m=>{if(m.key!=="theme")return;const f=fs(),u=xs(f);s(f),n(u)};return window.addEventListener(_n,c),window.addEventListener("storage",l),()=>{window.removeEventListener(_n,c),window.removeEventListener("storage",l)}},[]);const o=a.useCallback(c=>{const l=xs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}kr(c,l)},[]),i=a.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",m=xs(l);n(m);try{localStorage.setItem("theme",l)}catch{}return kr(l,m),l})},[]);return{theme:r,preference:e,setPreference:o,cycleTheme:i,isDark:r==="dark"}}const Ga={dark:"Dark",light:"Light",system:"System"};function gu({collapsed:e}){const{preference:s,cycleTheme:r}=na(),n=s==="dark"?t.jsx(qc,{size:16}):s==="light"?t.jsx(Gc,{size:16}):t.jsx(Yc,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Ga[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Ga[s]})]})}function Jt({label:e,description:s,checked:r,disabled:n,onChange:o,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.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:[t.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))"}}),t.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 yu({onPrefChange:e}){const[s,r]=Bl(),n=(o,i)=>{r({[o]:i}),e==null||e(o,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Wr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:o=>n("globalEnabled",o)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:o=>n("browserNotifications",o)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:o=>n("completionAlert",o)}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qc,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:o=>n("approvalAlert",o)}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:o=>n("disconnectAlert",o)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Rr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function vu(e,s){const r=Rr(e),n=Rr(s);if(!r||!n)return e.localeCompare(s);for(let o=0;o<3;o+=1){if(r[o]<n[o])return-1;if(r[o]>n[o])return 1}return 0}function yi(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Os(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||vu(r,s)>=0)return!1;const n=Rr(r),o=Rr(s);return!n||!o?!1:n[0]!==o[0]||n[1]!==o[1]}function wu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function on(e,s){return e instanceof Error?e.message:s}function ju({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(bi,{icon:t.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||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(Nu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o},c.id))})}function qa({title:e,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 zs.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.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"}),t.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 ku(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...ou,...iu,...cu].find(o=>o.id===s||s.includes(o.id)||o.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Nu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:o}){var O,_;const[i,c]=a.useState("idle"),[l,m]=a.useState(""),[f,u]=a.useState(null),[x,w]=a.useState("idle"),[C,L]=a.useState(""),d=e.version||null,b=((O=e.machine)==null?void 0:O.platform)||((_=e.system)==null?void 0:_.platform)||"",k=Ct(e,{fallbackId:e.id}),p=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",N=s.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),R=s.filter(S=>S.daemonId===e.id&&S.transport==="pty"),y=s.filter(S=>S.daemonId===e.id&&S.transport==="acp"),v=e.p2p,j=async()=>{if(r){c("upgrading"),m("Starting upgrade...");try{const S=wu(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(c("done"),m(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(c("done"),m(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(S.error||"Upgrade failed"))}catch(S){c("error"),m(on(S,"Connection lost during upgrade"))}}},g=async()=>{if(u(null),!!n){w("loading");try{await n(e.id),w("done"),L("Machine disconnected.")}catch(S){w("error"),L(on(S,"Failed to disconnect"))}}},h=async()=>{if(u(null),!!o){w("loading");try{await o(e.id),w("done"),L("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){w("error"),L(on(S,"Failed to revoke token"))}}},K="0.8.61",I=yi(e,K),A=Os(e,K),M=N.length+R.length+y.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:p}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:k}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${I?"":"bg-bg-secondary"}`,style:I?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!I&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&I&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:x==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),o&&t.jsx("button",{onClick:()=>u("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(xu,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[v&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${v.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${v.state==="connecting"||v.state==="new"?"animate-pulse":""}`,style:v.state==="connecting"||v.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",v.state==="connected"?"connected":v.state==="connecting"||v.state==="new"?"connecting...":v.state||"off"]}),v.peers!==void 0&&v.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",v.peers," peer",v.peers!==1?"s":"",")"]})]}),v&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(S=>{const H=ku(S.type),q=S.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:H.icon}),t.jsx("span",{children:H.name}),q!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${q?"bg-green-400":"animate-pulse"}`,style:q?void 0:{background:"var(--status-warning)"},title:q?"CDP connected":"CDP connecting..."})]},S.id)}),R.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:S.cliName||"CLI"})]},S.id)),y.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:S.cliName||"ACP"})]},S.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||C)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:C||l})]}),f==="disconnect"&&t.jsx(qa,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
|
|
33
|
+
|
|
34
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
|
+
|
|
36
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:g,onCancel:()=>u(null)}),f==="revoke"&&t.jsx(qa,{title:"⚠️ Remove Machine",message:`Remove "${k}" from your dashboard?
|
|
37
|
+
|
|
38
|
+
This will:
|
|
39
|
+
• Immediately disconnect the machine
|
|
40
|
+
• Delete the machine registration
|
|
41
|
+
• Require restarting ADHDev on that machine
|
|
42
|
+
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:h,onCancel:()=>u(null)})]})}const Su=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Cu(){const{preference:e,setPreference:s}=na();return t.jsx("div",{className:"flex gap-2",children:Su.map(r=>t.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 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Iu(e){const s=e.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 Tu(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function cn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Ya(e){const{r:s,g:r,b:n}=Tu(e);return .2126*cn(s)+.7152*cn(r)+.0722*cn(n)}function Xa(e,s){const r=Ya(e),n=Ya(s),o=Math.max(r,n),i=Math.min(r,n);return(o+.05)/(i+.05)}function vi(e){const s=Iu(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Xa(s,r)>=Xa(s,n)?r:n}const Rn={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},Pn={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},Au=[{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"}}}],wi="adhdev-chat-theme",ji="adhdev-chat-theme-custom";function Nr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(wi)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(ji);if(s){const r=JSON.parse(s);return{...e==="dark"?Rn:Pn,...r[e]}}}catch{}return e==="dark"?Rn:Pn}function dr(e,s){try{localStorage.setItem(ji,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${o}, ${s})`}function Pr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),o=Math.min(255,parseInt(e.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 Mu={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Hs(e,s){var o;const r=(o=Mu[e])==null?void 0:o[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Pr(r,24)),n.style.setProperty("--accent-on-primary",vi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Pr(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function ss(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Pr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",vi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Pr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function aa(){const e=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=>e.style.removeProperty(r))}function Lu(e){try{localStorage.setItem(wi,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=rs()?"dark":"light";ss(Et(s))}else aa(),Hs(e,rs()?"dark":"light")}function _u(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Nr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=rs()?"dark":"light";ss(Et(s))}else aa(),Hs(e,rs()?"dark":"light")}function rs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.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}}),t.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 Rs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ru({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,o]=a.useState(()=>Et(r));a.useEffect(()=>{o(Et(r))},[r]);const i=a.useCallback((c,l)=>{o(m=>{const f={...m,[c]:l},x=Et(r==="dark"?"light":"dark");return r==="dark"?dr(f,x):dr(x,f),ss(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Rs,{title:"App Background",children:[t.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Rs,{title:"App Text",children:[t.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Rs,{title:"Borders & Accent",children:[t.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Rs,{title:"Chat Bubbles",children:[t.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Rs,{title:"Chat Layout",children:[t.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(wt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.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)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?Rn:Pn,m=Et(e?"light":"dark");e?dr(c,m):dr(m,c),o(c),ss(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 Pu(){const[e,s]=a.useState(Nr),[r,n]=a.useState(!0),[o,i]=a.useState(()=>Et("dark"));a.useEffect(()=>{n(rs());const m=new MutationObserver(()=>{const x=rs();n(x);const w=Nr();w==="custom"?ss(Et(x?"dark":"light")):Hs(w,x?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const x=rs();n(x);const w=Nr();w==="custom"?ss(Et(x?"dark":"light")):Hs(w,x?"dark":"light")};return f.addEventListener("change",u),()=>{m.disconnect(),f.removeEventListener("change",u)}},[]),a.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ss(Et(r?"dark":"light")):(aa(),Hs(e,r?"dark":"light"))},[e,r]),a.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=m=>{s(m),Lu(m)},l=[...Au,{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 t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(m=>{const f=e===m.id,u=r?m.preview.dark:m.preview.light,x=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?o.userText:"#fff";return t.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:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:x},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(Ru,{dark:r,onColorsChange:m=>i(m)})]})}const ki="adhdev_mobileDashboardMode_v1";function Ni(){try{return localStorage.getItem(ki)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Du(e){try{localStorage.setItem(ki,e)}catch{}}function Eu(){const[e,s]=a.useState(!0);return a.useEffect(()=>{s(Ni()==="chat")},[]),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ut,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"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:e,onChange:r=>{s(r),Du(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function $u(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function Bu(e,s){const{sendData:r}=_t(),{injectEntries:n,getIdes:o}=Tr(),i=Array.from(new Set(e.filter(Boolean))).join("|");a.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(m=>Vt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},f=>{const u=o().find(w=>w.id===m),x=$u(u,m,f);n([x])}));return()=>{l.forEach(m=>m())}},[i,o,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Wu=4e3;function Si(e,s){const{sendData:r}=_t(),[n,o]=a.useState(null),[i,c]=a.useState(!1);return a.useEffect(()=>{if(!e){o(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}o(null),c(!0);let l=null;const m=Vt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),o(f.diagnostics),c(!1)});return m.initialSendAccepted?l=setTimeout(()=>{c(!1)},Wu):c(!1),()=>{l&&clearTimeout(l),m()}},[e,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 Ku(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ci(e){const{sendData:s}=_t(),[r,n]=a.useState({});return a.useEffect(()=>{const o=Ku(e);if(!o||!e.sessionId||!s){n({});return}const i=Vt.subscribe({sendData:s},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),as.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Ii="adhdev_hiddenTabs";function Ou(){try{const e=localStorage.getItem(Ii);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ms(e){try{localStorage.setItem(Ii,JSON.stringify([...e]))}catch{}}function Hu(){const[e,s]=a.useState(Ou),r=a.useCallback(f=>{s(u=>{const x=new Set(u);return x.has(f)?x.delete(f):x.add(f),ms(x),x})},[]),n=a.useCallback(f=>{s(u=>{if(u.has(f))return u;const x=new Set(u);return x.add(f),ms(x),x})},[]),o=a.useCallback(f=>{s(u=>{if(!u.has(f))return u;const x=new Set(u);return x.delete(f),ms(x),x})},[]),i=a.useCallback(()=>{s(f=>{if(f.size===0)return f;const u=new Set;return ms(u),u})},[]),c=a.useCallback((f,u)=>{s(x=>{const w=new Set(x);for(const C of u)w.add(C);return ms(w),w})},[]),l=a.useCallback((f,u)=>{s(x=>{const w=new Set(x);for(const C of u)w.delete(C);return ms(w),w})},[]),m=a.useCallback(f=>e.has(f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:o,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:m}}function Uu({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){a.useEffect(()=>{Kl()},[]);const o=a.useMemo(()=>e.map(i=>({id:i.tabKey,name:ni(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Hl(o),a.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const m=Date.now(),f={};for(const[u,x]of Object.entries(l))m-x<5e3&&(f[u]=x);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),a.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const m=l.filter(f=>f.timestamp>c).slice(-100);return m.length===l.length?l:m})},6e4);return()=>clearInterval(i)},[n]),null}function zu(e){const s=e.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 ur(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Fu(e,s){const r=Date.now();return e.map(n=>{const o=s[n.tabKey];return o&&r-o<5e3?{...n,messages:[],title:""}:n})}function Vu(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const o of e.childSessions||[]){const i=o.id||o.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:o.id,ref:s[o.id]})}return r}function Gu(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function qu(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Yu(e){const s=qu(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Vs(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Xu({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:o}){const i=a.useRef([]),c=a.useRef([]),l=a.useRef([]),m=a.useRef([]),f=a.useMemo(()=>{const v=zu(e);return ur(i.current,v)?i.current:(i.current=v,v)},[e]),u=a.useMemo(()=>ui(e),[e]),x=a.useRef(new Map),w=a.useRef(new Map),C=a.useMemo(()=>{const v=new Map,j=[];for(const I of f){const{connectionState:A="new",machineName:M}=mi(I,{machineNames:u,connectionStates:s,defaultConnectionState:"new"}),O=Vu(I,r),_=x.current.get(I.id);if(_&&_.ide===I&&_.connectionState===A&&_.machineName===M&&Gu(_.localRefs,O)){v.set(I.id,_),j.push(..._.conversations);continue}const S=ra(I,r,{machineNames:u,connectionStates:s,defaultConnectionState:"new"}),H={ide:I,connectionState:A,machineName:M,localRefs:O,conversations:S};v.set(I.id,H),j.push(...S)}x.current=v;const g=new Map,h=I=>{const A=Yu(I),M=w.current.get(I.tabKey);if(M&&M.signature===A)return g.set(I.tabKey,M),M.timestamp;const O={signature:A,timestamp:oi(I)||(M==null?void 0:M.timestamp)||0};return g.set(I.tabKey,O),O.timestamp},K=[...j].sort((I,A)=>Lr(I,A,h));return w.current=g,K},[f,r,s,u]),L=a.useMemo(()=>{const v=Fu(C,n);return ur(c.current,v)?c.current:(c.current=v,v)},[C,n]),d=a.useMemo(()=>{const v=new Map,j=Array.from(new Set(L.map(g=>g.routeId)));for(const g of j){const h=Bt(L,g);h&&v.set(g,h)}return v},[L]),b=a.useMemo(()=>{const v=new Map;for(const j of L)if(j.sessionId&&v.set(j.sessionId,j),j.streamSource==="native"&&j.sessionId){const g=d.get(j.routeId);g&&v.set(j.sessionId,g)}return v},[L,d]),k=a.useMemo(()=>{const v=new Map;for(const j of L)j.sessionId&&v.set(j.sessionId,j),v.set(j.routeId,d.get(j.routeId)||j),v.set(j.tabKey,j);return v},[L,d]),p=a.useCallback(v=>{if(v)return b.get(v)},[b]),N=a.useCallback(v=>{if(v)return k.get(v)},[k]),R=a.useMemo(()=>{const v=L.filter(j=>!o.has(j.tabKey));return ur(l.current,v)?l.current:(l.current=v,v)},[L,o]),y=a.useMemo(()=>{const v=R.map(j=>j.tabKey);return ur(m.current,v)?m.current:(m.current=v,v)},[R]);return{chatIdes:f,conversations:L,visibleConversations:R,visibleTabKeys:y,resolveConversationBySessionId:p,resolveConversationByTarget:N}}function Qu({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const o=a.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=a.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=a.useCallback(()=>{s&&n(l=>{const m=new URLSearchParams(l);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:o,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Ju({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:o}){a.useEffect(()=>{st.setIdes(e)},[e]),a.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),a.useEffect(()=>{const i=st.onToast(m=>{r(u=>u.some(w=>w.message===m.message&&m.timestamp-w.timestamp<3e3)?u:[...u.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(u=>u.filter(x=>x.id!==m.id)),f)}),c=st.onSystemMessage((m,f)=>{var C,L;const u=o(m),x=(C=f._localId)==null?void 0:C.startsWith("sys_approval_"),w=!!(u&&(u.status==="waiting_approval"||(L=u.modalButtons)!=null&&L.length||u.modalMessage));x&&w||n(d=>({...d,[m]:[...d[m]||[],f]}))}),l=st.onClearSystemMessage((m,f)=>{n(u=>{var x;return(x=u[m])!=null&&x.length?{...u,[m]:u[m].filter(w=>{var C;return!(w.role==="system"&&((C=w._localId)!=null&&C.startsWith(f)))})}:u})});return()=>{i(),c(),l()}},[r,n]),a.useEffect(()=>{const i=ti.on("status_event",c=>{st.handleRawEvent(c,"ws")});return()=>{i()}},[]),a.useEffect(()=>{var c;const i=l=>{var b;const m=l.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,u=o(f),x=(u==null?void 0:u.routeId)||m.daemonId;if(!x)return;const w=Number(m.buttonIndex),C=m.button||((b=u==null?void 0:u.modalButtons)==null?void 0:b[w])||"Approve",L=String(C).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);s(x,"resolve_action",{action:d?"approve":"reject",button:C,...Number.isFinite(w)&&{buttonIndex:w},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...m.targetSessionId&&{targetSessionId:m.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[o,s])}const Zu="adhdev_dashboardLayout_v1",em="adhdev_dashboardDockview_v1",tm="adhdev_dashboardDockviewHiddenRestore_v1",Ps={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function oa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Ti(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ai(e){return`${Zu}:${e}`}function sm(e){const s=Ai(e);return oa(s,null)}function rm(e,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=Ai(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Mi(e){return`${em}:${e}`}function nm(e){const s=Mi(e);return oa(s,null)}function am(e,s){try{const r=Mi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Li(e){return`${tm}:${e}`}function om(e){const s=Li(e);return oa(s,{})}function im(e,s){try{const r=Li(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function cm(){return{groupAssignments:[...Ps.groupAssignments],focusedGroup:Ps.focusedGroup,groupActiveTabIds:{...Ps.groupActiveTabIds},groupTabOrders:{...Ps.groupTabOrders},groupSizes:[...Ps.groupSizes]}}function lm(){const[e]=a.useState(()=>Ti(typeof window<"u"?window.innerWidth:1280)),[s,r]=a.useState(()=>new Map),[n,o]=a.useState(0),[i,c]=a.useState({}),[l,m]=a.useState({}),[f,u]=a.useState([]),[x,w]=a.useState(()=>typeof window<"u"&&window.innerWidth<768),[C,L]=a.useState(!1),d=a.useCallback(()=>{if(C)return;const b=sm(e)??cm();r(new Map(b.groupAssignments)),o(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),u(b.groupSizes),L(!0)},[C,e]);return a.useEffect(()=>{C&&rm(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[C,e,s,n,i,l,f]),a.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),k=p=>w(p.matches);return b.addEventListener("change",k),()=>b.removeEventListener("change",k)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:o,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:m,groupSizes:f,setGroupSizes:u,isMobile:x,hasHydratedStoredLayout:C,hydrateStoredLayout:d}}function dm(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[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 um({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:o,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:m,historyModalOpen:f,activeConv:u,isRefreshingHistory:x,ides:w,handleRefreshHistory:C}){const L=a.useRef(!1),d=a.useRef(!1),b=a.useRef(null),k=a.useRef(!1);a.useEffect(()=>{if(!e||L.current||s.length===0)return;if(!o){i();return}const p=r(e);if(!p)return;const N=n.get(p.tabKey)??0;c(R=>({...R,[N]:p.tabKey})),l(N),L.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(R=>{const y=new URLSearchParams(R);return y.delete("activeTab"),y},{replace:!0})},[e,s,r,n,o,i,c,l,m]),a.useEffect(()=>{if(!(d.current||o)&&s.length!==0){if(!e){i(),d.current=!0;return}if(L.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)}}},[e,s.length,o,i]),a.useEffect(()=>{if(!f){k.current=!1;return}if(!u||k.current||x)return;const p=w.find(N=>N.id===u.routeId);p&&(!p.chats||p.chats.length===0||dm(p.chats,u))&&(k.current=!0,C())},[f,u,x,w,C]),a.useEffect(()=>{if(!u)return;let p=null,N=0,R=-1,y=0;const v=()=>{p=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(h=>h.offsetParent!==null);if(j.length===0){N<18&&(N+=1,p=requestAnimationFrame(v));return}let g=0;for(const h of j)h.scrollTop=h.scrollHeight,g+=h.scrollHeight;g===R?y+=1:(y=0,R=g),N+=1,!(y>=2||N>=18)&&(p=requestAnimationFrame(v))};return p=requestAnimationFrame(v),()=>{p!=null&&cancelAnimationFrame(p)}},[u==null?void 0:u.tabKey])}function mm({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:o,conversations:i,ides:c,resolveConversationByTarget:l}){const[m,f]=a.useState(null),[u,x]=a.useState(null),w=a.useMemo(()=>{if(e||!n)return null;const k=l(n);return k&&!Xe(k)&&!Ge(k)?k:null},[e,n,l]),C=a.useMemo(()=>{const k=m==null?void 0:m.routeId;if(!k)return null;const p=m!=null&&m.tabKey?i.find(N=>N.tabKey===m.tabKey):o?i.find(N=>N.tabKey===o):null;return(p==null?void 0:p.routeId)===k?p:Bt(i,k)},[i,m,o]),L=a.useMemo(()=>{if(C)return c.find(k=>k.id===C.routeId)},[c,C]);a.useEffect(()=>{w&&(f({routeId:w.routeId,tabKey:Da(w)}),x(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const d=a.useCallback(k=>{k&&(f({routeId:k.routeId,tabKey:Da(k)}),x(k))},[]),b=a.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:C,remoteDialogIdeEntry:L,remoteDialogActiveConv:u,setRemoteDialogActiveConv:x,openRemoteDialog:d,closeRemoteDialog:b}}function gs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Xe(e)||Ge(e)?{agentType:St(e)}:e.streamSource==="agent-stream"?{agentType:St(e)}:s}function Qs(e){return e?Ar(e):""}function Ds(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ln(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[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 Qa({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:o,setLocalUserMessages:i,setClearedTabs:c}){const[l,m]=a.useState(!1),[f,u]=a.useState(!1),x=a.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),w=a.useCallback(async(d,b)=>{try{const k=d||(s==null?void 0:s.daemonId)||"",p=await e(k,"switch_chat",{id:b,sessionId:b,...gs(s)}),N=p==null?void 0:p.result;if((p==null?void 0:p.success)===!0||N==="switched"||N==="switched-by-title")return;N===!1||N==="not_found"?Ds(o,"⚠️ Session tab not found — try refreshing history"):typeof N=="string"&&N.startsWith("error:")?Ds(o,`⚠️ Switch error: ${N}`):Ds(o,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),Ds(o,`❌ Switch failed: ${k.message||"connection error"}`)}},[s,e,o]),C=a.useCallback(async()=>{if(!(!s||l)){m(!0);try{const d=Qs(s);await e(d,"new_chat",{...gs(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,l,e,c,i]),L=a.useCallback(async()=>{var d,b;if(!(!s||f)){u(!0);try{const k=Qs(s),p=async()=>e(k,"list_chats",{forceExpand:!0,...gs(s)});let N=await p(),R=(N==null?void 0:N.chats)||((d=N==null?void 0:N.result)==null?void 0:d.chats);ln(R,s)&&(await new Promise(y=>setTimeout(y,450)),N=await p(),R=(N==null?void 0:N.chats)||((b=N==null?void 0:N.result)==null?void 0:b.chats)),N!=null&&N.success&&Array.isArray(R)&&(n(s.routeId,R),ln(R,s)&&!ln(r,s)&&Ds(o,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{u(!1)}}},[s,r,f,e,n,o]);return{isCreatingChat:l,isRefreshingHistory:f,handleLaunchIde:x,handleSwitchSession:w,handleNewChat:C,handleRefreshHistory:L}}function pm(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function fm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Ja(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(o=>s[Number(o)]===e[Number(o)])}function mr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const o={};n.forEach((c,l)=>{o[c]=l}),n.length===0&&(o[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const m=o[l];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:o,usedGroups:n}}function Za(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=o)}return r}function xm(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(o=>o<e)??s[0];return r[n]??0}function hm(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),o=n.length===s.length?n:Array(r).fill(100/r),i=o.reduce((c,l)=>c+l,0);return i>0?o.map(c=>c/i*100):Array(r).fill(100/r)}function eo(e,s){const r={};for(const[n,o]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=o}return r}function to(e){return Array(e).fill(100/e)}function bm({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:o,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:m,visibleTabKeys:f}){const u=a.useRef(null),x=a.useMemo(()=>mr(e,f),[e,f]),w=x.assignments,C=a.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),L=C>1,d=a.useCallback((y,v)=>{s(j=>{const g=new Map(mr(j,f).assignments);return v===0?g.delete(y):g.set(y,v),g}),n(j=>({...j,[v]:y})),r(v)},[s,f,n,r]),b=a.useCallback(y=>{s(v=>{const j=mr(v,f).assignments,g=new Map;for(const[h,K]of j)K!==y&&(K>y?g.set(h,K-1):g.set(h,K));return g}),c(v=>{if(v.length<=1)return[];const j=[...v];j.splice(y,1);const g=j.reduce((h,K)=>h+K,0);return g>0?j.map(h=>h/g*100):[]}),r(0)},[s,f,c,r]),k=a.useCallback((y,v)=>{v.preventDefault();const j=u.current;if(!j)return;const g=v.clientX,h=j.offsetWidth,K=i.length===C?[...i]:to(C),I=M=>{const _=(M.clientX-g)/h*100,S=[...K];S[y]=Math.max(15,K[y]+_),S[y+1]=Math.max(15,K[y+1]-_),c(S)},A=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",A)},[i,C,c]),p=a.useCallback((y,v,j)=>{if(C>=4)return;const g=j==="left"?v:v+1;s(h=>{const K=mr(h,f).assignments,I=new Map;for(const A of m){const M=K.get(A.tabKey)??0,O=M>=g?M+1:M;O>0&&I.set(A.tabKey,O)}return g>0&&I.set(y,g),I}),c(h=>{const K=h.length===C?[...h]:to(C),I=K[v]??100/C,A=Math.max(15,I/2),M=Math.max(15,I/2),O=[...K];O[v]=A,O.splice(g,0,M);const _=O.reduce((S,H)=>S+H,0);return O.map(S=>S/_*100)}),n(h=>{const K=eo(h,g);return K[g]=y,K}),o(h=>{const K=eo(h,g);return K[g]=[y],K}),r(g)},[C,s,f,m,c,n,o,r]);a.useEffect(()=>{pm(e,w)||s(w)},[e,w,s]),a.useEffect(()=>{const{mapping:y,usedGroups:v}=x;n(j=>{const g=Za(j,y);return Ja(j,g)?j:g}),o(j=>{const g=Za(j,y);return Ja(j,g)?j:g}),r(j=>{const g=l?0:xm(j,v,y);return j===g?j:g}),c(j=>{const g=l?[]:hm(j,v,x.groupCount);return fm(j,g)?j:g})},[x,l,n,o,r,c]);const N=a.useMemo(()=>{const y=Array.from({length:C},()=>[]);for(const v of m){const j=w.get(v.tabKey)??0,g=Math.min(j,C-1);y[g].push(v)}return y},[m,w,C]),R=a.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:w,numGroups:C,isSplitMode:L,groupedConvs:N,moveTabToGroup:d,closeGroup:b,handleResizeStart:k,splitTabRelative:p,clearAllSplits:R}}function gm({ides:e,sendDaemonCommand:s}){const r="0.8.61",n=a.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:yi(u,r)).sort((u,x)=>Number(Os(x,r))-Number(Os(u,r))),[r,e]),o=a.useMemo(()=>n.some(u=>Os(u,r)),[r,n]),[i,c]=a.useState(!1),[l,m]=a.useState({}),f=a.useCallback(async u=>{var x,w;m(C=>({...C,[u]:"upgrading"}));try{const C=await s(u,"daemon_upgrade",{});(x=C==null?void 0:C.result)!=null&&x.upgraded||(w=C==null?void 0:C.result)!=null&&w.success?m(L=>({...L,[u]:"done"})):m(L=>({...L,[u]:"error"}))}catch{m(C=>({...C,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:o,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}function so(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ia(e){return e instanceof Error?e.message:String(e||"")}function ro(e){const s=ia(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function no(e,s){const r=ia(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Ur({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:o}){const[i,c]=a.useState(!1),[l,m]=a.useState(!1),f=a.useRef(!1),u=a.useRef(null),x=a.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||f.current)return;const k=s.tabKey,p=Date.now(),N=u.current;if(N&&N.tabKey===k&&N.message===b&&p-N.timestamp<2e3)return;f.current=!0,m(!0),u.current={tabKey:k,message:b,timestamp:p};const R=`${p}-${Math.random().toString(36).slice(2,8)}`,y={role:"user",content:b,timestamp:p,_localId:R},v=!(Xe(s)||Ge(s));v&&r(j=>({...j,[k]:[...j[k]||[],y]}));try{const j=Qs(s);if(!j)return;const g=await e(j,"send_chat",{message:b,...gs(s)}),h=so(g);if(v&&(h!=null&&h.deduplicated||(h==null?void 0:h.sent)===!1)){r(K=>({...K,[k]:(K[k]||[]).filter(I=>I._localId!==R)}));return}if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Send failed");setTimeout(()=>{const K=Date.now()-6e4;r(I=>{const A=I[k];if(!A)return I;const M=A.filter(O=>O.timestamp>K);return M.length===A.length?I:{...I,[k]:M}})},6e4)}catch(j){const g=ia(j);g.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",g):console.error("Send failed",j),v&&r(h=>({...h,[k]:(h[k]||[]).filter(K=>K._localId!==R)}))}finally{f.current=!1,m(!1)}},[s,e,r]),w=a.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),C=a.useCallback(async d=>{if(s)try{const k=(s.modalButtons||[]).indexOf(d),p=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(p),R=Qs(s);if(!R)return;const y=await e(R,"resolve_action",{button:d,action:N?"approve":"reject",...k>=0&&{buttonIndex:k},...gs(s)}),v=so(y);v.success||n(j=>[...j,{routeId:s.tabKey,text:no(d,v==null?void 0:v.error),timestamp:Date.now()}])}catch(b){ro(b)||console.error("[ModalButton] Error:",b),n(k=>[...k,{routeId:s.tabKey,text:ro(b)?no(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),L=a.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,"focus_session",{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:x,handleRelaunch:w,handleModalButton:C,handleFocusAgent:L}}const ca=a.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:o,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:m,isSendingChat:f,handleFocusAgent:u,isFocusingAgent:x,actionLogs:w,userName:C,scrollToBottomRequestNonce:L,isInputActive:d=!0}){const b=Ci(s),k=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 t.jsxs(t.Fragment,{children:[t.jsx(Oo,{activeConv:k,onModalButton:c}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(is,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.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:l,children:"Relaunch with CDP"})]})}):null,k.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Dd,{activeConv:k,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:f,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(An,{activeConv:k,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:u,isFocusingAgent:x,actionLogs:w,userName:C,scrollToBottomRequestNonce:L,isInputActive:d})})]}):t.jsx(An,{activeConv:k,ideEntry:o,handleSendChat:m,isSendingChat:f,handleFocusAgent:u,isFocusingAgent:x,actionLogs:w,userName:C,scrollToBottomRequestNonce:L,isInputActive:d})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function ym({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:o,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:m,onOpenNativeConversation:f,onOpenMachine:u,onOpenHistory:x,onOpenRemote:w,onHideConversation:C,onStopCli:L,cliViewMode:d,onSetCliViewMode:b,handleSendChat:k,handleFocusAgent:p,handleModalButton:N,handleRelaunch:R}){const y=a.useRef(null),v=Xe(e)&&!s,j=v&&d==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(Kn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:rt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Qo,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>f(e),onOpenMachine:()=>u(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[v&&d&&t.jsx(Qn,{mode:d,onChange:b,compact:!0}),v&&L&&t.jsx("button",{onClick:()=>{L(e)},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:t.jsx(kt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:t.jsx(Hn,{size:14})}),!s&&!v&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(It,{size:14})}),C&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(e),type:"button",title:"Close chat",children:t.jsx(kt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ca,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:y,handleModalButton:N,handleRelaunch:R,handleSendChat:k,isSendingChat:c,handleFocusAgent:p,isFocusingAgent:l,actionLogs:o,userName:i})})]})}const dn={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 vm(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function _i(){const[e,s]=a.useState("unix"),[r,n]=a.useState("powershell"),[o,i]=a.useState(!1),c=e==="unix"?"unix":r;a.useEffect(()=>{s(vm())},[]);const l=a.useCallback(()=>{navigator.clipboard.writeText(dn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="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"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="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"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:dn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:dn[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:o?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Ri({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:Ut}];return t.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:t.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=e===n;return t.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:[t.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:t.jsx(i,{size:15})}),t.jsx("span",{children:o})]},n)})})})}function pr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ps({children:e,className:s=""}){return t.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:e})}function Es({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function fr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const o=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:m,isConnecting:f}=Ts(e.conversation),u=rt(e.conversation),x=ls(e.conversation),w=ri(e.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",L=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",k=c?"text-text-secondary opacity-80":"text-text-muted",p=c?"text-text-muted opacity-80":"text-text-muted",N="text-[color:var(--status-warning)]";return t.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(e.conversation),type:"button",children:[o||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${L}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:u}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${p}`,children:Ko(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[x,m?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${N} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:N,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${k}`,children:e.preview})]}),o&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.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&&t.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"})]},e.conversation.tabKey)}function ao({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function wm({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:o,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:m,onShowConversation:f,onShowAllHidden:u,onOpenNewSession:x,onOpenMachine:w,onOpenSettings:C,onSectionChange:L,wsStatus:d="connected",isStandalone:b=!1}){const k=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",p=c.length>0,N=s.length>0||r.length>0||n.length>0||o.length>0,R=e==="machines"?"Machines":"Chats",y=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",v=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${y}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:R}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(Wr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.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:t.jsx($r,{size:18})})]})]})}),t.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] ${v}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:k?t.jsx(Es,{icon:t.jsx(ao,{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?t.jsx(Es,{icon:t.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 machines",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 ADHDev on a machine, sign in, and it will show up here.",children:!b&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(_i,{})})}):t.jsx(ps,{children:c.map((j,g)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(j.id),type:"button",children:[t.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:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(pr,{title:"Needs attention",className:"mb-0"}),t.jsx(ps,{children:s.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:m})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(pr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ps,{children:r.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:m})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(pr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ps,{children:n.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"working",getAvatarText:l,onOpenConversation:m})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&t.jsx(pr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?t.jsx(ps,{children:o.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:m})},j.conversation.tabKey))}):N?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):k?t.jsx(Es,{icon:t.jsx(ao,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):p?t.jsx(Es,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Ut,{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."}):t.jsx(Es,{icon:t.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."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.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:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:u,children:"Restore all"})]}),t.jsx(ps,{className:"bg-bg-secondary/25",children:i.map((j,g)=>t.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 ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(j),type:"button",children:[t.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:l(rt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:rt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ls(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&x&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(Ri,{section:e,onSectionChange:L})]})}function jm(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Pi(e){const s=[e.workspace||"Workspace unknown"],r=cs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=jm(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function zr(...e){const s=new Set,r=[],n=o=>{const i=typeof o=="string"?o.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const o of e){if(Array.isArray(o)){for(const i of o)n(i);continue}n(o)}return r}function km(e){const s=e.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(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=km(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 Nm(e){const s=e.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}function Sm(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Vr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),o=Sm(n);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(o==null?void 0:o.path)=="string"?o.path:r,c=i.includes("\\")?"\\":"/",l=(f,u)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${u}`:f==="/"||f==="\\"?`${c}${u}`:`${f.replace(/[\\/]+$/,"")}${c}${u}`,m=Array.isArray(o==null?void 0:o.files)?o.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,u)=>f.name.localeCompare(u.name)):[];return{path:i,directories:m}}function Gr({title:e,description:s,currentPath:r,directories:n,busy:o=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:m,onConfirm:f}){const[u,x]=a.useState(r);a.useEffect(()=>{x(r)},[r]);const w=Nm(r),C=u.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:l,"aria-label":"Close folder browser",children:t.jsx(kt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!w||o||m(w)},disabled:!w||o,children:[t.jsx(Kn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:u,onChange:L=>x(L.target.value),onKeyDown:L=>{L.key!=="Enter"||!C||o||(L.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"}),t.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"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(L=>t.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(L.path),children:[t.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:t.jsx(vs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:L.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:L.path})]})]},L.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.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 la({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:o,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:m=!1,showArgsInput:f,argsValue:u,onArgsChange:x,showModelInput:w,modelValue:C,onModelChange:L,historyProviderNode:d,onConfirm:b,onCancel:k}){const p=n==null?void 0:n.find(N=>N.key===o);return t.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:t.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:k,"aria-label":"Close launch confirmation",children:t.jsx(kt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:o||"",onChange:N=>i(N.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:m,children:n.map(N=>t.jsx("option",{value:N.key,children:N.label},N.key))}),(p==null?void 0:p.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p.description})]}),d,r.map(N=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),w&&L&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:C||"",onChange:N=>L(N.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:m})]}),f&&x&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:u||"",onChange:N=>x(N.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:m})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:k,disabled:m,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:m,children:[t.jsx(Un,{size:14}),m?l:c]})]})]})})}function oo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ns(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:o=!0}=e,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?"⭐ ":""}${oo(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:oo(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 l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Cm(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Im(e){return[Cm(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Tm(e){return e.lastLaunchedAt?Kr(e.lastLaunchedAt):""}function Di(e){return{metaText:Im(e),updatedLabel:Tm(e)}}function un(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Am({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:o,onListSavedSessions:i}){var nt,He,at,dt;const c=tr(),[l,m]=a.useState(!1),f=(((nt=e.detectedIdes)==null?void 0:nt.length)||0)>0,u=a.useMemo(()=>(e.workspaces||[]).map(be=>({id:be.id,path:be.path,label:be.label})),[e]),x=e.defaultWorkspaceId||null,[w,C]=a.useState(x||((He=u[0])==null?void 0:He.id)||""),[L,d]=a.useState(""),[b,k]=a.useState(""),[p,N]=a.useState([]),[R,y]=a.useState(!1),[v,j]=a.useState(""),[g,h]=a.useState(!1),[K,I]=a.useState(un(f,s.length,r.length)),A=a.useRef(null),[M,O]=a.useState(null),_=a.useRef("__home__"),[S,H]=a.useState("__home__"),[q,T]=a.useState(""),[D,W]=a.useState(""),[z,X]=a.useState(""),[he,Te]=a.useState([]),[je,ve]=a.useState(()=>bt().textQuery),[te,ne]=a.useState(()=>bt().workspaceQuery),[V,ie]=a.useState(()=>bt().modelQuery),[re,Z]=a.useState(()=>bt().resumableOnly),[me,se]=a.useState(()=>bt().sortMode),[ce,ee]=a.useState(!1),[pe,ae]=a.useState(!1),Se=a.useRef(null),ge=a.useRef(null);a.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const P=w==="__custom__"?L.trim():((at=u.find(be=>be.id===w))==null?void 0:at.path)||"",fe=w==="__custom__"&&!!P&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Y=w!=="__custom__"&&((dt=u.find(be=>be.id===w))==null?void 0:dt.path)||"",ue=a.useMemo(()=>(e.recentLaunches||[]).map(be=>be.workspace),[e]),Ie=a.useCallback(async be=>{y(!0),j("");try{const Ue=await o(be);k(Ue.path),d(Ue.path),N(Ue.directories)}catch(Ue){j(Ue instanceof Error?Ue.message:"Could not load folder")}finally{y(!1)}},[o]),Pe=a.useCallback(()=>{var Ue;C("__custom__"),h(!0);const be=Fr(e.platform,zr(L.trim(),Y,ue,e.defaultWorkspacePath,(Ue=u.find(Qe=>Qe.id===x))==null?void 0:Ue.path,u.map(Qe=>Qe.path)));Ie(be)},[L,x,Ie,ue,Y,e.platform,u]),Be=a.useCallback(be=>{if(be!=null&&be.workspaceId){C(be.workspaceId),d("");return}if(be!=null&&be.workspacePath){C("__custom__"),d(be.workspacePath);return}C(""),d("")},[]),qe=a.useCallback(be=>{if(C(be),be==="__custom__"){Pe();return}d("")},[Pe]),We=a.useCallback(be=>{C("__custom__"),d(be)},[]),Fe=a.useCallback((be,Ue)=>{A.current=Ue,_.current=be.selectedWorkspaceKey||"__home__",H(be.selectedWorkspaceKey||"__home__"),T(be.initialArgs||""),W(be.initialModel||""),X(""),Te([]);const Qe=be.providerType?`${e.id}:${be.providerType}`:null;if(Hd(ge.current,Qe)){const ze=bt();ve(ze.textQuery),ne(ze.workspaceQuery),ie(ze.modelQuery),Z(ze.resumableOnly),se(ze.sortMode)}ge.current=Qe,O(be),be.providerType&&i&&(ee(!0),i(be.providerType).then(ze=>Te(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>ee(!1)))},[i,e.id]),Ye=a.useMemo(()=>ii(he,{textQuery:je,workspaceQuery:te,modelQuery:V,resumableOnly:re,sortMode:me}),[V,re,he,me,je,te]);a.useEffect(()=>{z&&(Ye.some(be=>be.providerSessionId===z)||X(""))},[Ye,z]);const pt=a.useCallback(()=>{A.current&&(ae(!0),A.current().finally(()=>{A.current=null,ae(!1),O(null)}))},[]),Ke=a.useCallback(()=>{A.current=null,O(null)},[]),lt=a.useCallback(be=>{_.current=be,H(be)},[]);return a.useEffect(()=>{var be;Se.current!==e.id&&(Se.current=e.id,C(x||((be=u[0])==null?void 0:be.id)||"__custom__"),d(""),k(""),N([]),j(""),h(!1),ve(bt().textQuery),ne(bt().workspaceQuery),ie(bt().modelQuery),Z(bt().resumableOnly),se(bt().sortMode),ge.current=null,I(un(f,s.length,r.length)))},[r.length,s.length,x,f,e.id,u]),a.useEffect(()=>{var be;w!=="__custom__"&&(w&&u.some(Ue=>Ue.id===w)||C(x||((be=u[0])==null?void 0:be.id)||"__custom__"))},[x,w,u]),a.useEffect(()=>{K==="ide"&&f||K==="cli"&&s.length>0||K==="acp"&&r.length>0||I(un(f,s.length,r.length))},[K,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:m,hasIdeOptions:f,workspaceRows:u,defaultWorkspaceId:x,workspaceChoice:w,customWorkspacePath:L,browseCurrentPath:b,browseDirectories:p,browseBusy:R,browseError:v,browseDialogOpen:g,activeLauncherKind:K,launchConfirm:M,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:S,launchConfirmArgs:q,launchConfirmModel:D,launchConfirmResumeId:z,launchConfirmSavedSessions:he,launchConfirmTextFilter:je,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:V,launchConfirmResumableOnly:re,launchConfirmSortMode:me,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:ce,launchConfirmBusy:pe,resolvedWorkspacePath:P,canCreateMissingWorkspace:fe,openBrowseDialog:Pe,loadBrowsePath:Ie,handleWorkspaceChoiceChange:qe,chooseCustomWorkspacePath:We,setCustomWorkspacePath:d,setBrowseDialogOpen:h,setActiveLauncherKind:I,openLaunchConfirm:Fe,handleConfirmLaunch:pt,closeLaunchConfirm:Ke,setWorkspaceSelectionFromOption:Be,setLaunchConfirmWorkspaceKeyAndSync:lt,setLaunchConfirmArgs:T,setLaunchConfirmModel:W,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:ve,setLaunchConfirmWorkspaceFilter:ne,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:Z,setLaunchConfirmSortMode:se}}function Mm({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:o,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:m,section:f,showBottomNav:u,onBack:x,onSectionChange:w,onOpenConversation:C,onOpenRecent:L,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:k,onAddWorkspace:p,onBrowseDirectory:N,onLaunchWorkspaceProvider:R,onListSavedSessions:y}){const v=S=>S==="ide"?"IDE":S==="cli"?"CLI":"ACP",j=r.slice(0,4),g=s.slice(0,3),h=Am({selectedMachineEntry:e,cliProviders:n,acpProviders:o,machineAction:l,onBrowseDirectory:N,onListSavedSessions:y}),K=a.useMemo(()=>j.map(S=>{const{metaText:H,updatedLabel:q}=Di(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:H,updatedLabel:q,onClick:()=>{const{options:T,selectedKey:D}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspacePath:S.workspace});h.openLaunchConfirm({title:S.kind==="ide"?es("restart-ide",S.label):S.providerSessionId?ea(S.label):es("start-fresh",S.label),description:S.kind==="ide"?ts("restart-ide"):S.providerSessionId?ta():ts("start-fresh"),confirmLabel:S.kind==="ide"?Ns("restart-ide"):S.providerSessionId?_r(!0):Ns("start-fresh"),busyLabel:S.kind==="ide"?Ss("restart-ide"):S.providerSessionId?Jn(!0):Ss("start-fresh"),workspaceOptions:T,selectedWorkspaceKey:D,details:[{label:"Mode",value:v(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const W=T.find(z=>z.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(W),await L({...S,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[h,L,j]),I=a.useMemo(()=>g.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:rt(S.conversation),secondary:Ld(S.conversation,{timestampLabel:S.timestamp?Ko(S.timestamp):null}),unread:S.unread,onClick:()=>C(S.conversation)})),[C,g]),A=h.showAllRecent?K:K.slice(0,4),M=K.length>0,O=I.length>0,_=m?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${_} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Kn,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(S=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),M&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(S=>t.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:S.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:S.primary}),S.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),K.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.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:()=>h.setShowAllRecent(S=>!S),children:h.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(h.hasIdeOptions||n.length>0||o.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:h.workspaceChoice,onChange:S=>h.handleWorkspaceChoiceChange(S.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:h.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[h.workspaceRows.map(S=>t.jsxs("option",{value:S.id,children:[S.id===h.defaultWorkspaceId?"⭐ ":"",Or(S.path,S.label)||S.path]},S.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),h.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(vs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:h.resolvedWorkspacePath||h.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.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:h.openBrowseDialog,children:"Select workspace…"}),t.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:()=>{h.resolvedWorkspacePath&&p(h.resolvedWorkspacePath)},disabled:!h.resolvedWorkspacePath||h.browseBusy,children:"Save as workspace"})]})]}),h.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[h.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("cli"),children:"CLI"}),o.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${h.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:()=>h.setActiveLauncherKind("acp"),children:"ACP"})]}),h.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:h.activeLauncherKind==="ide"?"Choose an IDE":h.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:h.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(S=>t.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:H,selectedKey:q}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${S.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:H,selectedWorkspaceKey:q,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:S.name}]},async()=>{const T=H.find(D=>D.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(T),k(S.type,{workspacePath:(T==null?void 0:T.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:S.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},S.type)):(h.activeLauncherKind==="cli"?n:o).map(S=>t.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 H=h.activeLauncherKind==="cli"?"cli":"acp",{options:q,selectedKey:T}=ns({machine:{workspaces:h.workspaceRows,defaultWorkspaceId:h.defaultWorkspaceId},currentWorkspaceId:h.workspaceChoice!=="__custom__"?h.workspaceChoice:null,currentWorkspacePath:h.resolvedWorkspacePath});h.openLaunchConfirm({title:`Launch ${S.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${H.toUpperCase()}`,workspaceOptions:q,selectedWorkspaceKey:T,details:[{label:"Mode",value:H.toUpperCase()},{label:"Provider",value:S.displayName}],showArgsInput:!0,showModelInput:H==="acp",initialArgs:"",initialModel:"",providerType:S.type},async()=>{const D=q.find(W=>W.key===h.launchConfirmWorkspaceKeyRef.current);h.setWorkspaceSelectionFromOption(D),R(H,S.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:h.launchConfirmArgs,model:h.launchConfirmModel,resumeSessionId:h.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[S.icon?`${S.icon} `:"",S.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:h.resolvedWorkspacePath||"Use selected workspace"})]},S.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,h.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.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:()=>p(h.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.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:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.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:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),h.browseDialogOpen&&t.jsx(Gr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:h.browseCurrentPath,directories:h.browseDirectories,busy:h.browseBusy,error:h.browseError,confirmLabel:"Use this folder",onClose:()=>h.setBrowseDialogOpen(!1),onNavigate:S=>{h.loadBrowsePath(S)},onConfirm:S=>{h.chooseCustomWorkspacePath(S),h.setBrowseDialogOpen(!1)}}),h.launchConfirm&&t.jsx(la,{title:h.launchConfirm.title,description:h.launchConfirm.description,details:h.launchConfirm.details,workspaceOptions:h.launchConfirm.workspaceOptions,selectedWorkspaceKey:h.launchConfirmWorkspaceKey,onWorkspaceChange:h.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:h.launchConfirm.providerType?_r(!!h.launchConfirmResumeId):h.launchConfirm.confirmLabel,busyLabel:h.launchConfirm.providerType?void 0:h.launchConfirm.busyLabel,busy:h.launchConfirmBusy,showArgsInput:h.launchConfirm.showArgsInput,argsValue:h.launchConfirmArgs,onArgsChange:h.setLaunchConfirmArgs,showModelInput:h.launchConfirm.showModelInput,modelValue:h.launchConfirmModel,onModelChange:h.setLaunchConfirmModel,historyProviderNode:h.launchConfirm.providerType&&(h.launchConfirmSessionsLoading||h.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),h.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Zn()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:h.launchConfirmTextFilter,onChange:S=>h.setLaunchConfirmTextFilter(S.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmWorkspaceFilter,onChange:S=>h.setLaunchConfirmWorkspaceFilter(S.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:h.launchConfirmModelFilter,onChange:S=>h.setLaunchConfirmModelFilter(S.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),t.jsxs("select",{value:h.launchConfirmSortMode,onChange:S=>h.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:h.launchConfirmResumableOnly,onChange:S=>h.setLaunchConfirmResumableOnly(S.target.checked),disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:h.launchConfirmResumeId,onChange:S=>h.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:h.launchConfirmBusy||h.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Fd()}),h.filteredLaunchConfirmSavedSessions.map(S=>t.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.providerSessionId))]}),!h.launchConfirmSessionsLoading&&h.launchConfirmSavedSessions.length>0&&h.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),h.launchConfirmResumeId&&(()=>{const S=h.filteredLaunchConfirmSavedSessions.find(q=>q.providerSessionId===h.launchConfirmResumeId);if(!S)return null;const H=Pi(S);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:H.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:H.providerSessionId}),t.jsx("div",{className:"mt-1",children:H.metaLine}),H.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:H.updatedLabel}),H.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:H.preview})]})})()]}),onConfirm:h.handleConfirmLaunch,onCancel:h.closeLaunchConfirm}),u&&t.jsx(Ri,{section:f,onSectionChange:w})]})}function Ei(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Lm(e,s){if(!e)return[];const r=e.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:cs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,m,f,u;const o=Ys(n)?"cli":bs(n)?"acp":"ide",i=cs(n.summaryMetadata);return{id:`${o}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Ys(n)?n.cliName||n.type:bs(n)&&n.cliName||n.type),kind:o,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:bs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(f=(m=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:m.at)==null?void 0:f.call(m,-1))==null?void 0:u.timestamp)||0}}).sort((n,o)=>o.timestamp-n.timestamp).map(({timestamp:n,...o})=>o)}function _m(e,s){const r=new Map;for(const n of s){const o=qt(n.conversation),i=r.get(o);i?i.push(n):r.set(o,[n])}return e.map(n=>{const o=r.get(n.id)||[],i=[...o].sort((x,w)=>w.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Cn(n),m=o.filter(x=>x.unread||x.requiresAction).length,f=Ei(n),u=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:m,total:o.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?_d(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 xr(e,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] ${e}`,s)}catch{}}function Rm({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:o,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:m,onRequestedActiveTabConsumed:f,requestedMachineId:u,onRequestedMachineConsumed:x,requestedMobileSection:w,onRequestedMobileSectionConsumed:C,setSelectedTabKey:L,setScreen:d,setSelectedMachineId:b,setSection:k,setMachineBackTarget:p,resetMachineAction:N}){const R=a.useRef(null),y=a.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const j=Gs(v,c),g=Math.max(Date.now(),Gt(v),j.lastUpdated||0);xr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:rt(v),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Gt(v),readAt:g}),l(qt(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,seenAt:g}).then(h=>{xr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:h})}).catch(h=>{xr("mark_read:error",{tabKey:v.tabKey,sessionId:v.sessionId,error:h instanceof Error?h.message:String(h)})})},[c,l]);return a.useEffect(()=>{var j;if(!n){d("inbox"),L(((j=e[0])==null?void 0:j.tabKey)||null),R.current=null;return}if(i!=="chat"){R.current=null;return}const v=`${n.tabKey}:${n.sessionId||""}`;R.current!==v&&(R.current=v,y(n))},[e,y,i,n,d,L]),a.useEffect(()=>{if(!m)return;const v=e.find(j=>j.tabKey===m);v&&(L(v.tabKey),d("chat"),f==null||f())},[e,f,m,d,L]),a.useEffect(()=>{if(!u)return;const v=s.find(j=>j.id===u);v&&(b(v.id),N(),k("machines"),p("inbox"),d("machine"),x==null||x())},[s,x,u,N,p,d,k,b]),a.useEffect(()=>{w&&(k(w),d("inbox"),C==null||C())},[C,w,d,k]),a.useEffect(()=>{const v=r.filter(j=>j.inboxBucket==="task_complete"||j.unread);v.length!==0&&xr("inbox_state",{screen:i,selectedTabKey:o,items:v.map(j=>{const g=Gs(j.conversation,c);return{liveState:g,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:rt(j.conversation),serverBucket:g.inboxBucket,computedBucket:j.inboxBucket,serverUnread:g.unread,computedUnread:j.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:Gt(j.conversation)}})})},[r,c,i,o]),{markConversationRead:y}}function Pm(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function io(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Dm(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Em({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[o,i]=a.useState("idle"),[c,l]=a.useState(""),[m,f]=a.useState(null),u=a.useCallback(()=>{i("idle"),l(""),f(null)},[]),x=a.useCallback(async(p,N,R)=>{var y;try{i("loading"),l(`Launching ${N}…`);const v={ideType:N,enableCdp:!0};(y=R==null?void 0:R.workspacePath)!=null&&y.trim()&&(v.workspace=R.workspacePath.trim()),await e(p,"launch_ide",v),i("done"),l(`${N} launch requested`)}catch(v){i("error"),l(v instanceof Error?v.message:"Launch IDE failed"),console.error("Launch IDE failed",v)}},[e]),w=a.useCallback(async(p,N,R)=>{if(N.trim())try{i("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(p,"workspace_add",{path:N.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(R!=null&&R.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),C=a.useCallback(async p=>{var N,R,y,v,j,g;try{i("loading"),l("Starting daemon upgrade…");const h=await e(p,"daemon_upgrade",{});if((N=h==null?void 0:h.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((R=h==null?void 0:h.result)==null?void 0:R.version)||"latest"}.`);return}if((y=h==null?void 0:h.result)!=null&&y.upgraded||(v=h==null?void 0:h.result)!=null&&v.success){i("done"),l(`Upgrade to v${((j=h==null?void 0:h.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((g=h==null?void 0:h.result)==null?void 0:g.error)||"Upgrade failed")}catch(h){i("error"),l(h instanceof Error?h.message:"Upgrade failed")}},[e]),L=a.useCallback(async(p,N,R,y)=>{var g,h,K;const v=Date.now(),j={machineId:p,kind:N,providerType:R,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:v};try{i("loading"),l(`Launching ${R}…`),f(j);const I={cliType:R};(g=y==null?void 0:y.workspacePath)!=null&&g.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(I.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(h=y==null?void 0:y.args)!=null&&h.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(K=y==null?void 0:y.model)!=null&&K.trim()&&(I.initialModel=y.model.trim());const A=await e(p,"launch_cli",I),M=(A==null?void 0:A.result)||A,O=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(A!=null&&A.success&&O){f(null),i("done"),l(`${R} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(A!=null&&A.success){i("loading"),l(`${R} launch requested — waiting for session…`);return}f(null),i("error"),l((A==null?void 0:A.error)||(M==null?void 0:M.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(I){if(Dm(I)){i("loading"),l(`${R} launch requested — waiting for session…`);return}f(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${N.toUpperCase()} workspace`)}},[s,e]),d=a.useCallback(async(p,N)=>{try{const R=await e(p,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(R==null?void 0:R.result)??R;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),b=a.useCallback(async(p,N)=>Vr(e,p,N),[e]);a.useEffect(()=>{var y;if(!m)return;const p=io(m.workspacePath),N=r.find(v=>{var A,M,O,_;if(!v||v.type==="adhdev-daemon"||Pm(v.daemonId||v.id)!==m.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==m.kind||String(v.agentType||v.type||"")!==m.providerType)return!1;const K=String(v.providerSessionId||"");if(m.resumeSessionId&&K)return K===m.resumeSessionId;if(p){const S=io(v.workspace||v.runtimeWorkspaceLabel);return S?S===p:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((_=(O=(M=(A=v.activeChat)==null?void 0:A.messages)==null?void 0:M.at)==null?void 0:O.call(M,-1))==null?void 0:_.timestamp)||0)>=m.startedAt-5e3});if(!N)return;const R=typeof N.sessionId=="string"&&N.sessionId?N.sessionId:typeof N.instanceId=="string"&&N.instanceId?N.instanceId:(y=n.find(v=>v.routeId===N.id))==null?void 0:y.sessionId;R&&(f(null),i("done"),l(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(R)}`))},[n,r,s,m]),a.useEffect(()=>{if(!m)return;const p=window.setTimeout(()=>{f(N=>!N||N.startedAt!==m.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(p)},[m]);const k=a.useCallback(async(p,N)=>{if(N.kind==="ide"&&N.providerType){await x(p,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await L(p,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[x,L]);return{machineAction:{state:o,message:c},resetMachineAction:u,handleLaunchDetectedIde:x,handleAddWorkspace:w,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:L,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:k}}function $m({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:o,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:m,setMachineBackTarget:f}){const u=a.useCallback(k=>{i(k.tabKey),c("chat"),n(k)},[n,c,i]),x=a.useCallback(k=>{const p=e.find(N=>N.routeId===k.routeId&&N.streamSource==="native");p&&(i(p.tabKey),c("chat"),n(p))},[e,n,c,i]),w=a.useCallback(()=>{n(s),c("inbox")},[n,s,c]),C=a.useCallback((k,p="inbox")=>{l(k),o(),m("machines"),f(p),c("machine")},[o,f,c,m,l]),L=a.useCallback(k=>{const p=qt(k);p&&C(p,"chat")},[C]),d=a.useCallback(()=>{o(),c(r)},[r,o,c]),b=a.useCallback(k=>{m(k),c("inbox")},[c,m]);return{openConversation:u,openNativeConversation:x,backFromConversation:w,openMachine:C,openConversationMachine:L,backFromMachine:d,changeMachineSection:b}}function Bm(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Wm(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function hr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Km({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:m,requestedActiveTabKey:f,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:w,requestedMobileSection:C,onRequestedMobileSectionConsumed:L,onOpenHistory:d,onOpenRemote:b,onStopCli:k,wsStatus:p,isConnected:N,onShowHiddenConversation:R,onShowAllHiddenConversations:y,onHideConversation:v,onOpenNewSession:j}){const[g,h]=a.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[K,I]=a.useState(()=>e[0]?"chat":"inbox"),[A,M]=a.useState("chats"),[O,_]=a.useState(null),[S,H]=a.useState("inbox"),q=Cs(),T="0.8.61",D=a.useMemo(()=>e.find(Y=>Y.tabKey===g)||e[0]||null,[e,g]),W=a.useMemo(()=>D?r.find(Y=>Y.id===D.routeId):void 0,[r,D]),z=a.useMemo(()=>!D||Ge(D)||!Xe(D)?null:js(D),[D]),X=a.useMemo(()=>r.filter(Y=>Y.type==="adhdev-daemon").sort(Fn),[r]),he=a.useMemo(()=>X.find(Y=>Y.id===O)||null,[X,O]),Te=a.useMemo(()=>Zs(r),[r]),je=Ur({sendDaemonCommand:o,activeConv:D||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ve=Em({sendDaemonCommand:o,navigate:q,ides:r,conversations:e}),te=a.useMemo(()=>e.map(Y=>{const ue=K==="chat"&&(D==null?void 0:D.tabKey)===Y.tabKey,Ie=qs(Y,Te,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ue}),Pe=Gt(Y),Be=si(Y);return{conversation:Y,timestamp:Pe,preview:Be,unread:Ie.unread,requiresAction:Ie.requiresAction,isWorking:Ie.isWorking,inboxBucket:Ie.inboxBucket}}),[e,Te,K,D]),{markConversationRead:ne}=Rm({conversations:e,machineEntries:X,items:te,selectedConversation:D,selectedTabKey:g,screen:K,liveSessionInboxState:Te,sendDaemonCommand:o,requestedActiveTabKey:f,onRequestedActiveTabConsumed:u,requestedMachineId:x,onRequestedMachineConsumed:w,requestedMobileSection:C,onRequestedMobileSectionConsumed:L,setSelectedTabKey:h,setScreen:I,setSelectedMachineId:_,setSection:M,setMachineBackTarget:H,resetMachineAction:ve.resetMachineAction}),V=$m({conversations:e,selectedConversation:D,machineBackTarget:S,markConversationRead:ne,resetMachineAction:ve.resetMachineAction,setSelectedTabKey:h,setScreen:I,setSelectedMachineId:_,setSection:M,setMachineBackTarget:H}),ie=a.useMemo(()=>hr(te.filter(Y=>Y.requiresAction)),[te]),re=a.useMemo(()=>hr(te.filter(Y=>Y.unread&&!Y.requiresAction)),[te]),Z=a.useMemo(()=>hr(te.filter(Y=>!Y.unread&&!Y.requiresAction&&Y.isWorking)),[te]),me=a.useMemo(()=>hr(te.filter(Y=>!Y.unread&&!Y.requiresAction&&!Y.isWorking)),[te]),se=a.useMemo(()=>he?te.filter(Y=>qt(Y.conversation)===he.id):[],[te,he]),ce=a.useMemo(()=>Lm(he,r),[r,he]),ee=(he==null?void 0:he.version)||null,pe=!!he&&!!ee&&!0&&ee!==T,ae=a.useMemo(()=>(he==null?void 0:he.availableProviders)||[],[he]),Se=a.useMemo(()=>ae.filter(Y=>Y.category==="cli"&&Y.installed!==!1).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[ae]),ge=a.useMemo(()=>ae.filter(Y=>Y.category==="acp"&&Y.installed!==!1).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[ae]),P=a.useMemo(()=>_m(X,te),[te,X]),fe=a.useCallback(async Y=>{he&&await ve.handleOpenRecent(he.id,Y)},[ve,he]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&D?t.jsx(ym,{selectedConversation:D,isAcp:Ge(D),isStandalone:l,selectedIdeEntry:W,actionLogs:n,userName:m,isSendingChat:je.isSendingChat,isFocusingAgent:je.isFocusingAgent,handleModalButton:je.handleModalButton,handleRelaunch:je.handleRelaunch,onBack:V.backFromConversation,onOpenNativeConversation:V.openNativeConversation,onOpenMachine:V.openConversationMachine,onHideConversation:v,onOpenHistory:d,onOpenRemote:b,onStopCli:k,cliViewMode:z,onSetCliViewMode:async Y=>{if(D&&z!==Y)try{await o(qt(D)||D.routeId,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:St(D),mode:Y})}catch(ue){Wm(ue)?console.warn("Skipped CLI view mode switch:",ue instanceof Error?ue.message:String(ue)):console.error("Failed to switch CLI view mode:",ue)}},handleSendChat:je.handleSendChat,handleFocusAgent:je.handleFocusAgent}):K==="machine"&&he?t.jsx(Mm,{selectedMachineEntry:he,selectedMachineConversations:se,selectedMachineRecentLaunches:ce,cliProviders:Se,acpProviders:ge,selectedMachineNeedsUpgrade:pe,appVersion:T,machineAction:ve.machineAction,isStandalone:l,section:A,showBottomNav:S==="inbox",onBack:V.backFromMachine,onSectionChange:V.changeMachineSection,onOpenConversation:V.openConversation,onOpenRecent:fe,onOpenMachineDetails:()=>q(`/machines/${he.id}`),onMachineUpgrade:()=>ve.handleMachineUpgrade(he.id),onLaunchDetectedIde:(Y,ue)=>ve.handleLaunchDetectedIde(he.id,Y,ue),onAddWorkspace:(Y,ue)=>ve.handleAddWorkspace(he.id,Y,ue),onBrowseDirectory:Y=>ve.handleBrowseDirectory(he.id,Y),onLaunchWorkspaceProvider:(Y,ue,Ie)=>ve.handleLaunchWorkspaceProvider(he.id,Y,ue,Ie),onListSavedSessions:Y=>ve.handleListSavedSessions(he.id,Y)}):t.jsx(wm,{section:A,attentionItems:ie,unreadItems:re,workingItems:Z,completedItems:me,hiddenConversations:s,machineCards:P,getAvatarText:Bm,onOpenConversation:V.openConversation,onShowConversation:R,onShowAllHidden:y,onOpenNewSession:j,onOpenMachine:V.openMachine,onOpenSettings:()=>q("/settings"),onSectionChange:M,wsStatus:p,isConnected:N,isStandalone:l})})}function mn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Om({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:o,onClearPreviewOrder:i}){const c=a.useRef(0),[l,m]=a.useState(!1),[f,u]=a.useState(null),x=a.useCallback(()=>{c.current=0,m(!1),u(null)},[]);a.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const w=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(),!mn(s,r)){u("merge");return}const k=b.currentTarget.getBoundingClientRect(),p=b.clientX-k.left,N=k.width/3;p<N?u("split-left"):p>N*2?u("split-right"):u("merge")},[s,r]),L=a.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),u(null))},[]),d=a.useCallback(b=>{c.current=0,m(!1);const k=b.dataTransfer.getData("text/tab-key"),p=k?e.some(R=>R.tabKey===k):!1,N=f;if(u(null),i(),!!k){if(b.preventDefault(),N==="split-left"&&mn(s,r)){r==null||r(k,"split-left");return}if(N==="split-right"&&mn(s,r)){r==null||r(k,"split-right");return}if(p){o(k);return}n==null||n(k)}},[e,f,s,r,n,o,i]);return{dragOver:l,dropAction:f,resetDragState:x,handleDragEnter:w,handleDragOver:C,handleDragLeave:L,handleDrop:d}}function Hm(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),o=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...o]}function Um({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:o}){const[i,c]=a.useState(s??null),[l,m]=a.useState(r??[]),[f,u]=a.useState(null),x=a.useRef(null),w=a.useRef(null),C=a.useRef(n),L=a.useRef(o);a.useEffect(()=>{C.current=n},[n]),a.useEffect(()=>{L.current=o},[o]),a.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),a.useEffect(()=>{m(j=>{const g=Hm(j,e);return g.length===j.length&&g.every((h,K)=>h===j[K])?j:g})},[e]);const d=a.useMemo(()=>{const j=f??l;if(j.length===0)return e;const g=new Map(j.map((h,K)=>[h,K]));return[...e].sort((h,K)=>{const I=g.get(h.tabKey)??999,A=g.get(K.tabKey)??999;return I-A})},[e,f,l]);a.useEffect(()=>{var g,h;if(d.length===0){i!==null&&(c(null),(g=C.current)==null||g.call(C,null));return}if(i&&d.some(K=>K.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(h=C.current)==null||h.call(C,j))},[d,i]);const b=a.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),k=a.useCallback(j=>{var g;c(j),(g=C.current)==null||g.call(C,j)},[]),p=a.useCallback((j,g,h)=>{m(K=>{var O;const I=K.filter(_=>_!==j),A=I.indexOf(g);if(A<0)return K;const M=h==="left"?A:A+1;return I.splice(M,0,j),(O=L.current)==null||O.call(L,I),I}),u(null)},[]),N=a.useCallback((j,g,h)=>{const I=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==j),A=I.indexOf(g);if(A<0)return;const M=h==="left"?A:A+1;I.splice(M,0,j),x.current=I,u(I)},[l,e]),R=a.useCallback(()=>{var g;const j=x.current;j&&(m(j),(g=L.current)==null||g.call(L,j))},[]),y=a.useCallback(()=>{x.current=null,u(null)},[]),v=a.useCallback(j=>{m(g=>{var K;const h=g.filter(I=>I!==j);return h.push(j),(K=L.current)==null||K.call(L,h),h})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:x,draggingTabRef:w,selectTab:k,handleTabReorder:p,updatePreviewOrder:N,commitPreviewOrder:R,clearPreviewOrder:y,moveTabToEnd:v,setDraggingTabKey:j=>{w.current=j}}}function zm({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="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:t.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"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.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"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="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:t.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 da({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:o=!1}){if(o)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),i&&t.jsx(_i,{}),i&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const $i="adhdev-tab-shortcuts";function Bi(){try{return JSON.parse(localStorage.getItem($i)||"{}")}catch{return{}}}function Wi({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=a.useState(()=>Bi()),[l,m]=a.useState(null),f=a.useCallback(x=>{const w=[];return x.metaKey&&w.push(o?"⌘":"Meta"),x.ctrlKey&&w.push("Ctrl"),x.altKey&&w.push(o?"⌥":"Alt"),x.shiftKey&&w.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(w.push(x.key.length===1?x.key.toUpperCase():x.key),w.join("+"))},[o]),u=a.useCallback(x=>{c(x);try{localStorage.setItem($i,JSON.stringify(x))}catch{}},[]);return a.useEffect(()=>{if(!e||!l)return;const x=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){m(null);return}const C=f(w);if(!C)return;const L={...i};for(const[d,b]of Object.entries(L))b===C&&delete L[d];L[l]=C,u(L),m(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,u,f]),a.useEffect(()=>{if(!e)return;const x=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[C,L]of Object.entries(i))if(s.includes(C)&&f(w)===L){w.preventDefault(),r(),n(C);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,f]),{isMac:o,tabShortcuts:i,shortcutListening:l,setShortcutListening:m,saveShortcuts:u}}const Fm=a.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:o,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:m,onSelectTab:f,onConversationActivated:u,onPreviewReorder:x,onReorderTab:w,onCommitPreviewOrder:C,onClearPreviewOrder:L,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:k,onOpenContextMenu:p,longPressTimer:N,isGroupActive:R}){const y=Ts(s),v=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",j=y.isReconnecting,g=a.useCallback(H=>{l.current=s.tabKey,b(s.tabKey),H.dataTransfer.setData("text/tab-key",s.tabKey),H.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),h=a.useCallback(()=>{l.current=null,b(null),C(),L(),d()},[l,b,C,L,d]),K=a.useCallback(H=>{const q=l.current;if(!(!q||q===s.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const T=H.currentTarget.getBoundingClientRect(),D=H.clientX<T.left+T.width/2?"left":"right";x(q,s.tabKey,D)}},[s.tabKey,l,x]),I=a.useCallback(H=>{H.preventDefault(),H.stopPropagation();const q=H.dataTransfer.getData("text/tab-key");if(q&&q!==s.tabKey){const T=H.currentTarget.getBoundingClientRect(),D=H.clientX<T.left+T.width/2?"left":"right";c.includes(q)?w(q,s.tabKey,D):k&&k(q)}L()},[s.tabKey,c,w,k,L]),A=a.useCallback(H=>{H.stopPropagation(),m(),f(s.tabKey),u(s)},[s,u,m,f]),M=a.useCallback(H=>{H.preventDefault(),p(H.clientX,H.clientY,s.tabKey)},[s.tabKey,p]),O=a.useCallback(H=>{const q=H.touches[0];N.current=setTimeout(()=>{p(q.clientX,q.clientY,s.tabKey)},600)},[s.tabKey,N,p]),_=a.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),S=["adhdev-dockview-tab",v,r&&"is-active",R&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:S,draggable:!0,onDragStart:g,onDragEnd:h,onDragOver:K,onDrop:I,onClick:A,onContextMenu:M,onTouchStart:O,onTouchEnd:_,onTouchMove:_,style:{cursor:"pointer",opacity:n?.4:void 0},children:[o&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:rt(s),children:rt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[Zt(s),t.jsx("span",{className:"connecting-dots"})]}):Zt(s)})]}),i&&t.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})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Vm({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:w,onDragTabKeyChange:C,onReceiveTab:L,onHideTab:d,isGroupActive:b,allowTabShortcuts:k=!0}){const[p,N]=a.useState(null),R=a.useRef(null),y=a.useRef(null),v=a.useMemo(()=>e.map(M=>M.tabKey),[e]);Js("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(p==null?void 0:p.tabKey)||null});const{isMac:j,tabShortcuts:g,shortcutListening:h,setShortcutListening:K,saveShortcuts:I}=Wi({enabled:k,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});a.useEffect(()=>{if(!p)return;const M=O=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(O.target)||N(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[p]),a.useEffect(()=>{const M=y.current;if(!M)return;const O=_=>{Math.abs(_.deltaY)<=Math.abs(_.deltaX)||(_.preventDefault(),M.scrollLeft+=_.deltaY)};return M.addEventListener("wheel",O,{passive:!1}),()=>M.removeEventListener("wheel",O)},[]);const A=a.useCallback((M,O,_)=>{N({x:M,y:O,tabKey:_})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(Fm,{conv:M,isActive:s===M.tabKey,isDraggedTab:o.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:k?g[M.tabKey]:void 0,conversationKeys:v,draggingTabRef:o,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:u,onClearPreviewOrder:x,onDragStateReset:w,onDragTabKeyChange:C,onReceiveTab:L,onOpenContextMenu:A,longPressTimer:R,isGroupActive:b},M.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),p&&t.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:p.x,top:p.y},children:[k&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:M=>{M.stopPropagation(),K(p.tabKey),N(null)},children:["⌨ ",g[p.tabKey]?`Change shortcut (${g[p.tabKey]})`:"Set shortcut"]}),g[p.tabKey]&&t.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={...g};delete M[p.tabKey],I(M),N(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[k&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.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(p.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&h&&t.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:()=>K(null),children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Gm({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,userName:f,groupIndex:u,onFocus:x,isSplitMode:w,numGroups:C,onMoveTab:L,onReceiveTab:d,style:b,onActiveTabChange:k,initialActiveTabId:p,initialTabOrder:N,onTabOrderChange:R,onHideTab:y,isFocused:v,allowTabShortcuts:j=!0}){const{sendCommand:g}=_t(),h=a.useRef(null),{activeTabId:K,activeConv:I,sortedConversations:A,draggingTabRef:M,selectTab:O,handleTabReorder:_,updatePreviewOrder:S,commitPreviewOrder:H,clearPreviewOrder:q,moveTabToEnd:T,setDraggingTabKey:D}=Um({conversations:e,initialActiveTabId:p,initialTabOrder:N,onActiveTabChange:k,onTabOrderChange:R}),W=Ur({sendDaemonCommand:o,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:z,dropAction:X,resetDragState:he,handleDragEnter:Te,handleDragOver:je,handleDragLeave:ve,handleDrop:te}=Om({conversations:e,numGroups:C,onMoveTab:L,onReceiveTab:d,onOwnTabDrop:T,onClearPreviewOrder:q}),ne=I&&!Ge(I)&&js(I)==="terminal",V=a.useMemo(()=>I?s.find(se=>se.id===I.routeId):void 0,[s,I]),ie=a.useMemo(()=>I?n.filter(se=>se.routeId===I.tabKey):[],[n,I]),re=a.useMemo(()=>Zs(s),[s]),Z=a.useMemo(()=>new Set(A.filter(se=>yl(se,re,{isOpenConversation:se.tabKey===K})).map(se=>se.tabKey)),[K,re,A]);Js("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:K,dragOver:z});const me=a.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,"focus_session",{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...b,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Vm,{conversations:A,activeTabId:K,groupIndex:u,numGroups:C,unreadTabKeys:Z,draggingTabRef:M,onFocus:x,onSelectTab:O,onConversationActivated:me,onPreviewReorder:S,onReorderTab:_,onCommitPreviewOrder:H,onClearPreviewOrder:q,onDragStateReset:he,onDragTabKeyChange:D,onMoveTab:L,onReceiveTab:d,onHideTab:y,isGroupActive:v??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Te,onDragOver:je,onDragLeave:ve,onDrop:te,children:[z&&t.jsx(zm,{dropAction:X,canSplit:!!(C<4&&L)}),I?t.jsx(ca,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ne,ideEntry:V,terminalRef:h,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,isSendingChat:W.isSendingChat,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:ie,userName:f,isInputActive:!w||!!v}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(da,{conversationsCount:e.length,isSplitMode:w,isStandalone:l,hasRegisteredMachines:m})})]})]})}function qm({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:o,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:u,isStandalone:x,hasRegisteredMachines:w,userName:C,focusedGroup:L,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:k,closeGroup:p,handleResizeStart:N,groupActiveTabIds:R,setGroupActiveTabIds:y,groupTabOrders:v,setGroupTabOrders:j,toggleHiddenTab:g,allowTabShortcuts:h=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:o.map((K,I)=>{const A=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(et.Fragment,{children:[s&&I>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:M=>N(I-1,M),onDoubleClick:()=>p(I),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Gm,{style:s?{flexBasis:A??`${100/r}%`,flexGrow:A?0:1,flexShrink:A?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:f,setActionLogs:u,isStandalone:x,hasRegisteredMachines:w,userName:C,groupIndex:I,isFocused:s&&L===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(M,O)=>{O==="left"&&I>0?b(M,I-1):O==="right"&&I<r-1?b(M,I+1):O==="split-left"&&r<4?k(M,I,"left"):O==="split-right"&&r<4&&k(M,I,"right")},onReceiveTab:M=>b(M,I),onActiveTabChange:M=>y(O=>(O[I]??null)===(M??null)?O:{...O,[I]:M}),initialActiveTabId:R[I],initialTabOrder:v[I],onTabOrderChange:M=>j(O=>{const _=O[I]||[];return _.length===M.length&&_.every((S,H)=>S===M[H])?O:{...O,[I]:M}}),onHideTab:g,allowTabShortcuts:h})]},I)})})}function Ki({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[o,i]=a.useState(null),[c,l]=a.useState(null);a.useEffect(()=>e?it.onScreenshot("ide-page",(u,x)=>{if(u!==e)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(x)}):void 0,[e]),a.useEffect(()=>{r!=="connected"&&i(null)},[r]),a.useEffect(()=>{var u;return e?((u=it.onStatus)==null?void 0:u.call(it,(x,w)=>{x===e&&w!=null&&w.screenshotUsage&&l(w.screenshotUsage)}))||(()=>{}):void 0},[e]),a.useEffect(()=>{i(null)},[e,s]),a.useEffect(()=>{const f=e?it.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const m=a.useCallback(async(f,u)=>{const x=e?it.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,u,s)},[e,r,s]);return{connScreenshot:o,screenshotUsage:c,handleRemoteAction:m}}const Oi="adhdev-dashboard-action-shortcuts",Ym=1200,Xm={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Qm(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Je(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Hi(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Je("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Je("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Je("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Je("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Je("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Je("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Je("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:Je("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:Je("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:Je("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Je("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Je("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Je("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Je("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Je("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Je("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Je("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Je("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Je("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Je("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Je("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Je("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Je("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Je("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Je("toggleCliView",e)}]}function Dn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Dr(e){const s=Object.fromEntries(Hi(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Oi)||"{}"),n={...s,...r};for(const[o,i]of Object.entries(Xm))n[o]===i&&(n[o]=s[o]);return n}catch{return s}}function Ui(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Jm({enabled:e=!0,onTrigger:s}){const r=Qm(),[n,o]=a.useState(()=>Dr(r)),[i,c]=a.useState(null),[l,m]=a.useState([]),f=a.useRef({parts:[],timer:null}),u=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(Ui(d.key)),b.join("+"))},[r]),x=a.useCallback(d=>{o(d);try{localStorage.setItem(Oi,JSON.stringify(d))}catch{}},[]);a.useEffect(()=>{const d=Dr(r),b=Object.entries(n),k=Object.entries(d);b.length===k.length&&b.every(([p,N])=>d[p]===N)||x(d)},[n,r,x]);const w=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}},Ym))},[]);a.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const k=u(b);if(!k)return;const N=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(k);if(l.length===0&&N){m([k]);return}const y=[...l,k].slice(0,2).join(" "),v={...n};for(const[j,g]of Object.entries(v))g===y&&delete v[j];v[i]=y,x(v),c(null),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,u,x,i,l]),a.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const k=u(b);if(!k)return;const p=b.metaKey||b.ctrlKey||b.altKey;if(Dn(b.target)&&!p)return;const N=f.current.parts,R=p?[k]:[...N.slice(-1),k].slice(-2),y=R.join(" "),v=R[R.length-1],j=Object.entries(n).filter(([,A])=>!!A),g=j.find(([,A])=>A===y);if(g){b.preventDefault(),w(),s(g[0]);return}if(j.some(([,A])=>A.startsWith(`${y} `))){b.preventDefault(),f.current.parts=R,C();return}const K=j.find(([,A])=>A===v);if(K){b.preventDefault(),w(),s(K[0]);return}if(j.some(([,A])=>A.startsWith(`${v} `))){b.preventDefault(),f.current.parts=[v],C();return}w()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,C,e,u,s,w,i]),a.useEffect(()=>()=>w(),[w]);const L=a.useMemo(()=>Hi(r),[r]);return{isMac:r,actionDefinitions:L,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:x}}const zi=a.createContext(null);function qr(){const e=a.useContext(zi);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Sr(e){return rt(e)||e.tabKey}function Zm(e){return`remote:${e}`}function Ft(e){return e.startsWith("remote:")}function co(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pn(e){var r,n,o,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(o=e==null?void 0:e.documentElement)==null?void 0:o.focus)==null||i.call(o),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,m;try{s.focus(),(m=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||m.call(l)}catch{}})}catch{}}function br(e,s){e.classList.remove(kn.className,Nn.className),e.classList.add(s==="light"?kn.className:Nn.className)}function lo(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function ep(e){const[,s]=a.useState(0);a.useEffect(()=>{const r=()=>s(o=>o+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const o of n)o.dispose()}},[e.api,e.containerApi])}function tp(e,s,r){var l;const n=[s];let o;for(const m of n){let f;for(const u of m){const x=e.addPanel({id:u.tabKey,component:"conversation",title:Sr(u),params:{kind:"conversation",tabKey:u.tabKey},...f?{position:{referencePanel:f,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});f||(f=x.id)}o=f??o}const i=r??((l=s[0])==null?void 0:l.tabKey)??null;if(!i)return;const c=e.getPanel(i);c&&c.group.model.openPanel(c)}function uo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Ft(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const o=e.getPanel(n.tabKey);if(o){o.update({params:{tabKey:n.tabKey}}),o.title!==Sr(n)&&o.api.setTitle(Sr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Sr(n),params:{kind:"conversation",tabKey:n.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function mo(e,s,r){var m,f;const n=r?Zm(r):null;for(const u of[...e.panels])Ft(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const o=Bt(s,r);if(!o&&e.totalPanels===0)return;const i=e.getPanel(n),c=ai(o);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(o==null?void 0:o.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((f=e.panels.find(u=>!Ft(u.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function sp({params:e,api:s}){var x;const r=qr(),n=a.useRef(null),[o,i]=a.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Ur({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});a.useEffect(()=>{i(s.isActive);const w=[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 w)C.dispose()}},[s]);const m=a.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),f=a.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(da,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const u=!Ge(c)&&js(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ca,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:m,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:o})})}function rp({params:e}){var m;const s=qr(),r=a.useMemo(()=>Bt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=a.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),o=(r==null?void 0:r.daemonId)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Ki({doId:o,targetSessionId:r?Yn(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(Wo,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.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 np(){const e=qr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(da,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function ap(e){var C,L;ep(e);const s=qr(),r=a.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,k=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${k?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const o=((L=e.api.group.activePanel)==null?void 0:L.id)===e.api.id,i=e.api.isGroupActive,c=qs(n,s.liveSessionInboxState,{isOpenConversation:o}),l=c.isReconnecting,m=c.isConnecting,f=c.isGenerating,u=c.isWaiting,x=c.unread,w=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${o?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:rt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var b;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((b=d.target)==null?void 0:b.ownerDocument)??document})},children:[x&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:rt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Zt(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Zt(n)}):t.jsx("span",{children:Zt(n)})})]}),w&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function op({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:o,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,initialDataLoaded:f,userName:u,toggleHiddenTab:x,actionShortcuts:w,registerActionHandlers:C,onActiveTabChange:L,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:k,scrollToBottomRequest:p}){var ut,yt,Q;const{theme:N}=na(),{sendCommand:R}=_t(),y=a.useRef(null),v=a.useRef(null),j=a.useRef(!1),g=a.useRef(!1),h=a.useRef(!1),K=a.useRef(null),I=a.useRef([]),[A,M]=a.useState(null),[O,_]=a.useState(!1),[S,H]=a.useState(!1),[q,T]=a.useState(0),D=a.useRef(null),W=a.useMemo(()=>Ti(typeof window<"u"?window.innerWidth:1280),[]),z=a.useRef(typeof window>"u"?{}:om(W)),X=a.useMemo(()=>new Map(e.map(E=>[E.tabKey,E])),[e]),he=a.useMemo(()=>Zs(r),[r]),Te=a.useMemo(()=>{const E=y.current;return E?E.groups.some(B=>{try{const F=B.model.location.type;return F!=="floating"&&F!=="popout"?!1:B.panels.some(U=>X.has(U.id))}catch{return!1}}):!1},[X,q,e]),je=a.useCallback(()=>{var E;(E=y.current)==null||E.focus()},[]),ve=a.useCallback(E=>{const B=document,F=E.document;for(const de of B.querySelectorAll('link[rel="stylesheet"]')){const De=F.createElement("link");De.rel="stylesheet",De.href=de.href,de.crossOrigin&&(De.crossOrigin=de.crossOrigin),F.head.appendChild(De)}for(const de of B.querySelectorAll("style")){const De=F.createElement("style");De.textContent=de.textContent,F.head.appendChild(De)}const U=[];for(const de of B.styleSheets)try{for(const De of de.cssRules)De instanceof CSSStyleRule&&(De.selectorText===":root"||De.selectorText==="html")&&U.push(De.cssText)}catch{}if(U.length>0){const de=F.createElement("style");de.textContent=U.join(`
|
|
44
|
+
`),F.head.appendChild(de)}const oe=B.documentElement.getAttribute("data-theme");oe&&F.documentElement.setAttribute("data-theme",oe),F.documentElement.style.colorScheme=oe==="light"?"light":"dark",F.body.className=B.body.className;const ke=B.documentElement.getAttribute("style");ke&&F.documentElement.setAttribute("style",ke);const G=F.getElementById("dv-popout-window");G instanceof HTMLElement&&(G.classList.add("adhdev-dockview"),br(G,N))},[N]),te=a.useCallback(()=>{var B;const E=y.current;if(E)for(const F of E.groups)try{const U=(B=F.element)==null?void 0:B.ownerDocument;if(!U||U===document)continue;const oe=U.getElementById("dv-popout-window");oe instanceof HTMLElement&&(oe.classList.add("adhdev-dockview"),br(oe,N));const ke=document.documentElement.getAttribute("data-theme");ke&&U.documentElement.setAttribute("data-theme",ke),U.documentElement.style.colorScheme=ke==="light"?"light":"dark",U.body.className=document.body.className;const G=document.documentElement.getAttribute("style");G?U.documentElement.setAttribute("style",G):U.documentElement.removeAttribute("style")}catch{}},[N]),ne=a.useCallback(()=>{var B;const E=y.current;if(E)for(const F of E.groups)try{const U=(B=F.element)==null?void 0:B.ownerDocument;if(!U||U===document)continue;const oe=U.getElementById("dv-popout-window");if(!(oe instanceof HTMLElement))continue;oe.classList.add("adhdev-dockview"),br(oe,N),oe.classList.toggle("is-showing-dockview-overlay",S),oe.classList.toggle("is-dragging-dockview",O)}catch{}},[O,S,N]),V=a.useCallback(E=>{const B=y.current;if(!B)return;const F=B.getPanel(E);F&&B.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:U})=>{ve(U),ae();const oe=X.get(E);U.document.title=oe?`${rt(oe)} — ADHDev`:"ADHDev — Popout"}})},[X,ve]),ie=a.useCallback(E=>{const B=y.current,F=B==null?void 0:B.getPanel(E);if(!B||!F)return;const U=B.groups.filter(oe=>{var ke;try{return((ke=oe.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});U.length>0?F.api.moveTo({group:U[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),re=a.useCallback(E=>{var U;const B=y.current;if(!B)return!1;const F=B.getPanel(E);if(!F)return!1;try{return((U=F.group.element)==null?void 0:U.ownerDocument)!==document}catch{return!1}},[]),Z=a.useCallback(E=>{re(E)&&ie(E),x(E)},[re,ie,x]),me=a.useCallback(E=>{const B=y.current,F=B==null?void 0:B.getPanel(E);!B||!F||B.addFloatingGroup(F,{width:600,height:500})},[]),se=a.useCallback(E=>{var F;const B=(F=y.current)==null?void 0:F.getPanel(E);if(!B)return!1;try{return B.group.model.location.type==="floating"}catch{return!1}},[]),ce=a.useCallback(()=>{var B,F;const E=(F=(B=y.current)==null?void 0:B.activePanel)==null?void 0:F.id;return!E||Ft(E)?null:X.has(E)?E:null},[X]),ee=a.useCallback(E=>{const B=y.current,F=B==null?void 0:B.getPanel(E);if(!B||!F)return;const U=B.groups.filter(oe=>{try{return oe.model.location.type==="grid"}catch{return!0}});U.length>0?F.api.moveTo({group:U[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),pe=a.useCallback(()=>{var ke;const E=y.current;if(!E)return;const F=E.groups.filter(G=>{var de;try{return((de=G.element)==null?void 0:de.ownerDocument)===document&&G.model.location.type==="grid"}catch{return!1}})[0]||null,U=[...E.panels];for(const G of U){const de=(ke=G.group.element)==null?void 0:ke.ownerDocument,De=G.group.model.location.type;de===document&&De==="grid"||(F&&F.id!==G.group.id?G.api.moveTo({group:F,position:"center"}):G.api.moveTo({position:"center"}))}const oe=E.activePanel;oe&&(oe.group.model.openPanel(oe),oe.api.setActive()),pn(document)},[]),ae=a.useCallback(()=>{var B,F;const E=y.current;if(E)for(const U of E.groups){const oe=(B=U.element)==null?void 0:B.ownerDocument;if(!oe||oe===document)continue;const ke=oe.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let G=null,de=oe.title||"ADHDev",De="Popout workspace";const Me=U.activePanel;if(Me)if(G=Me.id,Ft(Me.id)){const Ae=((F=Me.params)==null?void 0:F.routeId)||Me.id.slice(7),Le=Bt([...X.values()],Ae);de=ai(Le),De=Le!=null&&Le.machineName?`Remote view · ${Le.machineName}`:"Remote view"}else{const Ae=X.get(Me.id);de=Ae?rt(Ae):Me.title||Me.id,De=Ae?Zt(Ae):"Dockview panel"}oe.title=`${de} — ADHDev`;let Oe=oe.getElementById("adhdev-popout-header");Oe instanceof HTMLElement||(Oe=oe.createElement("div"),Oe.id="adhdev-popout-header",oe.body.appendChild(Oe)),Oe.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Oe.innerHTML=`
|
|
45
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
46
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
47
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${co(de)}</div>
|
|
48
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${co(De)}</div>
|
|
49
|
+
</div>
|
|
50
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
51
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
52
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
53
|
+
</div>
|
|
54
|
+
`,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const Ve=Oe.querySelector("[data-adhdev-popout-focus]");Ve&&(Ve.onclick=()=>{window.focus()});const Ze=Oe.querySelector("[data-adhdev-popout-dock]");Ze&&(Ze.disabled=!G,Ze.style.opacity=G?"1":"0.5",Ze.style.cursor=G?"pointer":"default",Ze.onclick=()=>{var Ae;G&&ie(G),(Ae=oe.defaultView)==null||Ae.focus()})}},[X,ie]),Se=a.useCallback(E=>{var U;const B=y.current,F=B==null?void 0:B.getPanel(E);if(!(!B||!F)){F.group.model.openPanel(F),F.api.setActive();try{const oe=F.group.model.location;oe.type==="popout"?oe.getWindow().focus():pn((U=F.group.element)==null?void 0:U.ownerDocument)}catch{}}},[]),ge=a.useCallback(E=>{const B=y.current,F=B==null?void 0:B.activePanel,U=(B==null?void 0:B.activeGroup)||(F==null?void 0:F.group);if(!B||!F||!U)return;const oe=U.panels||[];if(oe.length<=1)return;const ke=oe.findIndex(De=>De.id===F.id);if(ke<0)return;const G=(ke+E+oe.length)%oe.length,de=oe[G];de&&(de.group.model.openPanel(de),de.api.setActive())},[]),P=a.useCallback(E=>{var Ze;const B=y.current,F=(B==null?void 0:B.activeGroup)||((Ze=B==null?void 0:B.activePanel)==null?void 0:Ze.group);if(!B||!F)return;const U=B.groups||[],oe=U.find(Ae=>Ae.id===F.id);if(!oe)return;const ke=oe.element.getBoundingClientRect(),G=ke.left+ke.width/2,de=ke.top+ke.height/2,De=(Ae,Le,mt,ht)=>Math.max(0,Math.min(Le,ht)-Math.max(Ae,mt)),Me=Ae=>{const Le=Ae.element.getBoundingClientRect(),mt=Le.left+Le.width/2,ht=Le.top+Le.height/2;let $=0,J=0,le=0,_e=!1;if(E==="left"?(_e=mt<G,$=Math.max(0,ke.left-Le.right),J=Math.abs(ht-de),le=De(ke.top,ke.bottom,Le.top,Le.bottom)):E==="right"?(_e=mt>G,$=Math.max(0,Le.left-ke.right),J=Math.abs(ht-de),le=De(ke.top,ke.bottom,Le.top,Le.bottom)):E==="above"?(_e=ht<de,$=Math.max(0,ke.top-Le.bottom),J=Math.abs(mt-G),le=De(ke.left,ke.right,Le.left,Le.right)):(_e=ht>de,$=Math.max(0,Le.top-ke.bottom),J=Math.abs(mt-G),le=De(ke.left,ke.right,Le.left,Le.right)),!_e)return Number.POSITIVE_INFINITY;const xe=le>0?0:120;return $*3+J+xe};let Oe=null,Ve=Number.POSITIVE_INFINITY;for(const Ae of U){if(Ae.id===oe.id)continue;const Le=Me(Ae);Number.isFinite(Le)&&(Le>=Ve||(Ve=Le,Oe=Ae))}return Oe||void 0},[]),fe=a.useCallback(E=>{var U;const B=P(E);if(!B)return;const F=B.activePanel||B.panels[0];F&&(B.model.openPanel(F),F.api.setActive(),pn((U=B.element)==null?void 0:U.ownerDocument))},[P]),Y=a.useCallback((E,B)=>{const F=y.current,U=F==null?void 0:F.activePanel,oe=(F==null?void 0:F.activeGroup)||(U==null?void 0:U.group);if(!F||!U||!oe)return;let ke=P(E);!ke&&(B!=null&&B.createGroupIfMissing)&&(ke=F.addGroup({referenceGroup:oe,direction:E})),ke&&(U.api.moveTo({group:ke,position:"center"}),U.group.model.openPanel(U),U.api.setActive())},[P]),{isMac:ue,tabShortcuts:Ie,shortcutListening:Pe,setShortcutListening:Be,saveShortcuts:qe}=Wi({sortedTabKeys:e.map(E=>E.tabKey),onFocus:je,onSelectTab:Se}),We=a.useCallback(()=>{var F;const E=y.current;if(!E)return;const B=E.activePanel;if(B){if(Ft(B.id)){const U=((F=B.params)==null?void 0:F.routeId)||B.id.slice(7),oe=Bt(e,U);oe!=null&&oe.tabKey&&Be(oe.tabKey);return}X.has(B.id)&&Be(B.id)}},[X,Se,Be,e]),Fe=a.useCallback(E=>{const B=[];return E.metaKey&&B.push(ue?"⌘":"Meta"),E.ctrlKey&&B.push("Ctrl"),E.altKey&&B.push(ue?"⌥":"Alt"),E.shiftKey&&E.key.length!==1&&B.push(ue?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(E.key)?null:(B.push(Ui(E.key)),B.join("+"))},[ue]),Ye=a.useCallback(E=>{var B,F;switch(E){case"splitActiveTabRight":Y("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Y("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const U=ce();U&&me(U);return}case"popoutActiveTab":{const U=ce();U&&V(U);return}case"dockActiveTab":{const U=ce();if(!U)return;re(U)?ie(U):se(U)&&ee(U);return}case"focusLeftPane":fe("left");return;case"focusRightPane":fe("right");return;case"focusUpPane":fe("above");return;case"focusDownPane":fe("below");return;case"moveActiveTabToLeftPane":Y("left");return;case"moveActiveTabToRightPane":Y("right");return;case"moveActiveTabToUpPane":Y("above");return;case"moveActiveTabToDownPane":Y("below");return;case"selectPreviousGroupTab":ge(-1);return;case"selectNextGroupTab":ge(1);return;case"setActiveTabShortcut":We();return;case"hideCurrentTab":{const U=(F=(B=y.current)==null?void 0:B.activePanel)==null?void 0:F.id;U&&!Ft(U)&&Z(U);return}default:return}},[ge,ee,fe,me,ce,Z,se,re,ie,Y,V,We]);a.useEffect(()=>{if(!A)return;const E=A.sourceDocument,B=E.defaultView??window,F=U=>{const oe=E.querySelector("[data-dockview-tab-context-menu]");oe&&oe.contains(U.target)||M(null)};return B.addEventListener("mousedown",F,!0),B!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{B.removeEventListener("mousedown",F,!0),B!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[A]);const pt=a.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:X,hasDetachedConversationPanels:Te,ides:r,isStandalone:l,hasRegisteredMachines:m,liveSessionInboxState:he,sendDaemonCommand:o,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:Z,userName:u,scrollToBottomRequest:p,tabShortcuts:Ie,openTabContextMenu:({x:E,y:B,tabKey:F,sourceDocument:U})=>M({x:E,y:B,tabKey:F,sourceDocument:U??document}),popoutTab:V,moveTabBackToMain:ie,isTabInPopout:re,floatTab:me,isTabFloating:se}),[n,s,X,Te,r,l,m,he,o,c,i,Z,u,p,Ie,V,ie,re,me,se]),Ke=a.useCallback(E=>{if(!E)return!1;const B=y.current;if(!B)return!1;const F=B.getPanel(E);return F?(F.group.model.openPanel(F),F.api.setActive(),k==null||k(),!0):!1},[k]),lt=a.useCallback(()=>{if(h.current)return!1;const E=Ke(K.current);return E&&(h.current=!0),E},[Ke]),nt=a.useCallback(()=>{var B;const E=y.current;E&&am(W,{activeTabId:((B=E.activePanel)==null?void 0:B.id)??null,layout:E.toJSON()})},[W]),He=a.useCallback(()=>{im(W,z.current)},[W]),at=a.useCallback(E=>{var U,oe,ke,G;const B=y.current;if(!B)return{kind:"grid"};const F=B.toJSON();for(const de of F.floatingGroups||[])if((oe=(U=de.data)==null?void 0:U.views)!=null&&oe.includes(E)&&de.position)return{kind:"floating",position:de.position};for(const de of F.popoutGroups||[])if((G=(ke=de.data)==null?void 0:ke.views)!=null&&G.includes(E))return{kind:"popout",position:de.position,popoutUrl:de.url};return{kind:"grid"}},[]),dt=a.useCallback(E=>{const B=y.current;if(!B)return;const F=B.getPanel(E),U=z.current[E];if(!F||!U||U.kind==="grid")return;if(F.group.model.location.type===U.kind){delete z.current[E],He();return}if(U.kind==="floating"){B.addFloatingGroup(F,{x:U.position.left??24,y:U.position.top??24,width:U.position.width,height:U.position.height}),delete z.current[E],He();return}delete z.current[E],He()},[He]);a.useEffect(()=>(C==null||C({setShortcutForActiveTab:We,restoreHiddenTabToSavedLocation:dt,resetAllPanelsToMain:pe,activatePreviousTabInGroup:()=>ge(-1),activateNextTabInGroup:()=>ge(1),floatActiveTab:()=>{const E=ce();E&&me(E)},popoutActiveTab:()=>{const E=ce();E&&V(E)},dockActiveTab:()=>{const E=ce();E&&(re(E)?ie(E):se(E)&&ee(E))},splitActiveTabRight:()=>Y("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Y("below",{createGroupIfMissing:!0}),focusLeftPane:()=>fe("left"),focusRightPane:()=>fe("right"),focusUpPane:()=>fe("above"),focusDownPane:()=>fe("below"),moveActiveTabToLeftPane:()=>Y("left"),moveActiveTabToRightPane:()=>Y("right"),moveActiveTabToUpPane:()=>Y("above"),moveActiveTabToDownPane:()=>Y("below")}),()=>C==null?void 0:C(null)),[ge,ee,me,fe,ce,se,re,Y,ie,V,C,pe,dt,We]);const be=a.useCallback(()=>{const E=v.current;if(!E)return;const B=E.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of B)F.setAttribute("data-adhdev-force-hidden","true")},[]),Ue=a.useCallback(()=>{const E=v.current;if(!E)return;const B=E.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of B)F.removeAttribute("data-adhdev-force-hidden")},[]),Qe=a.useCallback(()=>{const E=v.current;if(!E)return;const B=E.querySelectorAll(".dv-drop-target-container");for(const oe of B)oe.remove();const F=E.querySelectorAll(".dv-drop-target-dropzone");for(const oe of F)oe.remove();const U=E.querySelectorAll(".dv-drop-target");for(const oe of U)oe.classList.remove("dv-drop-target")},[]),ze=a.useCallback(()=>{_(!1),H(!1),Ue(),be(),Qe(),!(typeof window>"u")&&(D.current!=null&&window.clearTimeout(D.current),window.requestAnimationFrame(()=>{be(),Qe()}),D.current=window.setTimeout(()=>{be(),Qe(),D.current=null},80))},[Ue,be,Qe]),Rt=a.useCallback(E=>{var F;y.current=E.api;const B=nm(W);K.current=(B==null?void 0:B.activeTabId)??null,B!=null&&B.layout&&E.api.fromJSON(B.layout,{reuseExistingPanels:!1}),g.current=!!(B!=null&&B.layout)&&!f&&e.length===0,g.current||(uo(E.api,e),mo(E.api,e,b)),E.api.totalPanels===0&&e.length>0?tp(E.api,e,d):!g.current&&!Ke(d)&<(),j.current=!0,E.api.onDidActivePanelChange(U=>{var ke;if(K.current=(U==null?void 0:U.id)??null,h.current=!0,ae(),U&&Ft(U.id)){const G=((ke=U.params)==null?void 0:ke.routeId)||U.id.slice(7),de=Bt(e,G);L((de==null?void 0:de.tabKey)??null),nt();return}if(L((U==null?void 0:U.id)??null),nt(),!U)return;const oe=X.get(U.id);(oe==null?void 0:oe.streamSource)==="agent-stream"&&oe.agentType&&R(oe.routeId,"focus_session",{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})}),E.api.onDidLayoutChange(()=>{nt(),ae(),T(U=>U+1)}),E.api.onWillDragPanel(()=>{_(!0),H(!1),be()}),E.api.onWillDragGroup(()=>{_(!0),H(!1),be()}),E.api.onWillShowOverlay(()=>{Ue(),H(!0)}),E.api.onDidMovePanel(ze),E.api.onDidDrop(ze),E.api.onDidAddGroup(U=>{requestAnimationFrame(()=>{var oe,ke;try{const G=(oe=U.element)==null?void 0:oe.ownerDocument;if(!G||G===document)return;(ke=G.getElementById("dv-popout-window"))==null||ke.classList.add("adhdev-dockview");const de=document.documentElement.getAttribute("data-theme");de&&G.documentElement.setAttribute("data-theme",de),G.body.className=document.body.className;const De=document.documentElement.getAttribute("style");De&&G.documentElement.setAttribute("style",De)}catch{}ae(),T(G=>G+1)})}),L(((F=E.api.activePanel)==null?void 0:F.id)??null)},[Ke,ze,Ue,X,f,W,be,Qe,L,nt,d,b,R,ae,e]);a.useLayoutEffect(()=>{const E=y.current;if(!E||!j.current||g.current&&!f)return;g.current&&(g.current=!1);const B=I.current,F=new Set(B),U=e.map(Me=>Me.tabKey),oe=new Set(U);let ke=!1;for(const Me of B)oe.has(Me)||(z.current[Me]=at(Me),ke=!0);ke&&He(),uo(E,e),mo(E,e,b);const G=U.filter(Me=>!F.has(Me));let de=!1;for(const Me of G){const Oe=E.getPanel(Me),Ve=z.current[Me];if(!Oe||!Ve||Ve.kind==="grid")continue;if(Oe.group.model.location.type===Ve.kind){delete z.current[Me],de=!0;continue}if(Ve.kind==="floating"){E.addFloatingGroup(Oe,{x:Ve.position.left??24,y:Ve.position.top??24,width:Ve.position.width,height:Ve.position.height}),delete z.current[Me],de=!0;continue}}if(de&&He(),I.current=U,d&&Ke(d))return;!E.activePanel&&E.panels[0]&&(E.panels[0].group.model.openPanel(E.panels[0]),E.panels[0].api.setActive()),!!(E.activePanel&&E.getPanel(E.activePanel.id))||lt()},[Ke,lt,f,He,at,d,b,e]),a.useEffect(()=>{j.current&&Ke(d)},[Ke,d]),a.useEffect(()=>{if(!O||typeof window>"u")return;const E=()=>ze();return window.addEventListener("pointerup",E),window.addEventListener("mouseup",E),window.addEventListener("dragend",E),()=>{window.removeEventListener("pointerup",E),window.removeEventListener("mouseup",E),window.removeEventListener("dragend",E)}},[ze,O]),a.useEffect(()=>()=>{typeof window>"u"||D.current!=null&&window.clearTimeout(D.current)},[]),a.useEffect(()=>{const E=F=>{const U=F.target;if(!U)return;const oe=U.querySelector("[data-tab-key]")||U.closest("[data-tab-key]");if(oe){const ke=oe.getAttribute("data-tab-key");if(ke&&F.dataTransfer){const G=U.closest(".dv-tab")||oe.closest(".dv-tab")||oe;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",ke),G instanceof HTMLElement&&F.dataTransfer.setDragImage(G,Math.max(12,Math.round(G.clientWidth/2)),Math.max(10,Math.round(G.clientHeight/2)))}}};window.addEventListener("dragstart",E);const B=lo(y.current);for(const F of B)F.addEventListener("dragstart",E);return()=>{window.removeEventListener("dragstart",E);for(const F of B)F.removeEventListener("dragstart",E)}},[q]),a.useEffect(()=>{var B;const E=(B=v.current)==null?void 0:B.querySelector(".adhdev-dockview");E instanceof HTMLElement&&br(E,N),te(),ae(),ne()},[ae,ne,te,N]),a.useEffect(()=>{ae(),ne()},[ae,ne]),a.useEffect(()=>{const E=B=>{if(B.defaultPrevented||Pe)return;const F=Fe(B);if(!F)return;const U=B.metaKey||B.ctrlKey||B.altKey;Dn(B.target)&&!U||Dr(ue).setActiveTabShortcut!==F||(B.preventDefault(),B.stopPropagation(),We())};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[Fe,ue,Pe,We]),a.useEffect(()=>{const E=v.current;if(!E)return;const B=F=>{var de,De;if(!F.isTrusted)return;const U=(De=(de=F.target)==null?void 0:de.closest)==null?void 0:De.call(de,".dv-scrollable");if(!U)return;F.preventDefault(),F.stopPropagation();const oe=Math.abs(F.deltaX),ke=Math.abs(F.deltaY),G=oe>ke?F.deltaX:F.deltaY;U.dispatchEvent(new WheelEvent("wheel",{deltaY:G,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return E.addEventListener("wheel",B,{passive:!1,capture:!0}),()=>E.removeEventListener("wheel",B,{capture:!0})},[]),a.useEffect(()=>{const E=lo(y.current);if(E.length===0)return;const B=E.map(F=>{let U=[],oe=null;const ke=()=>{oe!=null&&F.clearTimeout(oe),oe=null,U=[]},G=()=>{oe!=null&&F.clearTimeout(oe),oe=F.setTimeout(()=>{oe=null,U=[]},1200)},de=Me=>{if(!Me.ctrlKey&&!Me.metaKey&&!Me.altKey)return;const Oe=Fe(Me);if(!Oe)return;const Ve=Bi();for(const[Ze,Ae]of Object.entries(Ve))if(e.some(Le=>Le.tabKey===Ze)&&Ae===Oe){Me.preventDefault(),Se(Ze);return}},De=Me=>{if(Me.defaultPrevented||Pe)return;const Oe=Fe(Me);if(!Oe)return;const Ve=Me.metaKey||Me.ctrlKey||Me.altKey;if(Dn(Me.target)&&!Ve)return;const Ze=Dr(ue),Ae=Object.entries(Ze).filter(([xe,Re])=>!!Re&&(xe==="splitActiveTabRight"||xe==="splitActiveTabDown"||xe==="floatActiveTab"||xe==="popoutActiveTab"||xe==="dockActiveTab"||xe==="focusLeftPane"||xe==="focusRightPane"||xe==="focusUpPane"||xe==="focusDownPane"||xe==="moveActiveTabToLeftPane"||xe==="moveActiveTabToRightPane"||xe==="moveActiveTabToUpPane"||xe==="moveActiveTabToDownPane"||xe==="selectPreviousGroupTab"||xe==="selectNextGroupTab"||xe==="setActiveTabShortcut"||xe==="hideCurrentTab")),Le=Ve?[Oe]:[...U.slice(-1),Oe].slice(-2),mt=Le.join(" "),ht=Le[Le.length-1],$=Ae.find(([,xe])=>xe===mt);if($){Me.preventDefault(),ke(),Ye($[0]);return}if(Ae.some(([,xe])=>xe.startsWith(`${mt} `))){Me.preventDefault(),U=Le,G();return}const le=Ae.find(([,xe])=>xe===ht);if(le){Me.preventDefault(),ke(),Ye(le[0]);return}if(Ae.some(([,xe])=>xe.startsWith(`${ht} `))){Me.preventDefault(),U=[ht],G();return}ke()};return F.addEventListener("keydown",de),F.addEventListener("keydown",De),()=>{ke(),F.removeEventListener("keydown",de),F.removeEventListener("keydown",De)}});return()=>{for(const F of B)F()}},[Fe,ue,q,Se,Pe,Ye,e]);const gt=N==="light"?kn:Nn,Tt=((Q=(yt=(ut=y.current)==null?void 0:ut.activePanel)==null?void 0:yt.group.element)==null?void 0:Q.ownerDocument)??document;return t.jsxs(zi.Provider,{value:pt,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(yc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${O?" is-dragging-dockview":""}${S?" is-showing-dockview-overlay":""}`,components:{conversation:sp,remote:rp},defaultTabComponent:ap,watermarkComponent:np,onReady:Rt,singleTabMode:"default",tabAnimation:"smooth",theme:gt,popoutUrl:"/popout.html"})}),A&&zs.createPortal(t.jsxs("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[180px]",style:{left:A.x,top:A.y},children:[re(A.tabKey)?t.jsxs(t.Fragment,{children:[se(A.tabKey)&&t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{ee(A.tabKey),M(null)},children:[t.jsx(Na,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Dock in window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:w.dockActiveTab||""})]}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{ie(A.tabKey),M(null)},children:[t.jsx(tl,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Move back to main window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:w.dockActiveTab||""})]})]}):se(A.tabKey)?t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{ee(A.tabKey),M(null)},children:[t.jsx(Na,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Dock back to grid"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:w.dockActiveTab||""})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{me(A.tabKey),M(null)},children:[t.jsx(rl,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Float as panel"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:w.floatActiveTab||""})]}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:()=>{V(A.tabKey),M(null)},children:[t.jsx(el,{size:13,className:"shrink-0 opacity-70"}),t.jsx("span",{className:"flex-1 min-w-0",children:"Open in new window"}),t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:w.popoutActiveTab||""})]})]}),t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2",onClick:E=>{E.stopPropagation(),Be(A.tabKey),M(null)},children:[t.jsx(sl,{size:13,className:"shrink-0 opacity-70"})," ",Ie[A.tabKey]?`Change shortcut (${Ie[A.tabKey]})`:"Set shortcut"]}),Ie[A.tabKey]&&t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{const E={...Ie};delete E[A.tabKey],qe(E),M(null)},children:[t.jsx(kt,{size:13,className:"shrink-0 opacity-70"})," Remove shortcut"]}),t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted flex items-center gap-2",onClick:()=>{Z(A.tabKey),M(null)},children:[t.jsx(Po,{size:13,className:"shrink-0 opacity-70"})," Hide tab"]})]}),A.sourceDocument.body),Pe&&zs.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Be(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ue?"⌘+1":"Ctrl+1",", ",ue?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Tt.body)]})}const Fi="adhdev-recent-launch-args-v1",ip=8;function cp(e){return String(e||"").trim().replace(/\s+/g," ")}function Vi(e,s){return`${e.trim()}::${s.trim()}`}function Gi(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Fi)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function lp(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Fi,JSON.stringify(e))}catch{}}function qi(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Gi().byKey[Vi(r,n)])==null?void 0:i.items)||[]}function Yi(e,s,r){var u;const n=String(e||"").trim(),o=String(s||"").trim(),i=cp(r);if(!n||!o||!i)return;const c=Gi(),l=Vi(n,o),m=((u=c.byKey[l])==null?void 0:u.items)||[],f=[i,...m.filter(x=>x!==i)].slice(0,ip);c.byKey[l]={items:f},lp(c)}function dp(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function ua(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";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 Xi(e){var o;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=ua((i==null?void 0:i.meta)||void 0),m=((o=i==null?void 0:i.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(m||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Qi(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ys(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function fn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function up(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function po(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function fo(e){if(!e)return"unknown";const s=Date.now()-e,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 mp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function pp(e){switch(e){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 fp(e){var r;const s=new Map;for(const n of e){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 xp({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:o,onOpenConversation:i,onClose:c}){var q;const[l,m]=a.useState(n||((q=e[0])==null?void 0:q.id)||null),[f,u]=a.useState(""),[x,w]=a.useState(null),[C,L]=a.useState(!1);a.useEffect(()=>{var T;m(n||((T=e[0])==null?void 0:T.id)||null)},[n,e]);const d=a.useMemo(()=>e.find(T=>T.id===l)||e[0]||null,[l,e]),b=a.useMemo(()=>r.filter(T=>{if(T.type==="adhdev-daemon"||T.transport!=="pty")return!1;const D=up(T.daemonId||T.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),k=Si(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),p=k.diagnostics,N=k.loading,R=k.applyDiagnostics,y=a.useMemo(()=>{const T=new Map;for(const D of b){const W=s.find(z=>z.sessionId===D.sessionId||z.routeId===D.id);D.sessionId&&W&&T.set(D.sessionId,W)}return T},[b,s]),v=a.useCallback(async()=>{if(d!=null&&d.id){L(!0);try{const T=await o(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=fn(T);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");R(D.diagnostics||D.result||null),u("")}catch(T){const D=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";u(D)}finally{L(!1)}}},[d==null?void 0:d.id,R,o]);a.useEffect(()=>{!(d!=null&&d.id)||p||N||C||v()},[d==null?void 0:d.id,p,N,v,C]);const j=a.useCallback(async(T,D)=>{if(!(d!=null&&d.id)||T==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
55
|
+
This will terminate the hosted runtime.`))return;const W=`${T}:${D.sessionId}`;w(W);try{const z=await o(d.id,T,{sessionId:D.sessionId}),X=fn(z);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const he=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${he}: ${D.displayName}`,"success"),await v()}catch(z){const X=z instanceof Error?z.message:"Session host action failed";u(X),st.showToast(X,"warning")}finally{w(z=>z===W?null:z)}},[d==null?void 0:d.id,v,o]),g=a.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
56
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){w("session_host_prune_duplicate_sessions");try{const D=await o(d.id,"session_host_prune_duplicate_sessions",{}),W=fn(D);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const z=W.result||{},X=Array.isArray(z.prunedSessionIds)?z.prunedSessionIds.length:0,he=typeof z.duplicateGroupCount=="number"?z.duplicateGroupCount:0;st.showToast(`Pruned ${X} duplicate runtime(s) across ${he} group(s)`,"success"),await v()}catch(D){const W=D instanceof Error?D.message:"Duplicate prune failed";u(W),st.showToast(W,"warning")}finally{w(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,v,o]),h=a.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((T,D)=>(D.lastActivityAt||0)-(T.lastActivityAt||0)),[p==null?void 0:p.sessions]),K=a.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:Xi(h),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,h]),I=K.liveRuntimes,A=K.recoverySnapshots,M=K.inactiveRecords,O=a.useMemo(()=>fp(I),[I]),_=a.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[p==null?void 0:p.recentLogs]),S=a.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-3).reverse(),[p==null?void 0:p.recentTransitions]),H=(T,D)=>{var V,ie;const W=y.get(T.sessionId),z=b.find(re=>re.sessionId===T.sessionId),X=x===`session_host_resume_session:${T.sessionId}`,he=x===`session_host_restart_session:${T.sessionId}`,Te=x===`session_host_stop_session:${T.sessionId}`,je=ua(T.meta),ve=typeof((V=T.meta)==null?void 0:V.runtimeRecoveryError)=="string"?String(T.meta.runtimeRecoveryError):"",te=D==="recovery"?"Recover":"Resume",ne=Qi(D);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:T.displayName||(z==null?void 0:z.runtimeDisplayName)||(z==null?void 0:z.cliName)||T.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${pp(T.lifecycle)}`,children:T.lifecycle}),je&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:je})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:T.workspaceLabel||(z==null?void 0:z.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ie=T.writeOwner)==null?void 0:ie.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:mp(T.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(On,{size:11})," ",T.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",fo(T.lastActivityAt),T.osPid?` · pid ${T.osPid}`:"",` · Next: ${ne}`]}),ve&&t.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:ve})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[W&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(W),c()},children:"Open chat"}),D==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_resume_session",T)},children:X?`${te}ing…`:te}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_restart_session",T)},children:he?"Restarting…":"Restart"}),D==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.lifecycle==="interrupted")&&t.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:!!x,onClick:()=>{j("session_host_stop_session",T)},children:Te?"Stopping…":"Stop"})]})]},T.sessionId)};return t.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:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:T=>T.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Ht,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.label)||"No machine selected"}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Live runtime status, next actions, and explicit recover/restart controls."})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.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:()=>{v()},disabled:N||C,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Is,{size:16})}),t.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 hosted runtime recovery",children:t.jsx(kt,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(T=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${T.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(T.id),children:T.label},T.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[f&&!p&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(is,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:f})]})]})}),p&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Live"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:p.runtimeCount})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:A.length})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),t.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:fo(p.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:po(p.hostStartedAt)})]})]}),_&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(is,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:_.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Br,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:x==="session_host_prune_duplicate_sessions",onClick:()=>{g()},children:x==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${O}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:ys("live")}),I.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:I.map(T=>H(T,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:ys("recovery")}),A.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:A.map(T=>H(T,"recovery"))})]}),M.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:ys("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:M.map(T=>H(T,"inactive"))})]}),S.length>0&&t.jsxs("div",{className:"pb-1",children:[t.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"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:S.map(T=>{const D=h.find(W=>W.sessionId===T.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(D==null?void 0:D.displayName)||T.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:po(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]})]})]})]})})}function Bs({title:e,description:s,action:r,children:n,className:o="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Ji({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:o,onOpenHistory:i,onClearSelection:c}){const l=n?Pi(n):null;return t.jsxs(Bs,{title:"Saved history",description:Zn(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:o,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:qd()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function xn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(o=>o.category==="cli"&&o.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(o=>o.category==="acp"&&o.installed!==!1)?"acp":null}function gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hp({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:o,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:m,sendDaemonCommand:f,onOpenConversation:u}){var ut,yt;const x=tr(),w=a.useMemo(()=>[...e].sort(Fn),[e]),[C,L]=a.useState(((ut=w[0])==null?void 0:ut.id)||""),d=a.useMemo(()=>w.find(Q=>Q.id===C)||w[0],[C,w]),b=a.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[d]),k=(d==null?void 0:d.defaultWorkspaceId)||null,[p,N]=a.useState(""),[R,y]=a.useState(""),[v,j]=a.useState(xn(w[0])),[g,h]=a.useState(""),[K,I]=a.useState(""),[A,M]=a.useState([]),[O,_]=a.useState(""),[S,H]=a.useState([]),[q,T]=a.useState(!1),[D,W]=a.useState(""),[z,X]=a.useState(!1),[he,Te]=a.useState(()=>bt()),[je,ve]=a.useState(!1),[te,ne]=a.useState(null),[V,ie]=a.useState(!1),[re,Z]=a.useState(""),[me,se]=a.useState(!1),[ce,ee]=a.useState(""),[pe,ae]=a.useState([]),[Se,ge]=a.useState(!1),[P,fe]=a.useState(""),[Y,ue]=a.useState(!1),Ie=a.useRef(null),Pe=a.useRef(0);a.useEffect(()=>{var Q;!C&&((Q=w[0])!=null&&Q.id)&&L(w[0].id)},[C,w]),a.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||x(d.id,{minFreshMs:3e4}).catch(()=>{})},[x,d]);const Be=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Q=>Q.category==="cli"&&Q.installed!==!1),[d]),qe=a.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(Q=>Q.category==="acp"&&Q.installed!==!1),[d]),We=a.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[d]),Fe=a.useMemo(()=>v==="cli"?Be.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):v==="acp"?qe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):We,[qe,v,Be,We]);a.useEffect(()=>{var E;if(!d)return;if(Ie.current!==d.id){Ie.current=d.id,N(k||((E=b[0])==null?void 0:E.id)||"__home__"),y(""),j(xn(d)),h(""),I(""),_(""),H([]),W(""),Te(bt()),Z("");return}N(B=>{var F;return B==="__custom__"||B==="__home__"||b.some(U=>U.id===B)?B:k||((F=b[0])==null?void 0:F.id)||"__home__"}),j(B=>B==="ide"&&We.length>0||B==="cli"&&Be.length>0||B==="acp"&&qe.length>0?B:xn(d))},[qe.length,Be.length,k,We.length,d,b]),a.useEffect(()=>{var Q;v&&(Fe.some(E=>E.id===g)||h(((Q=Fe[0])==null?void 0:Q.id)||""))},[v,Fe,g]);const Ye=a.useCallback(async(Q,E)=>{const B=Pe.current+1;return Pe.current=B,T(!0),W(""),m(Q,E).then(F=>{Pe.current===B&&H(F)}).catch(F=>{Pe.current===B&&(H([]),W(F instanceof Error?F.message:"Could not load saved sessions"))}).finally(()=>{Pe.current===B&&T(!1)})},[m]),pt=a.useCallback((Q,E)=>{M(qi(Q,E))},[]);a.useEffect(()=>{if(_(""),Te(bt()),!d||!g||v==="ide"?M([]):pt(d.id,g),v!=="cli"){H([]),W(""),T(!1);return}if(!d||!g){H([]),W(""),T(!1);return}Ye(d.id,g)},[v,pt,Ye,d,g]),a.useEffect(()=>{if(!O)return;const Q=S.find(E=>E.providerSessionId===O);Q!=null&&Q.canResume||_("")},[S,O]);const Ke=p==="__custom__"?R.trim():p==="__home__"?"":((yt=b.find(Q=>Q.id===p))==null?void 0:yt.path)||"",lt=a.useMemo(()=>d?r.filter(Q=>Q.id!==d.id&&Q.daemonId===d.id).map(Q=>Q.workspace):[],[r,d]),nt=a.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(Q=>Q.workspace),[d]),He=a.useCallback(Q=>{const E=String(Q.workspace||"").trim();if(!E)return;const B=b.find(F=>gr(F.path)===gr(E));if(B){N(B.id),y("");return}N("__custom__"),y(E)},[b]),at=a.useCallback(Q=>{const E=String(Q.workspace||"").trim();if(!E)return{workspaceId:null,workspacePath:null};const B=b.find(F=>gr(F.path)===gr(E));return B?{workspaceId:B.id,workspacePath:null}:{workspaceId:null,workspacePath:E}},[b]),dt=a.useMemo(()=>S.find(Q=>Q.providerSessionId===O)||null,[S,O]),be=a.useMemo(()=>{var E;if(v!=="cli"||!d||!g)return null;const Q=((E=Be.find(B=>B.type===g))==null?void 0:E.displayName)||g;return{routeId:d.id,daemonId:d.id,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:g,status:"idle",title:Q,messages:[],ideType:g,workspaceName:Ke,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${g}`,machineName:Ct(d,{fallbackId:d.id})}},[v,Be,Ke,d,O,g]),Ue=a.useCallback(()=>{var E;if(!d)return;N("__custom__"),se(!0),fe("");const Q=Fr(d.platform,zr(R.trim(),Ke,lt,nt,d.defaultWorkspacePath,(E=b.find(B=>B.id===k))==null?void 0:E.path,b.map(B=>B.path)));ge(!0),o(d.id,Q).then(B=>{ee(B.path),y(B.path),ae(B.directories)}).catch(B=>{fe(B instanceof Error?B.message:"Could not load folder")}).finally(()=>ge(!1))},[R,k,nt,lt,o,Ke,d,b]),Qe=a.useCallback(Q=>{d&&(ge(!0),fe(""),o(d.id,Q).then(E=>{ee(E.path),y(E.path),ae(E.directories)}).catch(E=>{fe(E instanceof Error?E.message:"Could not load folder")}).finally(()=>ge(!1)))},[o,d]),ze=a.useCallback(async()=>{if(!d||!Ke)return;ue(!0),Z("");const Q=await i(d.id,Ke);if(ue(!1),!Q.ok){Z(Q.error||"Could not save workspace");return}Z("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Ke,d]),Rt=a.useCallback(async()=>{if(!d||!v||!g)return;ie(!0),Z("");const Q=K.trim()?K.trim().split(/\s+/).filter(Boolean):[],E=v==="ide"?await c(d.id,g,{workspacePath:Ke||null}):await l(d.id,v,g,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Ke||null,resumeSessionId:v==="cli"&&O?O:null,cliArgs:Q});if(ie(!1),!E.ok){Z(E.error||"Could not start session");return}v!=="ide"&&K.trim()&&(Yi(d.id,g,K),pt(d.id,g)),n()},[v,K,pt,n,c,l,Ke,d,O,g,p]),gt=v?ci(v,v==="cli"&&!!O):"Start",Tt=v?li(v,v==="cli"&&!!O):"Starting…";return d?t.jsxs(t.Fragment,{children:[t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start or recover session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh, resume saved history, or recover a hosted runtime."})]}),t.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:t.jsx(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4",children:[t.jsx(Bs,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:Q=>L(Q.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:w.map(Q=>t.jsx("option",{value:Q.id,children:Ct(Q,{fallbackId:Q.id})},Q.id))})}),v==="cli"&&t.jsx(Bs,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:V||!d,onClick:()=>ve(!0),children:[t.jsx(Ht,{size:14}),Vd()]})}),t.jsxs(Bs,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:V,children:"Browse…"}),children:[t.jsxs("select",{value:p,onChange:Q=>{const E=Q.target.value;N(E),E==="__custom__"?Ue():Z("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(Q=>t.jsxs("option",{value:Q.id,children:[Q.id===k?"⭐ ":"",Or(Q.path,Q.label)||Q.path]},Q.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":Ke||"Select a workspace folder."}),p==="__custom__"&&Ke&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:V,children:[t.jsx(vs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ze,disabled:V||Y,children:Y?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Be.length>0},{id:"ide",label:"IDE",enabled:We.length>0},{id:"acp",label:"ACP",enabled:qe.length>0}].map(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${v===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(Q.id),disabled:!Q.enabled||V,children:Q.label},Q.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:v==="ide"?"Choose IDE":v==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Fe.map(Q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>h(Q.id),disabled:V,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),Fe.length===0&&t.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."})]})]}),v!=="ide"&&t.jsxs(Bs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:K,onChange:Q=>I(Q.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:V}),A.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:A.map(Q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>I(Q),disabled:V,title:Q,children:Q},Q))})]}),v==="cli"&&t.jsx(Ji,{busy:V,savedSessionsLoading:q,savedSessionsError:D,selectedSession:dt,onRefresh:()=>{!d||!g||Ye(d.id,g)},onOpenHistory:()=>{!d||!g||(X(!0),Ye(d.id,g))},onClearSelection:()=>_("")}),re&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:re})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-4 border-t border-border-subtle bg-bg-secondary",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:V,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Rt,disabled:V||!v||!g||p==="__custom__"&&!Ke,children:[t.jsx(Un,{size:14}),V?Tt:gt]})]})]})}),me&&t.jsx(Gr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ce,directories:pe,busy:Se,error:P,onClose:()=>se(!1),onNavigate:Qe,onConfirm:Q=>{y(Q),ee(Q),N("__custom__"),se(!1)}}),z&&be&&t.jsx(sa,{activeConv:be,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:S,isSavedSessionsLoading:q,isResumingSavedSessionId:te,savedHistoryFilters:he,onSavedHistoryFiltersChange:Te,onClose:()=>X(!1),onNewChat:()=>{_(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!g||Ye(d.id,g)},onResumeSavedSession:Q=>{if(!d||!g||te||!Q.canResume)return;const E=at(Q);_(Q.providerSessionId),He(Q),ne(Q.providerSessionId),X(!1),ie(!0),Z(""),l(d.id,"cli",g,{workspaceId:E.workspaceId,workspacePath:E.workspacePath,resumeSessionId:Q.providerSessionId}).then(B=>{if(!B.ok){Z(B.error||"Could not resume session");return}n()}).finally(()=>{ie(!1),ne(B=>B===Q.providerSessionId?null:B)})}}),je&&d&&t.jsx(xp,{machineCards:[{id:d.id,label:Ct(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Ei(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:f,onOpenConversation:Q=>{ve(!1),n(),u(Q)},onClose:()=>ve(!1)})]}):null}function bp(e){switch(e.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 gp(e){return e instanceof Error?e.message:String(e||"")}function yp(e){const s=gp(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function vp({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:o,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:m,activeCliViewMode:f,onSetActiveCliViewMode:u,mobileChatConversations:x,hiddenConversations:w,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:k,isStandalone:p,initialDataLoaded:N,userName:R,requestedMobileTabKey:y,onRequestedMobileTabConsumed:v,requestedMachineId:j,onRequestedMachineConsumed:g,requestedMobileSection:h,onRequestedMobileSectionConsumed:K,containerRef:I,isSplitMode:A,numGroups:M,groupSizes:O,groupedConvs:_,clearedTabs:S,focusedGroup:H,setFocusedGroup:q,moveTabToGroup:T,splitTabRelative:D,closeGroup:W,handleResizeStart:z,groupActiveTabIds:X,setGroupActiveTabIds:he,groupTabOrders:Te,setGroupTabOrders:je,toggleHiddenTab:ve,visibleConversations:te,requestedDesktopTabKey:ne,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:ie,onHideConversation:re,onShowHiddenConversation:Z,onShowAllHiddenConversations:me,scrollToBottomRequest:se,machineEntries:ce,onBrowseMachineDirectory:ee,onSaveMachineWorkspace:pe,onLaunchMachineIde:ae,onLaunchMachineProvider:Se,onListMachineSavedSessions:ge}){const P=et.useRef(null),[fe,Y]=et.useState(!1),[ue,Ie]=et.useState(!1),[Pe,Be]=et.useState(!1),[qe,We]=et.useState(!1),Fe=et.useCallback(G=>{var de;zs.flushSync(()=>{Z(G)}),(de=P.current)==null||de.restoreHiddenTabToSavedLocation(G.tabKey)},[Z]),[Ye,pt]=et.useState(!1),[Ke,lt]=et.useState("quickstart"),[nt,He]=et.useState("workspace"),at=!e&&!s,dt=et.useCallback(G=>{Y(G),G&&Ie(!1)},[]),be=et.useCallback(G=>{Ie(G),G&&Y(!1)},[]),Ue=et.useCallback(()=>{var de;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((de=P.current)==null||de.resetAllPanelsToMain(),Ie(!1))},[]),Qe=et.useCallback(()=>{lt(te.length===0?"quickstart":"shortcuts"),He("workspace"),Be(!0),Y(!1),Ie(!1)},[te.length]),ze=et.useCallback(async G=>{var Ve;if(!r)return;const de=(Ve=r.modalButtons)==null?void 0:Ve[G];if(!de)return;const De=Qs(r);if(!De)return;const Me=de.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Oe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Me);try{await d(De,"resolve_action",{button:de,action:Oe?"approve":"reject",buttonIndex:G,...gs(r)})}catch(Ze){yp(Ze)||console.error("[Shortcut approval] Failed:",Ze)}},[r,d]),{isMac:Rt,actionDefinitions:gt,actionShortcuts:Tt,shortcutListening:ut,shortcutListeningDraft:yt,setShortcutListening:Q,setShortcutListeningDraft:E,saveShortcuts:B}=Jm({enabled:at&&!Pe,onTrigger:G=>{var de,De,Me,Oe,Ve,Ze,Ae,Le,mt,ht,$,J,le,_e,xe,Re;if(G==="openShortcutHelp"){Qe();return}if(G==="hideCurrentTab"){r&&re(r);return}if(G==="toggleHiddenTabs"){be(!ue);return}if(G==="openHistoryForActiveTab"){r&&!Ge(r)&&c(r);return}if(G==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ge(r)&&l(r);return}if(G==="splitActiveTabRight"){(de=P.current)==null||de.splitActiveTabRight();return}if(G==="splitActiveTabDown"){(De=P.current)==null||De.splitActiveTabDown();return}if(G==="floatActiveTab"){(Me=P.current)==null||Me.floatActiveTab();return}if(G==="popoutActiveTab"){(Oe=P.current)==null||Oe.popoutActiveTab();return}if(G==="dockActiveTab"){(Ve=P.current)==null||Ve.dockActiveTab();return}if(G==="focusLeftPane"){(Ze=P.current)==null||Ze.focusLeftPane();return}if(G==="focusRightPane"){(Ae=P.current)==null||Ae.focusRightPane();return}if(G==="focusUpPane"){(Le=P.current)==null||Le.focusUpPane();return}if(G==="focusDownPane"){(mt=P.current)==null||mt.focusDownPane();return}if(G==="moveActiveTabToLeftPane"){(ht=P.current)==null||ht.moveActiveTabToLeftPane();return}if(G==="moveActiveTabToRightPane"){($=P.current)==null||$.moveActiveTabToRightPane();return}if(G==="moveActiveTabToUpPane"){(J=P.current)==null||J.moveActiveTabToUpPane();return}if(G==="moveActiveTabToDownPane"){(le=P.current)==null||le.moveActiveTabToDownPane();return}if(G==="triggerPrimaryApprovalAction"){ze(0);return}if(G==="triggerSecondaryApprovalAction"){ze(1);return}if(G==="triggerTertiaryApprovalAction"){ze(2);return}if(G==="setActiveTabShortcut"){(_e=P.current)==null||_e.setShortcutForActiveTab();return}if(G==="selectPreviousGroupTab"){(xe=P.current)==null||xe.activatePreviousTabInGroup();return}if(G==="selectNextGroupTab"){(Re=P.current)==null||Re.activateNextTabInGroup();return}!r||!Xe(r)||Ge(r)||G==="toggleCliView"&&u(f==="chat"?"terminal":"chat")}}),F=et.useCallback(()=>{Be(!1),Q(null),E([])},[Q,E]),U=et.useMemo(()=>nt==="all"?gt:gt.filter(G=>bp(G)===nt),[gt,nt]),oe=et.useCallback(()=>{const G=Object.fromEntries(gt.map(de=>[de.id,""]));B(G)},[gt,B]),ke=et.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const G=Object.fromEntries(gt.map(de=>[de.id,de.defaultShortcut]));B(G)},[gt,B]);return et.useEffect(()=>{const G=de=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?de.metaKey&&de.key.toLowerCase()==="w":de.ctrlKey&&de.key.toLowerCase()==="w")&&(de.preventDefault(),r&&re&&re(r))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[r,re]),et.useEffect(()=>{if(!Pe||ut)return;const G=de=>{de.key==="Escape"&&(de.preventDefault(),F())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[F,Pe,ut]),et.useEffect(()=>{if(!at){pt(!1);return}pt(!0);const G=window.setTimeout(()=>{pt(!1)},1e4);return()=>window.clearTimeout(G)},[at]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Od,{activeConv:r,agentCount:n.length,wsStatus:o,isConnected:i,conversations:te,hiddenConversations:w,onOpenHistory:c,onOpenConversation:Fe,onHideConversation:re,onShowConversation:Fe,onShowAllHidden:me,onResetPanelsToMain:Ue,inboxOpen:fe,onInboxOpenChange:dt,hiddenOpen:ue,onHiddenOpenChange:be,onOpenNewSession:s?void 0:()=>We(!0),actionShortcuts:Tt,onOpenRemote:()=>{!r||Xe(r)||Ge(r)||l(r)},onStopCli:m,activeCliViewMode:f,onSetCliViewMode:u}),e?t.jsx(Km,{conversations:x,hiddenConversations:w,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:k,isStandalone:p,userName:R,requestedActiveTabKey:y,onRequestedActiveTabConsumed:v,requestedMachineId:j,onRequestedMachineConsumed:g,requestedMobileSection:h,onRequestedMobileSectionConsumed:K,onOpenHistory:c,onOpenRemote:l,onStopCli:m,wsStatus:o,isConnected:i,onShowHiddenConversation:Fe,onShowAllHiddenConversations:me,onOpenNewSession:()=>We(!0)}):s?t.jsx(qm,{containerRef:I,isSplitMode:A,numGroups:M,groupSizes:O,groupedConvs:_,clearedTabs:S,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:k,isStandalone:p,hasRegisteredMachines:ce.length>0,userName:R,focusedGroup:H,setFocusedGroup:q,moveTabToGroup:T,splitTabRelative:D,closeGroup:W,handleResizeStart:z,groupActiveTabIds:X,setGroupActiveTabIds:he,groupTabOrders:Te,setGroupTabOrders:je,toggleHiddenTab:ve,allowTabShortcuts:!1}):t.jsx(op,{visibleConversations:te,clearedTabs:S,ides:C,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:k,isStandalone:p,hasRegisteredMachines:ce.length>0,initialDataLoaded:N,userName:R,toggleHiddenTab:ve,actionShortcuts:Tt,registerActionHandlers:G=>{P.current=G},onActiveTabChange:ie,requestedActiveTabKey:ne,onRequestedActiveTabConsumed:V,scrollToBottomRequest:se}),qe&&t.jsx(hp,{machines:ce,conversations:x,ides:C,onClose:()=>We(!1),onBrowseDirectory:ee,onSaveWorkspace:pe,onLaunchIde:ae,onLaunchProvider:Se,onListSavedSessions:ge,sendDaemonCommand:d,onOpenConversation:G=>{We(!1),Z(G),ie(G.tabKey)}}),Pe&&t.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:F,children:t.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:G=>G.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:F,"aria-label":"Close dashboard guide",children:t.jsx(kt,{size:14})})]}),t.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(G=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ke===G.id?"btn-primary":"btn-secondary"}`,onClick:()=>lt(G.id),children:G.label},G.id))}),Ke==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Rt?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ke==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]})]})]})]}),Ke==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.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(G=>t.jsx("button",{type:"button",className:`btn btn-sm ${nt===G.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(G.id),children:G.label},G.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:oe,children:"Disable all"}),t.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:ke,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:U.map(G=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${ut===G.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:G.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:G.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:G.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.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:ut===G.id?yt.length>0?`${yt.join(" ")} ...`:"Listening...":Tt[G.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Q(G.id),E([])},children:ut===G.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const de={...Tt};de[G.id]="",B(de)},children:"Disable"})]})]})},G.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Rt?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Qe,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 ${Ye?"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:[t.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:"?"}),Ye&&t.jsx("span",{children:"Guide"})]})]})}const hn=[{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 wp({onClose:e}){const[s,r]=a.useState(0),n=hn[s],o=s===hn.length-1;return t.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&&e()},children:[t.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:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(kt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:hn.map((i,c)=>t.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))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.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:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),o&&t.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 →"})]}),t.jsxs("div",{className:"flex justify-between items-center mt-6",children:[t.jsx("button",{onClick:e,className:"btn btn-secondary border-none",children:"Skip"}),t.jsx("button",{onClick:()=>o?e():r(i=>i+1),className:"btn btn-primary",children:o?"Get Started →":"Next →"})]})]}),t.jsx("style",{children:`
|
|
57
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
58
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
59
|
+
`})]})}function jp({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:o}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.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,l=i.status==="waiting_approval",m=i.status==="generating";return t.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:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.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 kp({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:o,preferredTabKey:i}){const[c,l]=a.useState(()=>i||"native"),m=a.useMemo(()=>ui(s),[s]),f=a.useMemo(()=>e?ra(e,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,m,r]),u=a.useMemo(()=>f.find(b=>b.streamSource==="native"),[f]),x=a.useMemo(()=>f.filter(b=>b.streamSource==="agent-stream"),[f]),w=a.useMemo(()=>e?Bt(f,e.id):null,[f,e]);a.useEffect(()=>{i&&l(i)},[i]),a.useEffect(()=>{if(i||!w)return;const b=w.streamSource==="native"?"native":w.tabKey;!b||c===b||c==="native"&&l(b)},[c,w,i]),a.useEffect(()=>{var b;c!=="native"&&(x.some(k=>k.tabKey===c)||l(((b=x[0])==null?void 0:b.tabKey)||"native"))},[c,x]),a.useEffect(()=>{c==="native"&&(u||x[0]&&l(x[0].tabKey))},[c,u,x]);const C=a.useMemo(()=>c==="native"&&u?u:x.find(b=>b.tabKey===c)||w||u||x[0],[c,u,w,x]),L=a.useMemo(()=>x.map(b=>({tabKey:b.tabKey,title:ni(b)||o,status:b.status})),[x,o]),d=a.useCallback(b=>{if(b)return f.find(k=>k.sessionId===b||k.routeId===b||k.tabKey===b)},[f]);return{activeChatTab:c,setActiveChatTab:l,activeConv:C,conversations:f,extensionTabs:L,hasExtensions:L.length>0,resolveConversationByTarget:d}}function Np({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:o,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:m,isStandalone:f,userName:u,onOpenHistory:x,onConversationChange:w,onClose:C}){const[L,d]=a.useState("split"),[b,k]=a.useState(()=>Ot(e)?"native":e.tabKey),p=a.useRef(null),N=a.useMemo(()=>s||r.find(T=>T.id===e.routeId),[e.routeId,s,r]),R=a.useMemo(()=>tt((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:y,extensionTabs:v,hasExtensions:j}=kp({ideData:N,allIdes:r,connectionStates:n,localUserMessages:i,ideName:R||"IDE",preferredTabKey:Ot(e)?void 0:e.tabKey}),g=a.useMemo(()=>N?Bt(y,N.id):null,[N,y]);a.useEffect(()=>{const T=p.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(p.current=D,!(T&&T.routeId===D.routeId&&T.tabKey===D.tabKey&&T.streamSource===D.streamSource)){if(Ot(e)){k("native");return}k(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),a.useEffect(()=>{if(b==="native"){if(y.some(T=>T.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&k(g.tabKey);return}if(!y.some(T=>T.tabKey===b)){if((g==null?void 0:g.streamSource)==="agent-stream"){k(g.tabKey);return}k("native")}},[y,b,g]);const h=a.useMemo(()=>b==="native"?y.find(T=>T.streamSource==="native")||e:y.find(T=>T.tabKey===b)||e,[e,y,b]),K=Ci(h),I=a.useMemo(()=>K.status||K.modalMessage||K.modalButtons?{...h,...K.status?{status:K.status}:{},...K.modalMessage!==void 0?{modalMessage:K.modalMessage}:{},...K.modalButtons!==void 0?{modalButtons:K.modalButtons}:{}}:h,[h,K]),A=Ar(I),M=Ur({sendDaemonCommand:c,activeConv:I,setLocalUserMessages:l,setActionLogs:m,isStandalone:f}),{connScreenshot:O,screenshotUsage:_,handleRemoteAction:S}=Ki({doId:A,targetSessionId:Yn(I),connState:I.connectionState||"new",viewMode:L}),H=a.useMemo(()=>o.filter(T=>T.routeId===I.tabKey),[o,I.tabKey]);a.useEffect(()=>{w==null||w(I)},[I,w]),a.useEffect(()=>{const T=D=>{D.key==="Escape"&&C()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[C]);const q=a.useCallback(T=>{T.stopPropagation()},[]);return t.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:t.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:q,children:[t.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:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.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:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(It,{size:16})}),t.jsx("span",{className:"truncate",children:Hr(h)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:C,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(T=>{const D=L===T;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${D?"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(T),title:T==="split"?"Split view":"Remote only",children:T==="split"?t.jsx(Oc,{size:15}):t.jsx(It,{size:15})},T)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>x(h),title:"Chat History",children:[t.jsx(Hn,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:C,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${L==="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:[L!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${L==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(jp,{hasExtensions:j,ideName:R||"IDE",activeChatTab:b,extensionTabs:v,onSelectTab:k}),t.jsx(Oo,{activeConv:I,onModalButton:M.handleModalButton}),t.jsx(An,{activeConv:I,ideEntry:N,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:H,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${L==="split"?"order-1 md:order-2":""}`,children:t.jsx(Wo,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:O,screenshotUsage:_,transportType:I.transport,onAction:S})})]})]})})}function Sp({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:o}){const i=Pd(e);return t.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-center justify-center p-4",children:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),t.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."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.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"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Cp({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:o,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:m,onNewHistoryChat:f,onSwitchHistorySession:u,onRefreshHistory:x,onResumeSavedHistorySession:w,remoteDialogConv:C,remoteDialogIdeEntry:L,connectionStates:d,actionLogs:b,localUserMessages:k,sendDaemonCommand:p,setLocalUserMessages:N,setActionLogs:R,isStandalone:y,userName:v,onOpenRemoteHistory:j,onRemoteConversationChange:g,onCloseRemoteDialog:h,cliStopDialogOpen:K,cliStopTargetConv:I,onCancelCliStop:A,onStopCliNow:M,onSaveCliAndStop:O,toasts:_,onDismissToast:S,onClickToast:H,showOnboarding:q,onCloseOnboarding:T}){var z;const[D,W]=et.useState(()=>bt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(sa,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:o,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:W,onClose:m,onNewChat:f,onSwitchSession:u,onRefreshHistory:x,onResumeSavedSession:w}),C&&t.jsx(Np,{activeConv:C,ideEntry:L,ides:r,connectionStates:d,actionLogs:b,localUserMessages:k,sendDaemonCommand:p,setLocalUserMessages:N,setActionLogs:R,isStandalone:y,userName:v,onOpenHistory:j,onConversationChange:g,onClose:h}),K&&I&&(Xe(I)||Ge(I))&&t.jsx(Sp,{activeConv:I,canSaveAndStop:Xe(I)&&!Ge(I)&&!!((z=I.resume)!=null&&z.supported),onCancel:A,onStopNow:M,onSaveAndStop:O}),t.jsx(di,{toasts:_,onDismiss:S,onClickToast:H}),q&&t.jsx(wp,{onClose:T})]})}function Ip({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:o,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Is,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=Ct(c,{fallbackId:c.id}),m=n[c.id],f=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),m==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):m==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):m==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(kt,{size:16})})]})}function Tp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ap(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Mp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Lp(){var ha,ba,ga,ya,va;const{sendCommand:e}=_t(),s=tr(),r=Wn(),n=Cs(),[o,i]=vc(),c=o.get("activeTab"),l=((ha=r.state)==null?void 0:ha.openRemoteForTabKey)||null,m=((ba=r.state)==null?void 0:ba.openMachineId)||null,f=((ga=r.state)==null?void 0:ga.mobileSection)||null,u=ei(),x=u.ides||[],w=u.initialLoaded??!0,{updateRouteChats:C,setToasts:L}=u,[d,b]=a.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),k=u.toasts||[],p=u.wsStatus||"connected",N=u.isConnected??!0,R=u.connectionStates||{},y=u.showReconnected||!1,{groupAssignments:v,setGroupAssignments:j,focusedGroup:g,setFocusedGroup:h,groupActiveTabIds:K,setGroupActiveTabIds:I,groupTabOrders:A,setGroupTabOrders:M,groupSizes:O,setGroupSizes:_,isMobile:S,hasHydratedStoredLayout:H,hydrateStoredLayout:q}=lm(),[T,D]=a.useState(!1),[W,z]=a.useState(!1),[X,he]=a.useState(null),[Te,je]=a.useState([]),[ve,te]=a.useState(!1),[ne,V]=a.useState(null),[ie]=a.useState(()=>Ni()),[re,Z]=a.useState([]),[me,se]=a.useState({}),[ce,ee]=a.useState({}),[pe,ae]=a.useState(null),[Se,ge]=a.useState(null),[P,fe]=a.useState(null),Y=a.useRef(null);Js("Dashboard",{ideCount:x.length,toastCount:k.length,focusedGroup:g,groupCount:Object.keys(v).length,localMessageTabs:Object.keys(me).length,actionLogCount:re.length});const ue=x.find(ye=>ye.type==="adhdev-daemon"),Ie=a.useMemo(()=>x.filter(ye=>ye.type==="adhdev-daemon").sort(Fn),[x]),Pe=!!ue;a.useEffect(()=>{!ue||!(!ue.detectedIdes||!ue.availableProviders||!ue.recentLaunches||!ue.workspaces)||s(ue.id,{minFreshMs:3e4}).catch(()=>{})},[ue,s]);const Be=(ue==null?void 0:ue.terminalBackend)||null,qe=ue?Ct(ue,{fallbackId:ue.id}):null,We=(ue==null?void 0:ue.id)||null,{hiddenTabs:Fe,hideTab:Ye,toggleTab:pt,showTab:Ke,showAllTabs:lt}=Hu(),{chatIdes:nt,conversations:He,visibleConversations:at,visibleTabKeys:dt,resolveConversationBySessionId:be,resolveConversationByTarget:Ue}=Xu({ides:x,connectionStates:R,localUserMessages:me,clearedTabs:ce,hiddenTabs:Fe}),Qe=a.useMemo(()=>Zs(x),[x]),ze=a.useRef(null),{containerRef:Rt,normalizedGroupAssignments:gt,numGroups:Tt,isSplitMode:ut,groupedConvs:yt,moveTabToGroup:Q,closeGroup:E,handleResizeStart:B,splitTabRelative:F}=bm({groupAssignments:v,setGroupAssignments:j,setFocusedGroup:h,setGroupActiveTabIds:I,setGroupTabOrders:M,groupSizes:O,setGroupSizes:_,isMobile:S,visibleConversations:at,visibleTabKeys:dt}),U=a.useMemo(()=>{var Ce,Ne;if(!S){if(pe){const we=He.find($e=>$e.tabKey===pe);if(we)return we}return at[0]}const ye=K[g];if(ye){const we=He.find($e=>$e.tabKey===ye);if(we)return we}return((Ce=yt[g])==null?void 0:Ce[0])||((Ne=yt[0])==null?void 0:Ne[0])},[pe,S,K,g,He,yt,at]);a.useEffect(()=>{if(S){ze.current=null;return}if(!(U!=null&&U.sessionId)){ze.current=null;return}const ye=`${U.tabKey}:${U.sessionId}`;if(ze.current===ye)return;const Ce=()=>{if(document.visibilityState!=="visible"||ze.current===ye)return;ze.current=ye;const Ne=Gs(U,Qe),we=Math.max(Date.now(),Gt(U),Ne.lastUpdated||0);e(U.daemonId||U.routeId,"mark_session_seen",{sessionId:U.sessionId,seenAt:we}).catch(()=>{})};if(document.visibilityState==="visible"){const Ne=setTimeout(Ce,1500),we=()=>{document.visibilityState!=="visible"&&clearTimeout(Ne)};return document.addEventListener("visibilitychange",we),()=>{clearTimeout(Ne),document.removeEventListener("visibilitychange",we)}}else{const Ne=()=>{document.visibilityState==="visible"&&(setTimeout(Ce,800),document.removeEventListener("visibilitychange",Ne))};return document.addEventListener("visibilitychange",Ne),()=>{document.removeEventListener("visibilitychange",Ne)}}},[U,S,Qe,e]);const{requestedDesktopTabKey:oe,requestedMobileTabKey:ke,consumeRequestedActiveTab:G}=Qu({isMobile:S,urlActiveTab:c,resolveConversationBySessionId:be,setSearchParams:i}),{remoteDialogConv:de,remoteDialogIdeEntry:De,remoteDialogActiveConv:Me,setRemoteDialogActiveConv:Oe,openRemoteDialog:Ve,closeRemoteDialog:Ze}=mm({isMobile:S,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:oe,conversations:He,ides:x,resolveConversationByTarget:Ue}),Ae=Me||de||U,Le=!!Ae&&Xe(Ae)&&!Ge(Ae),mt=a.useMemo(()=>{if(!Ae||!Le)return null;const ye=Ae.daemonId||Ae.routeId||"",Ce=St(Ae);return`${ye}:${Ce}`},[Ae,Le]),ht=a.useMemo(()=>at,[at]),$=S&&ie==="chat",J=a.useMemo(()=>He.filter(ye=>Fe.has(ye.tabKey)),[He,Fe]),le=a.useCallback(ye=>{const Ce=new URLSearchParams(o);Ce.set("activeTab",ye),i(Ce,{replace:!0})},[o,i]),_e=a.useCallback(async(ye,Ce)=>Vr(e,ye,Ce),[e]),xe=a.useCallback(async(ye,Ce)=>{if(!Ce.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ne=await e(ye,"workspace_add",{path:Ce.trim()});return Ne!=null&&Ne.success?{ok:!0}:{ok:!1,error:(Ne==null?void 0:Ne.error)||"Could not save workspace"}}catch(Ne){return{ok:!1,error:Ne instanceof Error?Ne.message:"Could not save workspace"}}},[e]),Re=a.useCallback(async(ye,Ce,Ne)=>{var we;try{const $e={ideType:Ce,enableCdp:!0};(we=Ne==null?void 0:Ne.workspacePath)!=null&&we.trim()&&($e.workspace=Ne.workspacePath.trim());const xt=await e(ye,"launch_ide",$e);return!(xt!=null&&xt.success)&&(xt==null?void 0:xt.success)!==void 0?{ok:!1,error:(xt==null?void 0:xt.error)||"Could not launch IDE"}:(fe({machineId:ye,kind:"ide",providerType:Ce,workspacePath:(Ne==null?void 0:Ne.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch($e){return{ok:!1,error:$e instanceof Error?$e.message:"Could not launch IDE"}}},[e]),ot=a.useCallback(async(ye,Ce,Ne,we)=>{var xt,Ms,us;const $e=Date.now();try{const Pt={cliType:Ne};(xt=we==null?void 0:we.workspacePath)!=null&&xt.trim()?Pt.dir=we.workspacePath.trim():we!=null&&we.workspaceId&&(Pt.workspaceId=we.workspaceId),(Ms=we==null?void 0:we.resumeSessionId)!=null&&Ms.trim()&&(Pt.resumeSessionId=we.resumeSessionId.trim()),Array.isArray(we==null?void 0:we.cliArgs)&&we.cliArgs.length>0&&(Pt.cliArgs=we.cliArgs),(us=we==null?void 0:we.initialModel)!=null&&us.trim()&&(Pt.initialModel=we.initialModel.trim());const vt=await e(ye,"launch_cli",Pt),Nt=(vt==null?void 0:vt.result)||vt,Ls=(Nt==null?void 0:Nt.sessionId)||(Nt==null?void 0:Nt.id);return vt!=null&&vt.success&&Ls?(le(Ls),{ok:!0}):vt!=null&&vt.success?(fe({machineId:ye,kind:Ce,providerType:Ne,workspacePath:(we==null?void 0:we.workspacePath)||null,resumeSessionId:(we==null?void 0:we.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||(Nt==null?void 0:Nt.error)||`Could not launch ${Ce.toUpperCase()} session`}}catch(Pt){return Ap(Pt)?(fe({machineId:ye,kind:Ce,providerType:Ne,workspacePath:(we==null?void 0:we.workspacePath)||null,resumeSessionId:(we==null?void 0:we.resumeSessionId)||null,startedAt:$e}),{ok:!0}):{ok:!1,error:Pt instanceof Error?Pt.message:`Could not launch ${Ce.toUpperCase()} session`}}},[le,e]),At=a.useCallback(async(ye,Ce)=>{if(!ye||!Ce)return[];try{const Ne=await e(ye,"list_saved_sessions",{providerType:Ce,kind:"cli",limit:30}),we=(Ne==null?void 0:Ne.result)??Ne;return Array.isArray(we==null?void 0:we.sessions)?we.sessions:[]}catch(Ne){return console.error("List saved sessions failed",Ne),[]}},[e]);a.useEffect(()=>{var we;if(!P)return;const ye=xo(P.workspacePath),Ce=x.find($e=>{var vt,Nt,Ls,wa;if(!$e||$e.type==="adhdev-daemon"||Tp($e.daemonId||$e.id)!==P.machineId||(Ys($e)?"cli":bs($e)?"acp":"ide")!==P.kind||String($e.agentType||$e.type||"")!==P.providerType)return!1;if(P.resumeSessionId)return String($e.providerSessionId||"")===P.resumeSessionId;if(ye){const Xr=xo($e.workspace||$e.runtimeWorkspaceLabel);return Xr?Xr===ye:!1}return Number($e.lastUpdated||$e._lastUpdate||$e.timestamp||((wa=(Ls=(Nt=(vt=$e.activeChat)==null?void 0:vt.messages)==null?void 0:Nt.at)==null?void 0:Ls.call(Nt,-1))==null?void 0:wa.timestamp)||0)>=P.startedAt-5e3});if(!Ce)return;const Ne=typeof Ce.sessionId=="string"&&Ce.sessionId?Ce.sessionId:typeof Ce.instanceId=="string"&&Ce.instanceId?Ce.instanceId:(we=He.find($e=>$e.routeId===Ce.id))==null?void 0:we.sessionId;Ne&&(fe(null),le(Ne))},[He,le,x,P]),a.useEffect(()=>{if(!P)return;const ye=window.setTimeout(()=>{fe(Ce=>!Ce||Ce.startedAt!==P.startedAt?Ce:null)},45e3);return()=>window.clearTimeout(ye)},[P]),Uu({visibleConversations:at,clearedTabs:ce,setClearedTabs:ee,setActionLogs:Z}),Ju({ides:x,sendDaemonCommand:e,setToasts:L,setLocalUserMessages:se,resolveConversationByTarget:Ue});const{isRefreshingHistory:ft,handleRefreshHistory:As}=Qa({sendDaemonCommand:e,activeConv:U,chats:(ya=x.find(ye=>ye.id===(U==null?void 0:U.routeId)))==null?void 0:ya.chats,updateRouteChats:C,setToasts:L,setLocalUserMessages:se,setClearedTabs:ee}),{isCreatingChat:Zi,isRefreshingHistory:ec,handleSwitchSession:tc,handleNewChat:sc,handleRefreshHistory:rc}=Qa({sendDaemonCommand:e,activeConv:Ae,chats:(va=x.find(ye=>ye.id===(Ae==null?void 0:Ae.routeId)))==null?void 0:va.chats,updateRouteChats:C,setToasts:L,setLocalUserMessages:se,setClearedTabs:ee}),Yr=a.useCallback(async()=>{if(!(!Ae||!Le||ve)){te(!0);try{const ye=Ae.daemonId||Ae.routeId,Ce=St(Ae),Ne=await e(ye,"list_saved_sessions",{agentType:Ce,providerType:Ce,kind:"cli",limit:50}),we=(Ne==null?void 0:Ne.result)??Ne;je(Array.isArray(we==null?void 0:we.sessions)?we.sessions:[])}catch(ye){console.error("Refresh saved sessions failed",ye),je([])}finally{te(!1)}}},[Ae,ve,Le,e]);a.useEffect(()=>{if(!T){Y.current=null;return}if(!Le){Y.current=null,je([]),te(!1);return}!mt||ve||Y.current!==mt&&(Y.current=mt,Yr())},[Yr,T,ve,Le,mt]);const nc=a.useCallback(async ye=>{if(!Ae||!Le||!ye.providerSessionId||!ye.workspace)return;const Ce=Ae.daemonId||Ae.routeId,Ne=St(Ae);try{V(ye.providerSessionId);const we=await e(Ce,"launch_cli",{cliType:Ne,dir:ye.workspace,resumeSessionId:ye.providerSessionId,initialModel:Fo(ye.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$e=(we==null?void 0:we.result)??we,xt=typeof($e==null?void 0:$e.sessionId)=="string"?$e.sessionId:typeof($e==null?void 0:$e.id)=="string"?$e.id:"";xt&&i(Ms=>{const us=new URLSearchParams(Ms);return us.set("activeTab",xt),us},{replace:!0}),D(!1)}catch(we){console.error("Resume saved session failed",we)}finally{V(null)}},[Ae,Le,e,i]);um({urlActiveTab:S&&!$?c:null,conversations:He,resolveConversationBySessionId:be,normalizedGroupAssignments:gt,hasHydratedStoredLayout:S&&!$?H:!0,hydrateStoredLayout:S&&!$?q:()=>{},setGroupActiveTabIds:I,setFocusedGroup:h,setSearchParams:i,historyModalOpen:T,activeConv:U,isRefreshingHistory:ft,ides:x,handleRefreshHistory:As});const ma=a.useCallback(async(ye,Ce)=>{const Ne=Ce||X||U;if(!Ne||!Xe(Ne)&&!Ge(Ne))return;const we=St(Ne),$e=Ne.routeId||Ne.daemonId||"";try{await e($e,"stop_cli",{cliType:we,targetSessionId:Ne.sessionId,mode:ye})}catch(xt){console.error("Stop CLI failed:",xt)}},[U,X,e]),ac=a.useCallback(async ye=>{const Ce=ye||U;!Ce||!Xe(Ce)&&!Ge(Ce)||(he(Ce),z(!0))},[U]),oc=a.useMemo(()=>!U||!Xe(U)||Ge(U)?null:js(U),[U]),ic=a.useCallback(async ye=>{if(!(!U||!Xe(U)||Ge(U)||js(U)===ye))try{await e(qt(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:St(U),mode:ye})}catch(Ne){Mp(Ne)?console.warn("Skipped CLI view mode switch:",Ne instanceof Error?Ne.message:String(Ne)):console.error("Failed to switch CLI view mode:",Ne)}},[U,e]),{versionMismatchDaemons:cc,hasRequiredVersionDaemons:pa,appVersion:lc,versionBannerDismissed:dc,setVersionBannerDismissed:uc,upgradingDaemons:mc,handleBannerUpgrade:pc}=gm({ides:x,sendDaemonCommand:e}),fa=a.useCallback(ye=>{ae(ye.tabKey),i(Ce=>{const Ne=new URLSearchParams(Ce),we=id(ye);return we?Ne.set("activeTab",we):Ne.delete("activeTab"),Ne},{replace:!0})},[i]),xa=a.useCallback(ye=>{Ke(ye.tabKey),fa(ye)},[fa,Ke]),fc=a.useCallback(ye=>{Ye(ye.tabKey)},[Ye]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Ed,{wsStatus:p,showReconnected:y}),t.jsx($d,{terminalBackend:Be,isStandalone:Pe,machineLabel:qe,machineKey:We}),(!dc||pa)&&t.jsx(Ip,{daemons:cc,targetVersion:lc,required:pa,upgradingDaemons:mc,onUpgrade:pc,onDismiss:()=>uc(!0)}),t.jsx(vp,{showMobileChatMode:$,isMobile:S,activeConv:U,chatIdes:nt,wsStatus:p,isConnected:N,onOpenHistory:ye=>{ye&&Oe(ye),D(!0)},onOpenRemote:Ve,onStopCli:ac,activeCliViewMode:oc,onSetActiveCliViewMode:ic,mobileChatConversations:ht,ides:x,actionLogs:re,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:Z,isStandalone:Pe,initialDataLoaded:w,userName:u.userName,requestedMobileTabKey:ke,onRequestedMobileTabConsumed:G,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:Rt,isSplitMode:ut,numGroups:Tt,groupSizes:O,groupedConvs:yt,clearedTabs:ce,focusedGroup:g,setFocusedGroup:h,moveTabToGroup:Q,splitTabRelative:F,closeGroup:E,handleResizeStart:B,groupActiveTabIds:K,setGroupActiveTabIds:I,groupTabOrders:A,setGroupTabOrders:M,toggleHiddenTab:pt,visibleConversations:at,hiddenConversations:J,requestedDesktopTabKey:oe,onRequestedDesktopTabConsumed:G,onDesktopActiveTabChange:ae,onHideConversation:fc,onShowHiddenConversation:xa,onShowAllHiddenConversations:lt,scrollToBottomRequest:Se,machineEntries:Ie,onBrowseMachineDirectory:_e,onSaveMachineWorkspace:xe,onLaunchMachineIde:Re,onLaunchMachineProvider:ot,onListMachineSavedSessions:At}),t.jsx("style",{children:`
|
|
60
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
+
`}),t.jsx(Cp,{historyModalOpen:T,historyTargetConv:Ae,ides:x,isHistoryCreatingChat:Zi,isHistoryRefreshingHistory:Le?!1:ec,savedHistorySessions:Te,isSavedHistoryLoading:ve,isResumingSavedHistorySessionId:ne,onCloseHistory:()=>D(!1),onNewHistoryChat:sc,onSwitchHistorySession:tc,onRefreshHistory:Le?Yr:rc,onResumeSavedHistorySession:nc,remoteDialogConv:de,remoteDialogIdeEntry:De,connectionStates:R,actionLogs:re,localUserMessages:me,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:Z,isStandalone:Pe,userName:u.userName,onOpenRemoteHistory:ye=>{ye&&Oe(ye),D(!0)},onRemoteConversationChange:Oe,onCloseRemoteDialog:Ze,cliStopDialogOpen:W,cliStopTargetConv:X,onCancelCliStop:()=>{z(!1),he(null)},onStopCliNow:async()=>{z(!1),await ma("hard",X),he(null)},onSaveCliAndStop:async()=>{z(!1),await ma("save",X),he(null)},toasts:k,onDismissToast:ye=>L(Ce=>Ce.filter(Ne=>Ne.id!==ye)),onClickToast:ye=>{if(ye.targetKey){const Ce=Ue(ye.targetKey);Ce&&(h(gt.get(Ce.tabKey)??0),xa(Ce),ge({tabKey:Ce.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function _p({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:o}){const[i,c]=a.useState([]),[l,m]=a.useState(null),[f,u]=a.useState(null),[x,w]=a.useState(!1),[C,L]=a.useState(null),[d,b]=a.useState(!1),[k,p]=a.useState(""),N=a.useRef(null),R=a.useCallback(T=>{N.current=T},[]),y=a.useCallback((T,D,W=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:T,message:D}]),setTimeout(()=>{var z;return(z=o.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),W&&st.showToast(D,T==="error"||T==="warn"?"warning":"success")},[o]),v=a.useCallback(T=>{const D=T instanceof Error?T.message:String(T||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),j=a.useCallback(async(T,D)=>{var W;if(!e||l)return!1;m(T),y("info",`Launching ${tt(T)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const z={ideType:T,enableCdp:!0};(W=D==null?void 0:D.workspace)!=null&&W.trim()?z.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",z);return y(X!=null&&X.success?"info":"error",X!=null&&X.success?`${tt(T)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(z){return y("error",`Launch error: ${z.message}`,!0),!1}finally{m(null)}},[e,l,y,r]),g=a.useCallback(async T=>{if(!e)return{success:!1};const{cliType:D,dir:W,workspaceId:z,useDefaultWorkspace:X,useHome:he,argsStr:Te,model:je,resumeSessionId:ve}=T;if(!D)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const te=Te?Te.split(/\s+/).filter(Boolean):void 0,ne=(W==null?void 0:W.trim())||(z?"(saved id)":X?"(default workspace)":he?"(home)":"");y("info",`Launching ${D}${ne?` in ${ne}`:""}${je?` (model: ${je})`:""}...`),u(D);try{const V={cliType:D,cliArgs:te,initialModel:je||void 0};W!=null&&W.trim()?V.dir=W.trim():z?V.workspaceId=z:X?V.useDefaultWorkspace=!0:he&&(V.useHome=!0),ve&&(V.resumeSessionId=ve);const ie=await r(e,"launch_cli",V),re=(ie==null?void 0:ie.result)||ie;return ie!=null&&ie.success?(y("info",`${D} launched`,!0),(re==null?void 0:re.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(re==null?void 0:re.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:re==null?void 0:re.sessionId}):(y("error",`Failed: ${(ie==null?void 0:ie.error)||(re==null?void 0:re.error)}`,!0),(ie==null?void 0:ie.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&L({cliType:D,argsStr:Te,model:je}),{success:!1,sessionId:re==null?void 0:re.sessionId})}catch(V){return v(V)?(y("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${V.message}`,!0),{success:!1})}finally{u(null)}},[e,y,v,r]),h=a.useCallback(async(T,D,W,z)=>e?T?D.trim()?g({cliType:T,dir:D,argsStr:W,model:z}):(L({cliType:T,argsStr:W,model:z}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,g]),K=a.useCallback(async(T,D,W)=>{if(e&&window.confirm(`Stop ${T}?
|
|
62
|
+
This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:T,dir:D,targetSessionId:W});z!=null&&z.success?y("info",`${T} stopped`,!0):y("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){y("error",`Stop failed: ${z.message}`,!0)}},[e,y,r]),I=a.useCallback(async T=>{try{await r(T.daemonId,"restart_ide",{ideType:T.type}),y("info",`${tt(T.type)} restart initiated`,!0)}catch(D){y("error",`Restart failed: ${D.message}`,!0)}},[y,r]),A=a.useCallback(async T=>{if(window.confirm(`Stop ${tt(T.type)}?
|
|
63
|
+
This will disconnect CDP and optionally kill the process.`))try{const D=await r(T.daemonId,"stop_ide",{ideType:T.type,killProcess:!0});D!=null&&D.success?y("info",`${tt(T.type)} stopped`,!0):y("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){y("error",`Stop failed: ${D.message}`,!0)}},[y,r]),M=a.useCallback(async()=>{if(e)try{const T=await r(e,"detect_ides",{});y("info",`Found ${((T==null?void 0:T.result)||[]).length} IDE(s)`,!0)}catch(T){y("error",`Detection failed: ${T.message}`,!0)}},[e,y,r]),O=a.useCallback(async T=>{if(!e||!T.trim())return!1;w(!0);try{const D=await r(e,"workspace_add",{path:T.trim()});return D!=null&&D.success?(y("info",`Workspace added: ${T.trim()}`),!0):(y("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return y("error",D.message),!1}finally{w(!1)}},[e,y,r]),_=a.useCallback(async T=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){w(!0);try{const D=await r(e,"workspace_remove",{id:T});D!=null&&D.success?y("info","Workspace removed",!0):y("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){y("error",D.message,!0)}finally{w(!1)}}},[e,y,r]),S=a.useCallback(async T=>{var D;if(e){w(!0);try{const W=await r(e,"workspace_set_default",T===null?{clear:!0}:{id:T});if(W!=null&&W.success){y("info",T?"Default workspace updated":"Default workspace cleared",!0);const z=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";z&&((D=N.current)==null||D.call(N,z))}else y("error",(W==null?void 0:W.error)||"workspace_set_default failed",!0)}catch(W){y("error",W.message,!0)}finally{w(!1)}}},[e,y,r]),H=a.useCallback(async T=>{var W;if(!e||!T.trim())return;const D=T.trim();w(!0);try{const z=await r(e,"workspace_set_default",{path:D});z!=null&&z.success?(y("info","Default workspace set from history"),(W=N.current)==null||W.call(N,D)):y("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){y("error",z.message)}finally{w(!1)}},[e,y,r]),q=a.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:k}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:k})}catch(T){y("warn",`Live nickname updated, but account sync failed: ${T.message}`)}y("info",`Nickname set to "${k||"(cleared)"}"`),b(!1)}catch(T){y("error",`Failed: ${T.message}`)}},[e,k,s,y,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:x,launchPick:C,setLaunchPick:L,editingNickname:d,setEditingNickname:b,nicknameInput:k,setNicknameInput:p,addLog:y,handleLaunchIde:j,runLaunchCliCore:g,handleLaunchCli:h,handleStopCli:K,handleRestartIde:I,handleStopIde:A,handleDetectIdes:M,handleWorkspaceAdd:O,handleWorkspaceRemove:_,handleWorkspaceSetDefault:S,handleWorkspaceResumePath:H,handleSaveNickname:q,setOnDefaultWorkspaceChanged:R}}function Rp({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:o,actions:i,sendDaemonCommand:c}){var I;const{workspaceBusy:l,handleWorkspaceAdd:m,handleWorkspaceRemove:f,handleWorkspaceSetDefault:u}=i,[x,w]=a.useState(!1),[C,L]=a.useState(""),[d,b]=a.useState([]),[k,p]=a.useState(!1),[N,R]=a.useState(""),y=a.useCallback(async A=>{p(!0),R("");try{const M=await Vr(c,e,A);L(M.path),b(M.directories)}catch(M){R(M instanceof Error?M.message:"Could not load folder")}finally{p(!1)}},[e,c]),v=a.useCallback(()=>{w(!0);const A=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...o.map(O=>O.workspace)],M=Fr(s.platform,zr(A,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));y(M)},[o,n,r,y,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,g=s.availableMem??s.freeMem??s.totalMem,h=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-g)/s.totalMem*100))):0,K=((I=s.loadavg)==null?void 0:I[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(ar,{icon:t.jsx(Do,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?kl(s.uptime):"Waiting…"}),t.jsx(ar,{icon:t.jsx(It,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(ar,{icon:t.jsx(Br,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(ar,{icon:t.jsx(zc,{size:16}),label:"ACPs",value:`${o.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(Aa,{value:j?Math.min(Math.round(K/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${K.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Aa,{value:h,max:100,label:"Memory",color:"#3b82f6",detail:j?`${en(s.totalMem-g)} / ${en(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${en(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(vs,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:A=>void u(A.target.value===""?null:A.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(A=>t.jsx("option",{value:A.id,children:A.label||A.path},A.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.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:l,onClick:v,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(A=>t.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:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[A.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Or(A.path,A.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:A.path,children:A.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(A.id),children:"Remove"})]},A.id))})]}),x&&t.jsx(Gr,{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:k,error:N,confirmLabel:"Add workspace",onClose:()=>w(!1),onNavigate:A=>{y(A)},onConfirm:A=>{(async()=>{if(!A)return;await m(A)&&w(!1)})()}})]})}function Pp(e){if(!e||typeof e!="object")return null;const s=e,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 Dp(e,s,r){const n=[];for(const[o,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(m=>m.type===o);n.push({type:o,displayName:(l==null?void 0:l.displayName)||o,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[o]||{}})}return n}function bn(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function ho(e){if(!e||typeof e!="object")return null;if(bn(e))return e;const s=e,r=s.result;return bn(r)?r:bn(s.sourceConfig)?s.sourceConfig:null}function Ep(e){const s=e.trim();return s||null}const bo=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],$p=[{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 Bp({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[o,i]=a.useState("config"),[c,l]=a.useState("codex-cli"),[m,f]=a.useState([]),[u,x]=a.useState(""),[w,C]=a.useState([]),[L,d]=a.useState(""),b=a.useRef(null),k=a.useRef(null),p=g=>{f(h=>h.includes(g)?h.filter(K=>K!==g):[...h,g])},N=()=>f([...bo]),R=()=>f([]);a.useEffect(()=>{var g;(g=b.current)==null||g.scrollIntoView({behavior:"smooth"})},[w]),a.useEffect(()=>()=>{k.current&&clearInterval(k.current)},[]);const y=a.useCallback(()=>{k.current&&clearInterval(k.current),k.current=setInterval(async()=>{try{const g=await r(e,"provider_auto_fix_status",{providerType:s.type});(g==null?void 0:g.running)===!1&&o==="running"&&(i("done"),C(h=>[...h,`
|
|
64
|
+
✅ Auto-fix completed!`]),k.current&&clearInterval(k.current))}catch{}},3e3)},[e,s.type,r,o]),v=async()=>{if(m.length!==0){i("running"),C(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),d("");try{const g=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...u?{comment:u}:{}});g!=null&&g.success&&(g!=null&&g.started||g!=null&&g.running)?(C(h=>[...h,"✅ Agent started. Monitoring progress..."]),y()):(i("error"),d((g==null?void 0:g.error)||"Failed to start auto-fix"))}catch(g){i("error"),d((g==null?void 0:g.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),C(g=>[...g,`
|
|
65
|
+
⚠️ Auto-fix cancelled.`]),i("done"),k.current&&clearInterval(k.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.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:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[o==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:$p.map(g=>t.jsxs("button",{onClick:()=>l(g.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===g.value?g.color+"66":"var(--border-subtle)",background:c===g.value?g.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===g.value?g.color:"var(--text-primary)"},children:g.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:g.desc})]},g.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:bo.map(g=>t.jsxs("button",{onClick:()=>p(g),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(g)?"#a78bfa":"var(--text-secondary)"},children:[m.includes(g)?"☑ ":"☐ ",g]},g))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:u,onChange:g=>x(g.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")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[w.map((g,h)=>t.jsx("div",{className:g.startsWith("✅")?"text-green-400":"",style:g.startsWith("❌")||g.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:g},h)),o==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),L&&t.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:L})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.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"]}),t.jsxs("div",{className:"flex gap-2",children:[o==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:v,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"&&t.jsx("button",{onClick:j,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(o==="done"||o==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),C([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Wp({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:o}){var y;const i=s.filter(v=>v.category==="ide"),[c,l]=a.useState(((y=i[0])==null?void 0:y.type)||""),[m,f]=a.useState(""),[u,x]=a.useState(""),[w,C]=a.useState(!1),[L,d]=a.useState(""),[b,k]=a.useState(!1),p=v=>{const j=v.toLowerCase().replace(/[^a-z0-9-]/g,"");f(j),(!u||u===N(m))&&x(N(j))},N=v=>v.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),R=async()=>{if(!(!m||!u||!c)){C(!0),d("");try{const v=await r(e,"provider_clone",{type:m,name:u,category:"ide",location:"user",cloneFrom:c});v!=null&&v.success||v!=null&&v.created?(k(!0),o==null||o(m)):d((v==null?void 0:v.error)||"Failed to create provider")}catch(v){d((v==null?void 0:v.message)||"Connection failed")}C(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"px-5 py-4 flex flex-col gap-4",children:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:m})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(v=>t.jsxs("button",{onClick:()=>l(v.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===v.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===v.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:v.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===v.type?"#a78bfa":"var(--text-secondary)"},children:v.displayName})]},v.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:m,onChange:v=>p(v.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"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",m||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange:v=>x(v.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"})]}),L&&t.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:L})]})}),t.jsx("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-end gap-2",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:R,disabled:!m||!u||w,className:"machine-btn",style:{background:m&&u?"rgba(34,197,94,0.12)":void 0,borderColor:m&&u?"rgba(34,197,94,0.3)":void 0,color:m&&u?"#86efac":void 0,opacity:!m||!u||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Kp({machineId:e,providers:s,sendDaemonCommand:r}){var I;const[n,o]=a.useState([]),[i,c]=a.useState(!1),[l,m]=a.useState(null),[f,u]=a.useState("all"),[x,w]=a.useState(null),[C,L]=a.useState(!1),[d,b]=a.useState(null),[k,p]=a.useState("normal"),[N,R]=a.useState(""),[y,v]=a.useState(!1),j=a.useCallback(async()=>{if(e)try{const A=await r(e,"get_provider_source_config",{}),M=ho(A);M&&(b(M),p(M.sourceMode),R(M.explicitProviderDir||""))}catch{}},[e,r]),g=a.useCallback(async()=>{if(e){c(!0);try{const A=await r(e,"get_provider_settings",{}),M=Pp(A);if(M){const O=Dp(M,s);O.sort((_,S)=>_.category.localeCompare(S.category)||_.displayName.localeCompare(S.displayName)),o(O)}}catch{}c(!1)}},[e,s,r]);a.useEffect(()=>{n.length===0&&g(),d||j()},[]);const h=async(A,M,O)=>{m(`${A}.${M}`),o(_=>_.map(S=>S.type===A?{...S,values:{...S.values,[M]:O}}:S));try{const _=await r(e,"set_provider_setting",{providerType:A,key:M,value:O});_!=null&&_.success||g()}catch{g()}m(null)},K=async()=>{v(!0);try{const A=await r(e,"set_provider_source_config",{providerSourceMode:k,providerDir:Ep(N)}),M=ho(A);M?(b(M),p(M.sourceMode),R(M.explicitProviderDir||"")):await j(),await g()}catch{await j()}v(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(A=>t.jsx("button",{onClick:()=>u(A),className:`machine-btn text-[10px] px-2 py-0.5 ${f===A?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.toUpperCase()},A))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>L(!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"}),t.jsx("button",{onClick:g,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:k,onChange:A=>p(A.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:N,onChange:A=>R(A.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void K(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(d==null?void 0:d.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(d==null?void 0:d.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((I=d==null?void 0:d.providerRoots)==null?void 0:I.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(A=>A.category===f).length>1&&(()=>{const A=n.filter(S=>S.category===f),M=new Map;for(const S of A)for(const H of S.schema){if(H.type!=="boolean")continue;const q=M.get(H.key),T=!!(S.values[H.key]??H.default);q?(q.onCount+=T?1:0,q.total+=1):M.set(H.key,{label:H.label||H.key,onCount:T?1:0,total:1})}const O=[...M.entries()].filter(([,S])=>S.total===A.length);if(O.length===0)return null;const _=async(S,H)=>{for(const q of A)await h(q.type,S,H)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",A.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([S,H])=>{const q=H.onCount===H.total,T=H.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:H.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",H.onCount,"/",H.total,")"]}),t.jsx("button",{onClick:()=>void _(S,!0),disabled:q,className:`machine-btn text-[9px] px-1.5 py-px ${q?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void _(S,!1),disabled:T,className:`machine-btn text-[9px] px-1.5 py-px ${T?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},S)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(A=>f==="all"||A.category===f).map(A=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:A.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:A.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:A.category==="acp"?"rgba(139,92,246,0.08)":A.category==="cli"?"rgba(59,130,246,0.08)":A.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:A.category==="acp"?"#a78bfa":A.category==="cli"?"#60a5fa":A.category==="ide"?"#86efac":"var(--status-warning)"},children:A.category}),A.category==="ide"&&t.jsx("button",{onClick:()=>w(s.find(M=>M.type===A.type)||{type:A.type,name:A.displayName,displayName:A.displayName,icon:A.icon,category:A.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"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:A.schema.map(M=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[M.label||M.key,l===`${A.type}.${M.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),M.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:M.description})]}),t.jsx("div",{className:"shrink-0",children:M.type==="boolean"?t.jsx("button",{onClick:()=>h(A.type,M.key,!(A.values[M.key]??M.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:A.values[M.key]??M.default?"#8b5cf6":"var(--border-subtle)"},children:t.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:A.values[M.key]??M.default?21:3}})}):M.type==="number"?t.jsx("input",{type:"number",value:Number(A.values[M.key]??M.default??0)||0,min:M.min,max:M.max,onChange:O=>{const _=parseInt(O.target.value)||0;M.min!==void 0&&_<M.min||M.max!==void 0&&_>M.max||h(A.type,M.key,_)},className:"machine-input w-20 text-center text-[11px]"}):M.type==="select"&&M.options?t.jsx("select",{value:String(A.values[M.key]??M.default??""),onChange:O=>h(A.type,M.key,O.target.value),className:"machine-input text-[11px]",children:M.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(A.values[M.key]??M.default??""),onBlur:O=>h(A.type,M.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},M.key))})]},A.type))}),x&&t.jsx(Bp,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>w(null)}),C&&t.jsx(Wp,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>L(!1),onCreated:()=>{L(!1),g()}})]})}const Op=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Hp({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Up(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function go(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function zp({machineId:e,sendDaemonCommand:s}){const[r,n]=a.useState([]),[o,i]=a.useState([]),[c,l]=a.useState([]),[m,f]=a.useState(0),[u,x]=a.useState(0),[w,C]=a.useState(!0),[L,d]=a.useState("debug"),[b,k]=a.useState("all"),p=a.useRef(null),N=a.useRef(!1),R=Up(o,b);return a.useEffect(()=>{if(!e||!w)return;const y=async()=>{try{const[j,g]=await Promise.all([s(e,"get_logs",{count:200,minLevel:L,since:m}),s(e,"get_debug_trace",Hp({count:120,since:u,category:b}))]),h=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(h==null?void 0:h.logs)&&h.logs.length>0){n(A=>[...A,...h.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const I=Math.max(...h.logs.map(A=>A.ts));f(I)}const K=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray(K==null?void 0:K.trace)){i(K.trace.slice(-120));const I=K.trace.reduce((A,M)=>Math.max(A,Number(M.ts||0)),u);I>u&&x(I)}}catch{}l(as.list({limit:120}))};y();const v=setInterval(y,3e3);return()=>clearInterval(v)},[e,w,m,u,L,b,s]),a.useEffect(()=>{if(w&&(r.length>0||o.length>0||c.length>0)){const y=N.current?"smooth":"instant";setTimeout(()=>{var v;(v=p.current)==null||v.scrollIntoView({behavior:y}),N.current=!0},50)}},[r.length,o.length,c.length,w]),a.useEffect(()=>{i([]),x(0)},[b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(y=>t.jsx("button",{onClick:()=>{d(y),n([]),f(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${L===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",R.length," web=",c.length]}),t.jsx("button",{onClick:()=>C(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),f(0),x(0),as.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((y,v)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:y.level==="error"?"#ef4444":y.level==="warn"?"var(--status-warning)":y.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(y.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:y.level==="error"?"ERR":y.level==="warn"?"WRN":y.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:y.message})]},`log-${v}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",b==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:Op.map(y=>t.jsx("button",{onClick:()=>k(y.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===y.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.label},y.value))})]}),R.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),R.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.level.toUpperCase()}),t.jsxs("span",{children:[y.category,".",y.stage]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:go(y.payload)})]},y.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.kind}),y.topic&&t.jsxs("span",{children:["topic=",y.topic]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:go(y.payload)})]},y.id))]})]}),t.jsx("div",{ref:p})]})}function gn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function yn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function yo(e){if(!e)return"unknown";const s=Date.now()-e,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 Fp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Vp(e){switch(e){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 Gp(e){var r;const s=new Map;for(const n of e){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 qp({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,o]=a.useState(""),[i,c]=a.useState(null),[l,m]=a.useState(!1),f=Si(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),u=f.diagnostics,x=f.loading,w=f.applyDiagnostics,C=a.useMemo(()=>dp({diagnostics:u,loading:x,refreshing:l,error:n}),[u,x,l,n]),L=a.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),d=a.useCallback(async()=>{if(e){m(!0);try{const I=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),A=gn(I);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");w(A.diagnostics||A.result||null),o("")}catch(I){const A=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";o(A)}finally{m(!1)}}},[w,e,r]);a.useEffect(()=>{!e||u||x||l||d()},[u,x,e,d,l]);const b=a.useCallback(async(I,A)=>{const M=`${I}:${A.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
|
|
66
|
+
This will terminate the hosted runtime.`))){c(M);try{const O=await r(e,I,{sessionId:A.sessionId}),_=gn(O);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Session host action failed");const S=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${S}: ${A.displayName}`,"success"),await d()}catch(O){const _=O instanceof Error?O.message:"Session host action failed";st.showToast(_,"warning"),o(_)}finally{c(O=>O===M?null:O)}}},[e,d,r]),k=a.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
67
|
+
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 A=await r(e,"session_host_prune_duplicate_sessions",{}),M=gn(A);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const O=M.result||{},_=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,S=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;st.showToast(`Pruned ${_} duplicate runtime(s) across ${S} group(s)`,"success"),await d()}catch(A){const M=A instanceof Error?A.message:"Duplicate prune failed";st.showToast(M,"warning"),o(M)}finally{c(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,d,r]),p=a.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,A)=>(A.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),N=a.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Xi(p),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,p]),R=N.liveRuntimes,y=N.recoverySnapshots,v=N.inactiveRecords,j=a.useMemo(()=>Gp(R),[R]),g=a.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),h=a.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(I,A)=>{var W;const M=i===`session_host_resume_session:${I.sessionId}`,O=i===`session_host_restart_session:${I.sessionId}`,_=i===`session_host_stop_session:${I.sessionId}`,S=ua(I.meta),H=L.get(I.sessionId),q=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,T=A==="recovery"?"Recover":"Resume",D=Qi(A);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(H==null?void 0:H.cliName)||I.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Vp(I.lifecycle)}`,children:I.lifecycle}),S&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(H==null?void 0:H.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((W=I.writeOwner)==null?void 0:W.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Fp(I.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(On,{size:11})," ",q]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",yo(I.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[A==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",I)},children:M?`${T}ing…`:T}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",I)},children:O?"Restarting…":"Restart"}),A==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&t.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:()=>{b("session_host_stop_session",I)},children:_?"Stopping…":"Stop"})]})]})},I.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Ht,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Gd()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${C.toneClass}`,children:C.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:x||l,children:[t.jsx(Is,{size:13}),x||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(is,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:yo(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:yn(u.hostStartedAt)})]})]}),h&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(is,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:h.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[yn(h.timestamp),h.sessionId?` · ${h.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Br,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ys("live")}),R.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:R.map(I=>K(I,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Ht,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ys("recovery")}),y.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:y.map(I=>K(I,"recovery"))})]}),v.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ys("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:v.map(I=>K(I,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),g.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:g.map(I=>{var M;const A=p.find(O=>O.sessionId===I.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(A==null?void 0:A.displayName)||((M=L.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:yn(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Yp({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:o}=r;return t.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:t.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-5",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.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:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.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"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function vn({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function wn({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function Xp({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:o,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),m=r.slice(0,4),u=Os(e,"0.8.61");return t.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:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(Ut,{size:13}),children:"Current Chats"}),t.jsx(wn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const w=Mn(x);return t.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(x),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:rt(x)}),w>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kr(w)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ls(x)})]},x.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(Do,{size:13}),children:"Recent Launches"}),t.jsx(wn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(x=>{const{metaText:w,updatedLabel:C}=Di(x);return t.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(x),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:x.label}),C&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:w})]},x.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(vn,{icon:t.jsx(is,{size:13}),children:"Daemon Update"}),t.jsx(wn,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.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:[t.jsx(Is,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Qp(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Jp(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Zp={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 yr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ef(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function jn({category:e,machine:s,machineId:r,providers:n,managedEntries:o,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:m,initialWorkspacePath:f}){const u=Cs(),{handleLaunchIde:x,handleStopCli:w,handleRestartIde:C,handleStopIde:L,handleDetectIdes:d,launchingIde:b,launchingAgentType:k,addLog:p}=c,[N,R]=a.useState(null),y=a.useCallback($=>{$&&u(Qp($))},[u]),v=Zp[e],j=e==="ide",g=e==="acp",h=a.useMemo(()=>n.filter($=>$.category===e&&(e==="ide"||$.installed!==!1)),[e,n]),K=a.useMemo(()=>new Map(h.map($=>[$.type,$.displayName||$.type])),[h]),[I,A]=a.useState(""),[M,O]=a.useState(""),[_,S]=a.useState([]),[H,q]=a.useState(""),[T,D]=a.useState(""),[W,z]=a.useState([]),[X,he]=a.useState(!1),[Te,je]=a.useState(""),[ve,te]=a.useState(!1),[ne,V]=a.useState(()=>bt()),[ie,re]=a.useState(null),[Z,me]=a.useState(f?"__custom__":m||s.defaultWorkspaceId||""),[se,ce]=a.useState(f||""),[ee,pe]=a.useState([]),[ae,Se]=a.useState(!1),[ge,P]=a.useState(""),[fe,Y]=a.useState([]),[ue,Ie]=a.useState(!1),[Pe,Be]=a.useState(""),qe=a.useRef(null),[We,Fe]=a.useState(null),Ye=a.useRef("__home__"),[pt,Ke]=a.useState("__home__"),[lt,nt]=a.useState(!1),He=a.useRef(0),at=ee.filter($=>!o.some(J=>J.type===$&&jt(J.status)!=="stopped")),dt=a.useRef({});a.useEffect(()=>{s.defaultWorkspaceId&&!Z&&me(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),a.useEffect(()=>{if(f){me("__custom__"),ce(f);return}m&&(me(m),ce(""))},[m,f]),a.useEffect(()=>{j||I&&(h.some($=>$.type===I)||(A(""),D("")))},[h,j,I]);const be=(()=>{if(Z==="__custom__")return se.trim();if(!Z)return"";const $=(s.workspaces||[]).find(J=>J.id===Z);return($==null?void 0:$.path)||""})(),Ue=a.useCallback($=>{const J=dt.current[$];J&&(clearTimeout(J),delete dt.current[$]),pe(le=>le.includes($)?le.filter(_e=>_e!==$):le)},[]),Qe=a.useRef(new Set),ze=a.useCallback(async $=>{if(l){Ie(!0),Be("");try{const J=await Vr(l,r,$);P(J.path),ce(J.path),Y(J.directories)}catch(J){Be(J instanceof Error?J.message:"Could not load folder")}finally{Ie(!1)}}},[r,l]),Rt=a.useCallback(()=>{if(!l)return;me("__custom__"),Se(!0);const $=o.map(le=>le.workspace),J=Fr(s.platform,zr(se.trim(),be,f,$,s.defaultWorkspacePath,(s.workspaces||[]).map(le=>le.path)));ze(J)},[se,f,ze,s.defaultWorkspacePath,s.platform,s.workspaces,o,be,l]),gt=a.useCallback($=>{const J=String($.workspace||"").trim();if(!J)return;const le=(s.workspaces||[]).find(_e=>yr(_e.path)===yr(J));if(le){me(le.id),ce("");return}me("__custom__"),ce(J)},[s.workspaces]),Tt=a.useCallback($=>{const J=String($.workspace||"").trim();if(!J)return{workspaceId:null,workspacePath:"",useHome:!0};const le=(s.workspaces||[]).find(_e=>yr(_e.path)===yr(J));return le?{workspaceId:le.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:J,useHome:!1}},[s.workspaces]),ut=a.useCallback(async $=>{if(!l||!$||e!=="cli"){z([]),he(!1),je("");return}const J=He.current+1;He.current=J,he(!0),je("");try{const le=await l(r,"list_saved_sessions",{providerType:$,kind:"cli",limit:30});if(He.current!==J)return;const _e=(le==null?void 0:le.result)??le;z(Array.isArray(_e==null?void 0:_e.sessions)?_e.sessions:[])}catch(le){if(He.current!==J)return;z([]),je(le instanceof Error?le.message:"Could not load saved sessions")}finally{He.current===J&&he(!1)}},[e,r,l]),yt=a.useMemo(()=>{if(e!=="cli"||!I)return null;const $=K.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:T||void 0,transport:"pty",mode:"chat",agentName:$,agentType:I,status:"idle",title:$,messages:[],ideType:I,workspaceName:be,displayPrimary:$,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,K,be,T,I]),Q=a.useCallback($=>{if(e==="ide"||!$){S([]);return}S(qi(r,$))},[e,r]);a.useEffect(()=>{if(D(""),Q(I),e!=="cli"||!I){z([]),je(""),he(!1);return}ut(I)},[e,Q,ut,I]);const E=a.useMemo(()=>W.find($=>$.providerSessionId===T)||null,[W,T]);a.useEffect(()=>{if(!T)return;const $=W.find(J=>J.providerSessionId===T);$!=null&&$.canResume||D("")},[W,T]);const B=a.useCallback(($,J)=>{qe.current=J,Ye.current=$.selectedWorkspaceKey||"__home__",Ke($.selectedWorkspaceKey||"__home__"),Fe($)},[]),F=a.useCallback(()=>{qe.current&&(nt(!0),qe.current().finally(()=>{qe.current=null,nt(!1),Fe(null)}))},[]),U=a.useCallback($=>{if(!$)return;pe(le=>le.includes($)?le:[...le,$]);const J=dt.current[$];J&&clearTimeout(J),dt.current[$]=setTimeout(()=>{pe(le=>le.includes($)?le.filter(_e=>_e!==$):le),delete dt.current[$]},2e4)},[]);a.useEffect(()=>{for(const J of o)jt(J.status)!=="stopped"&&(ee.includes(J.type)&&!Qe.current.has(J.type)&&(Qe.current.add(J.type),p("info",`${K.get(J.type)||J.type} launched`,!0)),Ue(J.type));const $=new Set(o.filter(J=>jt(J.status)!=="stopped").map(J=>J.type));Qe.current.forEach(J=>{!ee.includes(J)&&!$.has(J)&&Qe.current.delete(J)})},[p,Ue,o,ee,K]),a.useEffect(()=>()=>{Object.values(dt.current).forEach(clearTimeout),dt.current={}},[]);const[oe,ke]=a.useState({}),[G,de]=a.useState(null);a.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const J=await l(r,"get_ide_extensions",{}),le=(J==null?void 0:J.result)||J;le!=null&&le.success&&(le!=null&&le.ideExtensions)&&ke(le.ideExtensions)}catch{}})()},[j,r,l]);const De=$=>j?tt($.type):e==="cli"?$.cliName:$.acpName,Me=j?s.detectedIdes||[]:[],Oe=a.useCallback(async $=>{const J=($==null?void 0:$.type)||I,le=($==null?void 0:$.workspacePath)??be;if(j){await x(J,le?{workspace:le}:void 0)&&U(J);return}const _e=await c.runLaunchCliCore({cliType:J,dir:$!=null&&$.workspaceId?void 0:le||void 0,workspaceId:($==null?void 0:$.workspaceId)||void 0,useHome:($==null?void 0:$.useHome)||!($!=null&&$.workspaceId)&&!le,argsStr:($==null?void 0:$.argsStr)??(M||void 0),model:($==null?void 0:$.model)??(g&&H||void 0),resumeSessionId:($==null?void 0:$.resumeSessionId)||!g&&e==="cli"&&J===I&&T||void 0});if(_e.success||_e.pending){const xe=($==null?void 0:$.argsStr)??M;!j&&(xe!=null&&xe.trim())&&(Yi(r,J,xe),Q(J)),U(J),_e.success&&_e.sessionId&&y(_e.sessionId)}},[c,x,g,j,M,H,Q,U,r,y,be,T,I]),Ve=ci(j?"ide":g?"acp":"cli",!j&&!g&&!!T),Ze=li(j?"ide":g?"acp":"cli",!j&&!g&&!!T),Ae=()=>{var xe;const $=j?tt(I):K.get(I)||I,J=!j&&!g&&!!T,{options:le,selectedKey:_e}=ns({machine:s,currentWorkspaceId:Z&&Z!=="__custom__"?Z:null,currentWorkspacePath:be});B({title:J?ea($):es("start-fresh",$),description:J?ta():ts("start-fresh"),confirmLabel:Ve,busyLabel:Ze,workspaceOptions:le,selectedWorkspaceKey:_e,details:[{label:"Mode",value:v.label},{label:"Provider",value:$},...!j&&e==="cli"&&T?[{label:"Resume",value:((xe=W.find(Re=>Re.providerSessionId===T))==null?void 0:xe.title)||T}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...g&&H.trim()?[{label:"Model",value:H.trim()}]:[]]},async()=>{const Re=le.find(ot=>ot.key===Ye.current);Re!=null&&Re.workspaceId?(me(Re.workspaceId),ce("")):Re!=null&&Re.workspacePath?(me("__custom__"),ce(Re.workspacePath)):(me(""),ce("")),await Oe({workspaceId:(Re==null?void 0:Re.workspaceId)??null,workspacePath:(Re==null?void 0:Re.workspacePath)??"",useHome:!(Re!=null&&Re.workspaceId)&&!(Re!=null&&Re.workspacePath)})})},Le=$=>{j?L($):w($.type,$.workspace,$.id)},mt=a.useCallback(async($,J,le=!1)=>{if($.mode===J){le&&$.sessionId&&y($.sessionId);return}if(!l||!$.sessionId){le&&$.sessionId&&y($.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:$.type,mode:J}),le&&y($.sessionId)}catch(_e){ef(_e)?console.warn("Skipped CLI view mode switch:",_e instanceof Error?_e.message:String(_e)):console.error("Failed to switch CLI view mode:",_e)}},[r,y,l]),ht=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:Z,onChange:$=>{const J=$.target.value;if(me(J),J==="__custom__"&&l){Rt();return}J!=="__custom__"&&ce("")},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?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map($=>t.jsxs("option",{value:$.id,children:[$.id===s.defaultWorkspaceId?"⭐ ":"",Or($.path,$.label)]},$.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),Z==="__custom__"&&(l?t.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:Rt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:$=>ce($.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}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Z==="__custom__"?be?t.jsx("span",{className:"font-mono truncate block",title:be,children:be}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":be?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:Z===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:be,children:be})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${v.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",v.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Me.length>0?Me.map($=>{const J=o.find(ot=>(ot.type||"").toLowerCase()===($.type||"").toLowerCase()&&jt(ot.status)!=="stopped"),le=$.running||!!J,_e=!!J&&J.cdpConnected,xe=ee.includes($.type||$.id||""),Re=I===($.type||"");return t.jsxs("button",{onClick:()=>{if(_e&&J){const ot=J.sessionId;ot?u(`/dashboard?activeTab=${encodeURIComponent(ot)}`,{state:{openRemoteForTabKey:ot}}):u("/dashboard",{state:{openRemoteForTabKey:J.id}});return}xe||A(ot=>ot===($.type||"")?"":$.type||"")},disabled:!!b||xe,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${_e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Re?"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!==$.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i($.type)}),le&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${_e?"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"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.name||tt($.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${_e?"text-green-400":xe?"text-orange-400":Re?"text-accent-primary":"text-text-muted"}`,children:_e?"Open Session":xe?"Starting...":Re?"Configure":"Select"})]})]},$.type)}):t.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.",t.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:[t.jsx(Wc,{size:14})," Scan System"]})]}):h.length>0?h.map($=>{const J=I===$.type,le=ee.includes($.type),xe=!!o.find(Re=>Re.type===$.type&&jt(Re.status)!=="stopped");return t.jsxs("button",{onClick:()=>A(Re=>Re===$.type?"":$.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${J?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:$.icon}),xe&&t.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)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${le?"text-orange-400":J?"text-accent-primary":"text-text-muted"}`,children:le?"Starting...":J?"Configure":"Select"})]})]},$.type)}):t.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 ",e.toUpperCase()," providers available.",t.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."})]})}),I&&(j?Me.find($=>$.type===I):h.find($=>$.type===I))&&t.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:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?tt(I):K.get(I)||I})]}),ht,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(Ji,{busy:!!k||!!b||ee.includes(I),savedSessionsLoading:X,savedSessionsError:Te,selectedSession:E,onRefresh:()=>void ut(I),onOpenHistory:()=>{I&&(te(!0),ut(I))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:H,onChange:$=>q($.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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:M,onChange:$=>O($.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&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map($=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O($),title:$,children:$},$))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Ae,disabled:!!k||!!b||ee.includes(I),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:k===I||b===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",o.length+ee.filter($=>!o.some(J=>J.type===$&&jt(J.status)!=="stopped")).length,")"]}),o.length===0&&at.length===0?t.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 ",v.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[at.map($=>t.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:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?tt($):K.get($)||$}),t.jsx("div",{className:"text-[11px] text-text-muted",children:k===$?"Launching process...":"Waiting for process and session to register..."})]})]}),t.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:${$}`)),o.map($=>{const J=j?$:null,le=!j&&!g?$:null,_e=jt($.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i($.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[De($),(J==null?void 0:J.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",J.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:$.workspace||"—"}),(le==null?void 0:le.mode)&&t.jsx("span",{className:le.mode==="chat"?"text-violet-400":"text-text-secondary",children:le.mode==="chat"?"Chat view":"Terminal view"})]}),le&&(le.runtimeKey||le.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[le.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",le.runtimeKey]}),t.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 xe;(xe=navigator.clipboard)==null||xe.writeText(`adhdev attach ${le.runtimeKey}`),R(le.runtimeKey||null),window.setTimeout(()=>{R(Re=>Re===le.runtimeKey?null:Re)},1200)},children:N===le.runtimeKey?"Copied":"Copy"})]}),le.runtimeWriteOwner&&t.jsx("span",{style:{color:le.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:le.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Jp(le.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.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}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const xe=$.sessionId;if(xe){u(`/dashboard?activeTab=${encodeURIComponent(xe)}`,{state:{openRemoteForTabKey:xe}});return}u("/dashboard",{state:{openRemoteForTabKey:$.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:t.jsx(It,{size:13})}),t.jsx("button",{onClick:()=>{const xe=$.workspace||"",{options:Re,selectedKey:ot}=ns({machine:s,currentWorkspacePath:xe});B({title:es("restart-ide",tt($.type)),description:ts("restart-ide"),confirmLabel:Ns("restart-ide"),busyLabel:Ss("restart-ide"),workspaceOptions:Re,selectedWorkspaceKey:ot,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:tt($.type)}]},async()=>{const At=Re.find(As=>As.key===Ye.current),ft=(At==null?void 0:At.workspacePath)??"";if(ft&&ft!==xe){await Oe({type:$.type,workspacePath:ft});return}await C($)})},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:t.jsx(Is,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const xe=$.sessionId;xe&&y(xe)},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:!$.sessionId,children:t.jsx(Ut,{size:14})}),le&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[le.mode&&t.jsx(Qn,{mode:le.mode,onChange:xe=>void mt(le,xe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const xe=$.sessionId;xe&&y(xe)},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:!$.sessionId,children:le.mode==="chat"?t.jsx(Ut,{size:14}):t.jsx(It,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const xe=$.workspace||"",Re=j?tt($.type):De($),{options:ot,selectedKey:At}=ns({machine:s,currentWorkspacePath:xe});B({title:es("restart-stopped",Re),description:ts("restart-stopped"),confirmLabel:Ns("restart-stopped"),busyLabel:Ss("restart-stopped"),workspaceOptions:ot,selectedWorkspaceKey:At,details:[{label:"Mode",value:v.label},{label:"Provider",value:Re}]},async()=>{const ft=ot.find(As=>As.key===Ye.current);await Oe({type:$.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:ee.includes($.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:ee.includes($.type)?"⏳":t.jsx(Un,{size:14})}):t.jsx("button",{onClick:()=>Le($),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:t.jsx(kt,{size:14})})]})]}),J&&J.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:J.aiAgents.map(xe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ho(xe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[xe.name," · ",jt(xe.status)]},xe.id))}),J&&(oe[J.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(oe[J.type]||[]).map(xe=>t.jsxs("button",{disabled:G===`${J.type}.${xe.type}`,onClick:async()=>{const Re=`${J.type}.${xe.type}`;de(Re);try{await l(r,"set_ide_extension",{ideType:J.type,extensionType:xe.type,enabled:!xe.enabled}),ke(ot=>({...ot,[J.type]:(ot[J.type]||[]).map(At=>At.type===xe.type?{...At,enabled:!At.enabled}:At)}))}catch(ot){console.error("Extension toggle failed:",ot)}finally{de(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 ${xe.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${xe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),xe.name,t.jsx("span",{className:"text-[9px] font-normal",children:xe.enabled?"ON":"OFF"})]},xe.type))})]})]},$.id)})]}),ae&&l&&t.jsx(Gr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ge,directories:fe,busy:ue,error:Pe,confirmLabel:"Use this folder",onClose:()=>Se(!1),onNavigate:$=>{ze($)},onConfirm:$=>{ce($),me("__custom__"),Se(!1)}}),We&&t.jsx(la,{title:We.title,description:We.description,details:We.details,workspaceOptions:We.workspaceOptions,selectedWorkspaceKey:pt,onWorkspaceChange:$=>{Ye.current=$,Ke($)},confirmLabel:We.confirmLabel,busyLabel:We.busyLabel,busy:lt,onConfirm:F,onCancel:()=>{qe.current=null,Fe(null)}}),ve&&yt&&t.jsx(sa,{activeConv:yt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:W,isSavedSessionsLoading:X,isResumingSavedSessionId:ie,savedHistoryFilters:ne,onSavedHistoryFiltersChange:V,onClose:()=>te(!1),onNewChat:()=>{D(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{ut(I)},onResumeSavedSession:$=>{if(!$.canResume||ie)return;const J=Tt($);D($.providerSessionId),gt($),re($.providerSessionId),te(!1),Oe({type:$.providerType,workspaceId:J.workspaceId,workspacePath:J.workspacePath,useHome:J.useHome,resumeSessionId:$.providerSessionId}).finally(()=>{re(le=>le===$.providerSessionId?null:le)})}})]})}const vo=[{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 tf({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:o,acpSessions:i,actions:c,getIcon:l,initialCategory:m="ide",initialWorkspaceId:f,initialWorkspacePath:u,sendDaemonCommand:x}){var d;const[w,C]=a.useState(m);a.useEffect(()=>{C(m)},[m]);const L=a.useMemo(()=>({ide:n.length,cli:o.length,acp:i.length}),[n.length,o.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:vo.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>C(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=vo.find(b=>b.id===w))==null?void 0:d.helper})]}),w==="ide"&&t.jsx(jn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),w==="cli"&&t.jsx(jn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u}),w==="acp"&&t.jsx(jn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:u})]})}function sf({onNicknameSynced:e}={}){var Z,me,se,ce,ee,pe,ae,Se,ge;const{id:s}=wc(),r=Cs(),n=Wn(),{sendCommand:o}=_t(),i=tr(),c=ei(),l=c.ides||[],m=c.initialLoaded??!0,f=l.find(P=>P.id===s&&P.type==="adhdev-daemon"),u=l.some(P=>P.type==="adhdev-daemon"),[x,w]=a.useState("workspace"),[C,L]=a.useState("ide"),d=a.useRef(null),[b,k]=a.useState(null),p=a.useRef("__home__"),[N,R]=a.useState("__home__"),[y,v]=a.useState(!1),j=a.useRef(null);a.useEffect(()=>{!s||!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,f,s]),Bu(s&&x==="overview"?[s]:[],{enabled:x==="overview",intervalMs:15e3});const g=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},h=_p({machineId:s,registeredMachineId:(f==null?void 0:f.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:j});a.useEffect(()=>st.onToast(fe=>{c.setToasts(ue=>{if(ue.some(Be=>Be.message===fe.message&&fe.timestamp-Be.timestamp<3e3))return ue;const Pe={id:fe.id,message:fe.message,type:fe.type,timestamp:fe.timestamp,targetKey:fe.targetKey,actions:fe.actions};return[...ue.slice(-4),Pe]});const Y=fe.duration||5e3;setTimeout(()=>c.setToasts(ue=>ue.filter(Ie=>Ie.id!==fe.id)),Y)}),[c]);const K=(f==null?void 0:f.availableProviders)||[],I={};for(const P of K)I[P.type]=P.icon;const A=P=>I[P]||"",M=f?{id:f.id,hostname:Uo(f,{fallbackId:f.id}),platform:((Z=f.machine)==null?void 0:Z.platform)||"unknown",arch:((me=f.machine)==null?void 0:me.arch)||"",cpus:((se=f.machine)==null?void 0:se.cpus)||0,totalMem:((ce=f.machine)==null?void 0:ce.totalMem)||0,freeMem:(ee=f.machine)==null?void 0:ee.freeMem,availableMem:(pe=f.machine)==null?void 0:pe.availableMem,loadavg:(ae=f.machine)==null?void 0:ae.loadavg,uptime:(Se=f.machine)==null?void 0:Se.uptime,release:((ge=f.machine)==null?void 0:ge.release)||"",cdpConnected:!!f.cdpConnected,machineNickname:f.machineNickname||null,p2p:f.p2p?{screenshotActive:!1,...f.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:f.detectedIdes||[],workspaces:f.workspaces||[],defaultWorkspaceId:f.defaultWorkspaceId??f.activeWorkspaceId??null,defaultWorkspacePath:f.defaultWorkspacePath??f.activeWorkspacePath??null}:null,O=l.filter(P=>P.daemonId===s&&P.type!=="adhdev-daemon").filter(P=>!Ys(P)&&!bs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:Al(P.aiAgents||(P.agents||[]).map(fe=>({id:fe.name,name:fe.name,status:fe.status,version:fe.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:s})),_=l.filter(P=>P.daemonId===s&&Ys(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:s})),S=l.filter(P=>P.daemonId===s&&bs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:s})),H=f?Ct(f,{fallbackId:s}):"",q="workspace",T=n.state,D=T==null?void 0:T.initialMachineTab,W=T==null?void 0:T.initialWorkspaceCategory,z=T==null?void 0:T.initialWorkspaceId,X=T==null?void 0:T.initialWorkspacePath,he=D==="ides"||D==="clis"||D==="acps"?"workspace":D||q,Te=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":W,je=[...O.map(P=>{var fe,Y,ue,Ie,Pe;return{id:`ide:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((Pe=(Ie=(ue=(Y=P.activeChat)==null?void 0:Y.messages)==null?void 0:ue.at)==null?void 0:Ie.call(ue,-1))==null?void 0:Pe.timestamp)||0}}),..._.map(P=>{var fe,Y,ue,Ie,Pe;return{id:`cli:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((Pe=(Ie=(ue=(Y=P.activeChat)==null?void 0:Y.messages)==null?void 0:ue.at)==null?void 0:Ie.call(ue,-1))==null?void 0:Pe.timestamp)||0}}),...S.map(P=>{var fe,Y,ue,Ie,Pe;return{id:`acp:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:cs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:((Pe=(Ie=(ue=(Y=P.activeChat)==null?void 0:Y.messages)==null?void 0:ue.at)==null?void 0:Ie.call(ue,-1))==null?void 0:Pe.timestamp)||0}})].sort((P,fe)=>(fe.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),ve=((f==null?void 0:f.recentLaunches)||[]).length>0?((f==null?void 0:f.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:cs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):je,te=a.useMemo(()=>{var fe;const P=((fe=c.connectionStates)==null?void 0:fe[s||""])||void 0;return l.filter(Y=>Y.daemonId===s&&Y.type!=="adhdev-daemon").flatMap(Y=>ra(Y,{},{connectionStates:s&&P?{[s]:P}:void 0,defaultConnectionState:P})).filter(Y=>!(Y.transport==="pty"&&Y.mode==="terminal")).sort((Y,ue)=>Mn(ue)-Mn(Y))},[l,c.connectionStates,s]),ne=a.useCallback(P=>{const fe=P.sessionId||P.tabKey;fe&&r(`/dashboard?activeTab=${encodeURIComponent(fe)}`)},[r]),V=a.useCallback(()=>{d.current&&(v(!0),d.current().finally(()=>{d.current=null,v(!1),k(null)}))},[]),ie=a.useCallback(P=>{if(!M)return;const{options:fe,selectedKey:Y}=ns({machine:M,currentWorkspacePath:P.workspace}),ue=async()=>{L(P.kind),w("workspace")};d.current=async()=>{const Ie=fe.find(qe=>qe.key===p.current),Pe=(Ie==null?void 0:Ie.workspacePath)??null,Be=(Ie==null?void 0:Ie.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await h.handleLaunchIde(P.providerType,Pe?{workspace:Pe}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await h.runLaunchCliCore({cliType:P.providerType,dir:Be?void 0:Pe||"",workspaceId:Be||void 0,model:P.kind==="acp"&&Fo(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await ue()},p.current=Y,R(Y),k({title:P.kind==="ide"?es("restart-ide",P.label):P.providerSessionId?ea(P.label):es("start-fresh",P.label),description:P.kind==="ide"?ts("restart-ide"):P.providerSessionId?ta():ts("start-fresh"),confirmLabel:P.kind==="ide"?Ns("restart-ide"):P.providerSessionId?_r(!0):Ns("start-fresh"),busyLabel:P.kind==="ide"?Ss("restart-ide"):P.providerSessionId?Jn(!0):Ss("start-fresh"),workspaceOptions:fe,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[h,M]);if(a.useEffect(()=>{w(he)},[q,he,s]),a.useEffect(()=>{Te&&L(Te)},[Te,s]),!M)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const re=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(It,{size:14})," Workspace"]}),count:O.length+_.length+S.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($r,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kc,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($c,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:g,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:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[h.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:h.nicknameInput,onChange:P=>h.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&h.handleSaveNickname(),P.key==="Escape"&&h.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]"}),t.jsx("button",{onClick:h.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"}),t.jsx("button",{onClick:()=>h.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"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{h.setEditingNickname(!0),h.setNicknameInput(M.machineNickname||"")},title:"Click to set nickname",children:H}),t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(f==null?void 0:f.version)&&t.jsxs("span",{children:["v",f.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:re.map(P=>t.jsxs("button",{onClick:()=>w(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[x==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Xp,{machineEntry:f,providers:K,recentLaunches:ve,currentConversations:te,onUpgradeDaemon:async()=>{try{await o(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ie,onOpenConversation:ne}),t.jsx(tf,{machine:M,machineId:s,providers:K,ideSessions:O,cliSessions:_,acpSessions:S,actions:h,getIcon:A,initialCategory:C,initialWorkspaceId:z,initialWorkspacePath:X,sendDaemonCommand:o})]}),x==="providers"&&t.jsx(Kp,{machineId:s,providers:K,sendDaemonCommand:o}),x==="overview"&&t.jsx(Rp,{machineId:s,machine:M,ideSessions:O,cliSessions:_,acpSessions:S,actions:h,sendDaemonCommand:o}),x==="session-host"&&t.jsx(qp,{machineId:s,cliSessions:_,sendDaemonCommand:o}),x==="logs"&&t.jsx(zp,{machineId:s,sendDaemonCommand:o})]})})}),h.launchPick&&M&&t.jsx(Yp,{machine:M,launchPick:h.launchPick,actions:h}),b&&t.jsx(la,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:P=>{p.current=P,R(P)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:y,onConfirm:V,onCancel:()=>{d.current=null,k(null)}}),t.jsx(di,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(fe=>fe.filter(Y=>Y.id!==P)),onClickToast:P=>{P.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(P.targetKey)}`)}}),t.jsx("style",{children:`
|
|
68
|
+
@keyframes toast-in {
|
|
69
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
70
|
+
to { opacity: 1; transform: translateX(0); }
|
|
71
|
+
}
|
|
72
|
+
`})]})}class rf{constructor(){ct(this,"adapters",new Map);ct(this,"states",new Map);ct(this,"runtimeListeners",new Map);ct(this,"screenshotCallbacks",new Map);ct(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 Wt=new rf;function nf(){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 vr=nf(),wo=3e3,af=3e4;let $t=null,of=0;const Er=new Map;let Qt=null,Us=null;function jo(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function $s(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function cf(e){return e==="connected"?"connected":e}async function Cr(e,s,r){const n=au(e,r||{}),o=$t;if(o&&o.readyState===WebSocket.OPEN){const i=`req_${++of}_${Date.now()}`;return new Promise((c,l)=>{const m=setTimeout(()=>{Er.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Er.set(i,{resolve:f=>{clearTimeout(m),c(f)},reject:f=>{clearTimeout(m),l(f)}}),o.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function En(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class lf{constructor(s){ct(this,"daemonId");ct(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN}get connectionState(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Cr(this.daemonId,s,r)}async sendInput(s,r){return Cr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Cr(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());Wt.emitScreenshot(this.daemonId,o)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(s){Qt&&(clearInterval(Qt),Qt=null)}}let Lt=null;function df(e){return(!Lt||Lt.daemonId!==e)&&(Lt=new lf(e)),Lt}function uf({children:e}){const s=a.useRef(Tr()),r=Tr();s.current=r;const{setUserName:n}=os(),o=a.useRef(n);o.current=n;const i=a.useRef(null),c=a.useRef(null),[,l]=a.useState("disconnected"),m=a.useCallback((d,b)=>{l(d),Us==null||Us(d,b)},[]),f=a.useRef(null),u=a.useRef(),x=a.useRef(wo),w=a.useRef(!0),C=a.useRef(!1),L=a.useRef("initial_connect");return a.useEffect(()=>{w.current=!0,C.current=!1;function d(){var p,N;if(!w.current||((p=f.current)==null?void 0:p.readyState)===WebSocket.OPEN||((N=f.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;m("connecting"),console.log(`[Standalone WS] Connecting to ${vr}...`),$s("connect_attempt",{url:vr,reason:L.current,delayMs:x.current});let k;try{k=new WebSocket(vr)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),b();return}f.current=k,k.onopen=()=>{if(!w.current){k.close();return}m("connected"),x.current=wo,$s("open",{url:vr,reason:L.current}),Vt.resubscribeAll({sendData:En}),console.log("[Standalone WS] Connected")},$t=k,k.onmessage=R=>{var y,v;try{const j=JSON.parse(R.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const g=Er.get(j.requestId);g&&(Er.delete(j.requestId),j.type==="error"?g.reject(new Error(((y=j.data)==null?void 0:y.message)||"Command failed")):g.resolve(j.data));return}if(j.type==="session_output"){const g=j.sessionId||j.cliId||j.cliType;g&&Wt.emitSessionOutput(g,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const g=j.update;g&&Vt.publish(g);return}if(j.type==="status"||j.type==="initial_state"){const g=j.data;if(!g)return;const{injectEntries:h,markLoaded:K,getIdes:I}=s.current,A=g.instanceId||"standalone",M=I().find(S=>S.id===A),O=df(A);Wt.register(A,O),Wt.setState(A,"connected"),m("connected",A),Wt.emitStatus(A,g);const _=Mr(g,{daemonId:A,existingDaemon:M,existingEntries:I()});jo("ws_status",{type:j.type,daemonId:A,sessions:(g.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(g.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),jo("entries",{daemonId:A,entries:_.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),_.length>0&&h(_,{authoritativeDaemonIds:[A]}),K(),c.current!==A&&((v=i.current)==null||v.call(i),c.current=A,i.current=Vt.subscribe({sendData:En},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const H=s.current.getIdes(),q=H.find(D=>D.id===A),T=Mr(S.status,{daemonId:A,existingDaemon:q,existingEntries:H,timestamp:S.timestamp});T.length>0&&s.current.injectEntries(T),S.userName&&o.current&&o.current(S.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},k.onclose=R=>{w.current&&(Lt==null||Lt.stopScreenshots(),Lt&&Wt.setState(Lt.daemonId,"disconnected"),m("disconnected"),f.current=null,L.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,$s("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),b())},k.onerror=R=>{C.current||!w.current||(L.current="error",$s("error",{message:R instanceof Event?"event":String(R),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function b(){if(!w.current)return;clearTimeout(u.current);const k=x.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),$s("schedule_reconnect",{reason:L.current,delayMs:k}),u.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,af),d()},k)}return d(),()=>{var k;w.current=!1,C.current=!0,(k=i.current)==null||k.call(i),i.current=null,c.current=null,clearTimeout(u.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,$t=null),Lt&&(Lt.stopScreenshots(),Wt.unregister(Lt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function mf({children:e}){const[s,r]=a.useState("disconnected"),[n,o]=a.useState(null);a.useEffect(()=>(Us=(c,l)=>{r(c),l&&o(l)},()=>{Us=null}),[]);const i=a.useMemo(()=>{const c=s==="connected",l=cf(s),m={};return n&&(m[n]=l),m.standalone=l,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(Ac,{connectionOverrides:i,children:t.jsx(uf,{children:e})})}const pf=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Mo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ht,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx($r,{}),label:"Settings"}];function ff({children:e}){const s=Cs(),r=Wn(),[n,o]=a.useState(!1),[i,c]=a.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=u=>{s(u),o(!1)},m=()=>{c(u=>{const x=!u;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=u=>`nav-item${r.pathname.startsWith(u)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>o(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>o(!1),onKeyDown:u=>u.key==="Escape"&&o(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>o(!1),children:t.jsx(kt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:pf.map(u=>t.jsxs("div",{className:f(u.path),id:`nav-${u.id}`,onClick:()=>l(u.path),title:i?u.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:u.icon}),!i&&u.label]},u.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.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:[t.jsx("span",{className:"nav-icon",children:t.jsx(Lo,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.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:[t.jsx("span",{className:"nav-icon",children:t.jsx(_o,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.61"]}),t.jsx(gu,{collapsed:i}),t.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:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const xf=[{icon:t.jsx(Ht,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ut,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ro,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(It,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Fs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Lo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],hf=[{icon:t.jsx(Uc,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Mo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Wr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Ec,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(On,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Bc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],bf=[{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 gf(){return t.jsxs(hi,{icon:t.jsx(_o,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.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.61"]}),children:[t.jsx(Dt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(Dt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:xf.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Dt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:pi.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:xi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:fi.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.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))})]},e.label))})}),t.jsx(Dt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:hf.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Dt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:bf.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(bi,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Zc,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function yf(){const{ides:e}=os(),s=e.find(x=>x.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=_t(),{userName:o}=os(),[i,c]=a.useState(o||"");a.useEffect(()=>{o!==void 0&&c(o)},[o]);const l=x=>{const w=x.target.value.trim();s!=null&&s.id&&w!==o&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[m,f]=a.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=x=>{f(x);try{localStorage.setItem("adhdev_sound",x?"1":"0")}catch{}};return t.jsxs(hi,{icon:t.jsx($r,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(mu,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Dt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.61"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Dt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(x=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${x.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:x.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:x.type})]},x.type))})}),t.jsx(Dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(ju,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Dt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Cu,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Pu,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(Eu,{})]})]})}),t.jsx(Dt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(yu,{}),t.jsx(Jt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jc,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:u})]})}),t.jsx(Dt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(Dc,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.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:x=>c(x.target.value),onBlur:l,onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()}})]})})})]})}bu();_u();const vf=To({baseUrl:""});function ko(){const{ides:e,initialLoaded:s}=os();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(Sn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Sn,{to:"/dashboard",replace:!0})}function wf(){const e=a.useMemo(()=>({sendCommand:Cr,sendData:En}),[]);return t.jsx(jc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(_c,{client:vf,children:t.jsx(mf,{children:t.jsx(Pc,{value:e,children:t.jsx(ff,{children:t.jsxs(kc,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(Lp,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(ko,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(sf,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(ko,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(gf,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(yf,{})}),t.jsx(Yt,{path:"*",element:t.jsx(Sn,{to:"/dashboard",replace:!0})})]})})})})})})}Md({connectionManager:Wt});Nc(document.getElementById("root")).render(t.jsx(wf,{}));
|