@adhdev/daemon-standalone 0.8.66 → 0.8.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Mc=Object.defineProperty;var Lc=(e,s,r)=>s in e?Mc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var ft=(e,s,r)=>Lc(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Hn,a as Un,b as Mo,c as Lo,u as Ls,R as rt,d as qs,t as _c,e as Rc,D as Pc,f as In,g as An,h as zn,i as Dc,k as Ec,B as $c,l as Bc,m as Qt,N as Tn,n as Kc}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)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(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function Wc(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={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(a),r.length>s&&r.splice(0,r.length-s),a},list(n={}){const a=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(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const cs=Wc();function Aa(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 _o=o.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}),Ro=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ta(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 en(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=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,u=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Ar(e){return Array.isArray(e)?e.map(Ar):!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,Ar(r)]))}function Oc(e,s){try{return JSON.stringify(Ar(e))===JSON.stringify(Ar(s))}catch{return!1}}function rr(e,s,r){return Oc(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Hc(e,s,r){var u,p,m,f,v,N,L;const n=Date.now(),a=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 S=Ta(d),h=Ta(b);if(S>h){const w=(u=d.chats)!=null&&u.length?d.chats:b.chats,_=en(b,d,{...b,...d,chats:w,_lastUpdate:n});i.set(d.id,rr(b,_,n))}else if(S<h){const w={};if(d.status&&d.status!==b.status&&(w.status=d.status),d.cdpConnected!==void 0&&(w.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(w.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(w.machineNickname=d.machineNickname),d.version!==void 0&&(w.version=d.version),d.serverVersion!==void 0&&(w.serverVersion=d.serverVersion),d.versionMismatch===!0&&(w.versionMismatch=!0),Object.keys(w).length>0){const _=en(b,d,{...b,...w,_lastUpdate:b._lastUpdate});i.set(d.id,rr(b,_,n))}else rr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const w=d.timestamp||n,_=b._lastUpdate||b.timestamp||0;if(w>=_){const g=(f=d.chats)!=null&&f.length?d.chats:b.chats,j=en(b,d,{...b,...d,chats:g,_lastUpdate:n});i.set(d.id,rr(b,j,n))}else(v=d.chats)!=null&&v.length&&!((N=b.chats)!=null&&N.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 S=b.daemonId||d.split(":")[0];if(!l.has(S))continue;if(a.has(S)&&!c.has(d)){i.delete(d);continue}const h=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&h>1e4||b.transport==="acp"&&!c.has(d)&&h>1e4||b.transport==="cdp-page"&&!c.has(d)&&h>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 Uc(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 zc({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,p]=o.useState(void 0),m=o.useRef(r);o.useEffect(()=>{m.current=r},[r]);const f=o.useCallback((S,h)=>{n(w=>{let _=!1;const g=w.map(j=>j.id!==S||j.chats===h?j:(_=!0,{...j,chats:h}));return _?g:w})},[]),v=o.useCallback((S,h)=>{n(w=>{const _=w.length===0?S:Hc(S,w,h),g=!Uc(w,_);return g&&cs.record({kind:"dashboard.entries_applied",payload:{incoming:Aa(S),next:Aa(_)}}),g?_:w})},[]),N=o.useCallback(()=>i(!0),[]),L=o.useMemo(()=>({injectEntries:v,markLoaded:N,getIdes:()=>m.current}),[v,N]),d=s,b=o.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,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:u,setUserName:p}),[r,f,a,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,u]);return t.jsx(Ro.Provider,{value:L,children:t.jsx(_o.Provider,{value:b,children:e})})}function ls(){return o.useContext(_o)}function Tr(){return o.useContext(Ro)}function Po(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),p=a(l),m=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&m.searchParams.set("token",u),!l.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(l,u={}){const p={"Content-Type":"application/json",...u.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const f=a(l),v=new AbortController,N=setTimeout(()=>v.abort(),15e3);try{const L=await fetch(f,{...u,headers:p,signal:v.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(N)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Fc=Po({baseUrl:"http://localhost:3847"}),Vc=o.createContext(Fc);function Gc({client:e,children:s}){return t.jsx(Vc.Provider,{value:e,children:s})}const qc={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Do=o.createContext(qc);function Yc({value:e,children:s}){return t.jsx(Do.Provider,{value:e,children:s})}function _t(){return o.useContext(Do)}const He={size:18};function Eo({size:e=He.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 Fn({size:e=He.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 Ot({size:e=He.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 Vn({size:e=He.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 Xc({size:e=He.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 Qc({size:e=He.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 $o({size:e=He.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 Jc({size:e=He.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 Wr({size:e=He.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 Bo({size:e=He.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 Zc({size:e=He.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 Ht({size:e=He.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=He.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 Gn({size:e=He.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 el({size:e=He.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 Ns({size:e=He.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 _s({size:e=He.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 ds({size:e=He.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 Ys({size:e=He.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 Ko({size:e=He.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 Wo({size:e=He.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 Oo({size:e=He.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 tl({size:e=He.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 Or({size:e=He.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 sl({size:e=He.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 qn({size:e=He.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 rl({size:e=He.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=He.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 nl({size:e=He.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 al({size:e=He.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 ol({size:e=He.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 il({size:e=He.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 Hr({size:e=He.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 cl({size:e=He.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 ll({size:e=He.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 dl({size:e=He.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 ul({size:e=He.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 ml({size:e=He.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 pl({size:e=He.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 fl({size:e=He.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 xl({size:e=He.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 hl({size:e=He.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 bl({size:e=He.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 gl({size:e=He.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 yl({size:e=He.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 Ma(e){return!!e&&typeof e=="object"&&"text"in e}function Yn(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Ma(i)?String(i.text||""):"").join(r):Ma(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ss(e){return Yn(e,{normalizeWhitespace:!0})}const tn=new Map;function Ho(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function vl(e,s,r){return Number(e.receivedAt||r[vs(e,s)]||0)||0}function Uo(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function wl(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function nr(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 sn(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 La(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Uo(e)?t.jsx(Hn,{remarkPlugins:[Un,Mo,Lo],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ar({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:La(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=sn(r);return a?t.jsx("img",{src:a,alt:nr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=sn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=sn(r);return a?t.jsx("video",{controls:!0,src:a,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:nr(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||nr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=nr(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:a}),La(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:a},`resource-uri-${n}`)}return null})})}function vs(e,s){const r=e,n=Yn(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 jl=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Hn,{remarkPlugins:[Un],children:s.text}),t.jsx("span",{className:"action-time",children:Ho(s.timestamp)})]})},(e,s)=>e.log===s.log),kl=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var j,k,y;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=wl(s.content)?s.content:null,v=!!(f!=null&&f.some(x=>x.type!=="text")),N=Yn(s.content,{joiner:`
|
|
4
|
-
`});if(m==="thought"){const x=typeof((j=s.meta)==null?void 0:j.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(ol,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:N})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),v&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(ar,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:N})]});if(m==="terminal"){const x=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",E=typeof((y=s.meta)==null?void 0:y.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:x}),t.jsx("span",{children:E})]}),v&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(ar,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:N})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:v&&f?t.jsx(ar,{parts:f,renderAsPreformatted:!1}):N.slice(0,100)});const L=s.meta,b=(typeof(L==null?void 0:L.renderMode)=="string"?L.renderMode.trim():"")==="preformatted",S=N,h=!1,w=S,_=b,g=!_&&Uo(w);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(S||v||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${S||v?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Ho(r)})]}),(S||v)&&t.jsx("div",{className:"chat-markdown",children:v&&f?t.jsx(ar,{parts:f,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:w}):g?t.jsx(Hn,{remarkPlugins:[Un,Mo,Lo],children:w}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:w})}),h]})})},(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),Nl=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:p,onLoadMore:m,isLoadingMore:f,hasMoreHistory:v,hiddenLiveCount:N=0,loadError:L,scrollToBottomRequestNonce:d},b){var _e;const S=o.useRef(null),h=o.useRef(null),w=o.useRef(null),_=o.useRef(0),g=o.useRef(""),j=o.useRef(!1),k=o.useRef(null),y=o.useRef(!1),x=o.useRef(null),E=o.useRef(!1),[I,M]=o.useState(new Set),T=o.useRef(!1),W=o.useRef(!1),R=()=>{const ae=S.current;return ae?ae.scrollHeight-ae.scrollTop-ae.clientHeight<200:!0},C=o.useCallback((ae="auto")=>{const ee=S.current;ee&&ee.scrollTo({top:ee.scrollHeight,behavior:ae})},[]),H=o.useCallback(()=>{const ae=S.current;!ae||!l||tn.set(l,{top:ae.scrollTop,fromBottom:Math.max(0,ae.scrollHeight-ae.scrollTop-ae.clientHeight)})},[l]),G=o.useCallback(()=>{var re;const ae=S.current,ee=(re=window.getSelection)==null?void 0:re.call(window);if(!ae||!ee||ee.rangeCount===0||ee.isCollapsed){E.current=!1;return}const se=ee.anchorNode,ue=ee.focusNode;E.current=!!(se&&ue&&ae.contains(se)&&ae.contains(ue))},[]),A=o.useCallback((ae="auto")=>{k.current!=null&&cancelAnimationFrame(k.current),k.current=requestAnimationFrame(()=>{k.current=null,C(ae)})},[C]),$=s.length>0?`${s.length}:${(((_e=s[s.length-1])==null?void 0:_e.content)||"").length}`:"0:0";o.useEffect(()=>{const ae=!j.current,ee=g.current!==l;if(g.current=l,ae||ee){if(j.current=!0,T.current=!1,y.current=!0,!E.current){const ue=l?tn.get(l):null;ue?requestAnimationFrame(()=>{const re=S.current;if(!re)return;const z=Math.max(0,re.scrollHeight-re.clientHeight-ue.fromBottom);re.scrollTop=Number.isFinite(z)?z:ue.top,W.current=!0}):A("auto")}_.current=s.length;return}s.length>_.current?!T.current&&!E.current&&A("auto"):R()&&!T.current&&!E.current&&A("auto"),_.current=s.length},[$,l,c,s.length,A]),o.useEffect(()=>{d&&(T.current=!1,y.current=!0,W.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{y.current=!1,x.current=null},180),E.current||A("auto"))},[A,d]),o.useEffect(()=>()=>{H(),k.current!=null&&cancelAnimationFrame(k.current),x.current!=null&&window.clearTimeout(x.current)},[H]),o.useEffect(()=>{const ae=h.current;if(!ae)return;const ee=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{y.current=!1,x.current=null},180)},se=new ResizeObserver(()=>{y.current&&(E.current||(A("auto"),ee()))});return se.observe(ae),()=>{se.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[A,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(ae="smooth")=>{C(ae)}}),[C]),o.useEffect(()=>{const ae=S.current;if(!ae)return;let ee;const se=()=>{clearTimeout(ee),ee=setTimeout(()=>{T.current=!R(),H()},50)};return ae.addEventListener("scroll",se,{passive:!0}),()=>{ae.removeEventListener("scroll",se),clearTimeout(ee)}},[H]),o.useEffect(()=>(document.addEventListener("selectionchange",G),()=>document.removeEventListener("selectionchange",G)),[G]);const B=o.useRef(0),O=o.useRef(!1);o.useEffect(()=>{const ae=S.current;if(!ae||!O.current||B.current===0)return;const ee=ae.scrollHeight-B.current;ee>0&&(ae.scrollTop=ee),H(),B.current=0,O.current=!1},[s.length,H]),o.useEffect(()=>{if(W.current||!l)return;const ae=tn.get(l),ee=S.current;if(!ae||!ee)return;const se=Math.max(0,ee.scrollHeight-ee.clientHeight-ae.fromBottom);ee.scrollTop=Number.isFinite(se)?se:ae.top,W.current=!0},[l,s.length]);const X=()=>{const ae=S.current;ae&&(B.current=ae.scrollHeight),O.current=!0,m==null||m()},je=o.useMemo(()=>{const ae=s.map((re,z)=>({type:"message",data:re,index:z,ts:vl(re,z,u)}));if(!r||r.length===0)return ae;const ee=[...r].sort((re,z)=>re.timestamp-z.timestamp).map((re,z)=>({type:"action",data:re,index:z,ts:re.timestamp})),se=[];let ue=0;for(const re of ae){for(;ue<ee.length&&re.ts>0&&ee[ue].ts<re.ts;)se.push(ee[ue++]);se.push(re)}for(;ue<ee.length;)se.push(ee[ue++]);return se},[s,r,u]),$e=N>0||!!v,me=N>0?`↑ Show ${Math.min(N,80)} earlier messages${N>80?` (${N} hidden)`:""}`:L?`↻ ${L}`:"↑ Load older messages";return t.jsx("div",{ref:S,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[f&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),$e&&!f&&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&&N===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:me})}),je.length===0&&!$e&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),je.map(ae=>{if(ae.type==="action"){const Z=ae.data;return t.jsx(jl,{log:Z},`action-${ae.index}`)}const ee=ae.data,se=ae.index,ue=vs(ee,se),re=ee.receivedAt||u[ue],z=`${l}-${ue}`,le=I.has(z);return t.jsx(kl,{message:ee,receivedAt:re,agentName:n,userName:a,isCliMode:i,isTextExpanded:le,onToggleTextExpanded:()=>M(Z=>{const ie=new Set(Z);return le?ie.delete(z):ie.add(z),ie})},`msg-${ue}`)}),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:w})]})})}),Sl=o.memo(Nl,(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),Cl="modulepreload",Il=function(e){return"/"+e},_a={},Al=function(s,r,n){let a=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"));a=Promise.allSettled(r.map(u=>{if(u=Il(u),u in _a)return;_a[u]=!0;const p=u.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Cl,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((v,N)=>{f.addEventListener("load",v),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Ra=!1;const zo=o.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),v=()=>{const N=i.current;if(N){p.current&&(N.clear(),p.current=!1);for(const L of u.current)N.write(L);u.current=[],m.current&&(N.fit(),m.current=!1),f.current&&(N.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:N=>{i.current?i.current.write(N):u.current.push(N)},clear:()=>{i.current?i.current.clear():(u.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],p.current=!0)},resize:(N,L)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(N,L)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const N=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(N)},[c]),o.useEffect(()=>{let N=!1;return Al(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(L=>{Ra||(Ra=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),N||l(()=>L.GhosttyTerminalView)}).catch(L=>{console.error("[CliTerminal] failed to load terminal renderer",L)}),()=>{N=!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"}})});zo.displayName="CliTerminal";function or({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 Pa({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,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)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Tl({cursorPos:e,viewportRef:s,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=s.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,p=a.width/a.height;let m,f,v,N;u>p?(m=a.width,f=a.width/u,v=0,N=(a.height-f)/2):(f=a.height,m=a.height*u,v=(a.width-m)/2,N=0);const L=a.left-i.left+v+m*e.nx,d=a.top-i.top+N+f*e.ny,b=Math.max(8,Math.min(i.width-8,L)),S=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:S-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 Ml({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:m,isMobile:f,mobileFillZoom:v,onZoomOut:N,onZoomReset:L,onZoomIn:d,transportType:b,screenshotUsage:S,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:w=>w.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(w=>!w),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:w=>w.stopPropagation(),onChange:w=>l(w.target.value),onKeyDown:w=>{u(w)},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(w=>!w),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"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:p?"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:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*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"}),S&&S.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:S.budgetExhausted?"#ef4444":"#c4b5fd",background:S.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:S.budgetExhausted?"TURN blocked":`TURN ${S.dailyUsedMinutes}/${S.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:w=>w.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: ",m<=(f?v:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:w=>{w.stopPropagation(),N()},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:w=>{w.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:f?"FILL":"FIT"}),t.jsx("button",{onClick:w=>{w.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 Ll({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 _l(){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 Da(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 Zs(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!_l())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,Da(l)]))}),r.current=s;return}const i=Object.keys({...a,...s}).filter(c=>!Object.is(a[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Da(s[c])]))}),r.current=s})}function Rl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:m,setZoom:f,lastWheelTimeRef:v,onAction:N,setLastActionStatus:L,spawnRippleFromNormalized:d,clampPan:b,isMobile:S,mobileFillZoom:h}){const[w,_]=o.useState(null),g=o.useRef(null),j=o.useRef(null),k=o.useRef(null),y=o.useRef(!1),x=o.useRef(null),E=o.useRef(0),I=o.useRef(null),M=o.useRef(1),T=o.useRef({x:0,y:0}),W=o.useRef(!1),R=o.useRef(n),C=o.useRef(N),H=30,G=550,A=18,$=60,B=400,O=12,X=()=>{if(g.current)return;const me={nx:.5,ny:.5};g.current=me,_(me)};return o.useEffect(()=>{R.current=n,n==="mouse"&&X()},[n]),o.useEffect(()=>{C.current=N},[N]),o.useEffect(()=>{const me=e.current;if(!me)return;const _e=z=>{if(!r.current)return null;const le=r.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(z.clientX-le.left)/le.width)),ny:Math.max(0,Math.min(1,(z.clientY-le.top)/le.height))}},ae=(z,le)=>{if(!r.current)return{dnx:0,dny:0};const Z=r.current,ie=Z.getBoundingClientRect(),Q=Z.naturalWidth||ie.width,de=Z.naturalHeight||ie.height,oe=Q/de,ge=ie.width/ie.height;let fe,D;return oe>ge?(fe=ie.width,D=ie.width/oe):(D=ie.height,fe=ie.height*oe),{dnx:z/fe,dny:le/D}},ee=(z,le,Z)=>{if(Z<=1.05)return;const ie=-(z-.5)*100,Q=-(le-.5)*100,de=b(ie,Q,Z);(Math.abs(de.x-l.current)>.1||Math.abs(de.y-u.current)>.1)&&(p(de.x),m(de.y),l.current=de.x,u.current=de.y)},se=z=>{const le=s.current;if(le&&z.target instanceof Node&&le.contains(z.target))z.preventDefault();else return;if(z.touches.length===1){const Z=z.touches[0];j.current={x:Z.clientX,y:Z.clientY,time:Date.now()},k.current={x:Z.clientX,y:Z.clientY},W.current||(y.current=!1),x.current=setTimeout(()=>{if(!y.current&&!W.current)if(y.current=!0,R.current==="mouse"){const ie=g.current||{nx:.5,ny:.5};L("Right Click"),d(ie.nx,ie.ny,"right"),C.current("input_click",{...ie,button:"right"}).catch(()=>{})}else{const ie=_e(Z);ie&&(L("Right Click"),d(ie.nx,ie.ny,"right"),C.current("input_click",{...ie,button:"right"}).catch(()=>{}))}},500);return}if(z.touches.length===2){x.current&&clearTimeout(x.current),y.current=!0,W.current=!0;const Z=z.touches[1].clientX-z.touches[0].clientX,ie=z.touches[1].clientY-z.touches[0].clientY;I.current=Math.sqrt(Z*Z+ie*ie),M.current=c.current,T.current={x:(z.touches[0].clientX+z.touches[1].clientX)/2,y:(z.touches[0].clientY+z.touches[1].clientY)/2}}},ue=z=>{const le=s.current;if(le&&z.target instanceof Node&&le.contains(z.target)&&z.preventDefault(),z.touches.length===1&&k.current){const Z=z.touches[0],ie=Z.clientX-k.current.x,Q=Z.clientY-k.current.y;if(!y.current&&j.current){const de=Z.clientX-j.current.x,oe=Z.clientY-j.current.y;Math.sqrt(de*de+oe*oe)>8&&(y.current=!0,x.current&&clearTimeout(x.current))}if(y.current)if(R.current==="mouse"){const de=ae(ie,Q),oe=g.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,oe.nx+de.dnx)),fe=Math.max(0,Math.min(1,oe.ny+de.dny));g.current={nx:ge,ny:fe},_({nx:ge,ny:fe}),L(`Cursor: ${Math.round(ge*100)}%, ${Math.round(fe*100)}%`),ee(ge,fe,c.current);const D=Date.now();D-v.current>=30&&(v.current=D,C.current("input_mouseMoved",{nx:ge,ny:fe}).catch(()=>{}))}else if(c.current>1){const de=s.current;if(de){const oe=de.clientWidth,ge=de.clientHeight,fe=l.current+ie/oe*100,D=u.current+Q/ge*100,ye=b(fe,D,c.current);p(ye.x),m(ye.y),l.current=ye.x,u.current=ye.y}}else{const de=_e(Z);if(de){const oe=Date.now();oe-v.current>=40&&(v.current=oe,L("Scroll"),C.current("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(-ie*2.5),deltaY:Math.round(-Q*2.5)}).catch(()=>{}))}}k.current={x:Z.clientX,y:Z.clientY};return}if(z.touches.length===2&&I.current!==null){const Z=z.touches[1].clientX-z.touches[0].clientX,ie=z.touches[1].clientY-z.touches[0].clientY,de=Math.sqrt(Z*Z+ie*ie)/I.current,oe=(z.touches[0].clientX+z.touches[1].clientX)/2,ge=(z.touches[0].clientY+z.touches[1].clientY)/2,fe=oe-T.current.x,D=ge-T.current.y,ye=Math.abs(de-1)>.03;if(R.current==="mouse"){if(ye){const be=Math.max(i,Math.min(5,M.current*de));f(be),c.current=be}else if(Math.abs(fe)>2||Math.abs(D)>2){const be=g.current||{nx:.5,ny:.5},Ne=Date.now();Ne-v.current>=30&&(v.current=Ne,L("Scroll"),C.current("input_wheel",{nx:be.nx,ny:be.ny,deltaX:Math.round(-fe*3),deltaY:Math.round(-D*3)}).catch(()=>{}))}}else{const be=Math.max(i,Math.min(5,M.current*de));f(be),c.current=be;const Ne=s.current;if(Ne&&be>1){const J=Ne.clientWidth,Se=Ne.clientHeight,Ue=l.current+fe/J*100,De=u.current+D/Se*100,Ve=b(Ue,De,be);p(Ve.x),m(Ve.y),l.current=Ve.x,u.current=Ve.y}}T.current={x:oe,y:ge}}},re=z=>{var le;if(x.current&&clearTimeout(x.current),I.current=null,z.touches.length===1&&W.current){const Z=z.touches[0];j.current={x:Z.clientX,y:Z.clientY,time:Date.now()},k.current={x:Z.clientX,y:Z.clientY},y.current=!0;return}if(z.touches.length===0){if(W.current){W.current=!1,y.current=!1;return}if(z.changedTouches.length===1){const Z=z.changedTouches[0],ie=Date.now(),Q=ie-(((le=j.current)==null?void 0:le.time)||0),de=j.current?Z.clientX-j.current.x:0,oe=j.current?Z.clientY-j.current.y:0,ge=Math.sqrt(de*de+oe*oe);if(R.current==="mouse"){if(Q<H||Q>G||ge>A){y.current=!1;return}const fe=g.current||_e(Z);fe&&(L(`Click: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),d(fe.nx,fe.ny,"left"),C.current("input_click",{...fe}).catch(()=>{}))}else{if(y.current){y.current=!1;return}if(Q<$||Q>B||ge>O){y.current=!1;return}const fe=_e(Z);if(!fe)return;ie-E.current<300?(L("Double tap"),d(fe.nx,fe.ny,"double"),C.current("input_click",{...fe,clickCount:2}).catch(()=>{}),E.current=0):(L(`Tap: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),d(fe.nx,fe.ny,"left"),C.current("input_click",{...fe}).catch(()=>{}),E.current=ie)}}y.current=!1}};return me.addEventListener("touchstart",se,{passive:!1}),me.addEventListener("touchmove",ue,{passive:!1}),me.addEventListener("touchend",re,{passive:!1}),()=>{me.removeEventListener("touchstart",se),me.removeEventListener("touchmove",ue),me.removeEventListener("touchend",re),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,v,L,d,b]),{cursorPos:w,cursorPosRef:g,handleToggleInputMode:()=>{a(me=>{const _e=me==="touch"?"mouse":"touch";return _e==="mouse"&&X(),_e})},handleZoomReset:()=>{const me=S?h:1;f(me),c.current=me,p(0),m(0),l.current=0,u.current=0}}}function Fo({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[p,m]=o.useState(null),[f,v]=o.useState(""),[,N]=o.useState(!1),[L,d]=o.useState([]),b=o.useRef(0),[S,h]=o.useState(!1),[w,_]=o.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[j,k]=o.useState(g?"mouse":"touch"),[y,x]=o.useState(1),E=o.useRef(!1),[I,M]=o.useState(1),[T,W]=o.useState(0),[R,C]=o.useState(0);Zs("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:j,zoom:I,panX:T,panY:R,isMenuOpen:S,isImeOpen:w});const H=o.useRef(0),G=o.useRef(I),A=o.useRef(T),$=o.useRef(R);o.useEffect(()=>{G.current=I},[I]),o.useEffect(()=>{A.current=T},[T]),o.useEffect(()=>{$.current=R},[R]),o.useEffect(()=>{var Q;(Q=c.current)==null||Q.focus()},[]);const B=r==="connected",O=n,X=B?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",je=B?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!g||E.current||!O)return;const Q=u.current,de=l.current;if(!Q||!de)return;const oe=()=>{const ge=de.clientWidth,fe=de.clientHeight,D=Q.naturalWidth,ye=Q.naturalHeight;if(!D||!ye||!ge||!fe)return;const be=Math.min(ge/D,fe/ye),J=Math.max(ge/D,fe/ye)/be;J>1.01&&(x(J),M(J),G.current=J),E.current=!0};Q.complete&&Q.naturalWidth?oe():Q.addEventListener("load",oe,{once:!0})},[O,g]);const $e=.5;o.useEffect(()=>{I<=$e&&(W(0),C(0))},[I,$e]);const me=(Q,de,oe)=>{if(oe<=$e)return{x:0,y:0};const ge=(oe-1)/(2*oe)*100,fe=(oe-1)/(2*oe)*100;return{x:Math.max(-ge,Math.min(ge,Q)),y:Math.max(-fe,Math.min(fe,de))}},_e=(Q,de)=>{if(!u.current)return null;const oe=u.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(Q-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(de-oe.top)/oe.height))}},ae=(Q,de,oe)=>{const ge=l.current;if(!ge)return;const fe=ge.getBoundingClientRect(),D=++b.current;d(ye=>[...ye,{id:D,x:Q-fe.left,y:de-fe.top,type:oe}]),setTimeout(()=>d(ye=>ye.filter(be=>be.id!==D)),600)},ee=(Q,de,oe)=>{const ge=u.current,fe=l.current;if(!ge||!fe)return;const D=ge.getBoundingClientRect(),ye=fe.getBoundingClientRect(),be=ge.naturalWidth||D.width,Ne=ge.naturalHeight||D.height,J=be/Ne,Se=D.width/D.height;let Ue,De,Ve,Ye;J>Se?(Ue=D.width,De=D.width/J,Ve=0,Ye=(D.height-De)/2):(De=D.height,Ue=D.height*J,Ve=(D.width-Ue)/2,Ye=0);const Xe=D.left-ye.left+Ve+Ue*Q,pt=D.top-ye.top+Ye+De*de,Ge=++b.current;d(bt=>[...bt,{id:Ge,x:Xe,y:pt,type:oe}]),setTimeout(()=>d(bt=>bt.filter(lt=>lt.id!==Ge)),600)},se=async Q=>{var oe;const de=_e(Q.clientX,Q.clientY);if(de){m(`Click: ${Math.round(de.nx*100)}%, ${Math.round(de.ny*100)}%`),ae(Q.clientX,Q.clientY,"left"),(oe=c.current)==null||oe.focus();try{const ge=await e("input_click",{nx:de.nx,ny:de.ny});ge!=null&&ge.success||s(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){s(`❌ Click error: ${ge.message||ge}`)}}},ue=async(Q,de,oe,ge=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:Q,code:de,text:oe?Q:void 0,unmodifiedText:oe?Q:void 0,modifiers:ge})}catch(fe){s(`❌ Key error: ${fe.message||fe}`)}},re=async Q=>{if(Q.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Q.key)&&Q.preventDefault();let oe=0;Q.altKey&&(oe|=1),Q.ctrlKey&&(oe|=2),Q.metaKey&&(oe|=4),Q.shiftKey&&(oe|=8),m(`Key: ${Q.key}`),await ue(Q.key,Q.code,Q.key.length===1,oe)},z=async Q=>{if(Q.key==="Enter"){if(Q.nativeEvent.isComposing)return;if(f){const de=f;v(""),m(`IME Sent: ${de}`);try{const oe=await e("input_type",{text:de});oe!=null&&oe.success||s(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){s(`❌ IME error: ${oe.message}`)}}else m("Key: Enter"),await ue("Enter","Enter",!1)}};o.useEffect(()=>{const Q=c.current;if(!Q)return;const de=oe=>{var ge;if((ge=u.current)!=null&&ge.contains(oe.target)){oe.preventDefault();const fe=Date.now();if(fe-H.current<40)return;H.current=fe;const D=_e(oe.clientX,oe.clientY);if(!D)return;m(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return Q.addEventListener("wheel",de,{passive:!1}),()=>Q.removeEventListener("wheel",de)},[e]);const{cursorPos:le,handleToggleInputMode:Z,handleZoomReset:ie}=Rl({containerRef:c,viewportRef:l,imgRef:u,inputMode:j,setInputMode:k,minZoom:$e,zoomRef:G,panXRef:A,panYRef:$,setPanX:W,setPanY:C,setZoom:M,lastWheelTimeRef:H,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:ee,clampPan:me,isMobile:g,mobileFillZoom:y});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:re,onContextMenu:Q=>Q.preventDefault(),onFocus:()=>N(!0),onBlur:()=>N(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[O?t.jsx("img",{ref:u,src:O,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${I}) translate(${T}%, ${R}%)`,transformOrigin:"center center",cursor:j==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:se,onContextMenu:Q=>Q.preventDefault(),onDragStart:Q=>Q.preventDefault()}):t.jsx(Ll,{waitingLabel:X,waitingHint:je,transportType:i}),j==="mouse"&&O&&t.jsx(Tl,{cursorPos:le,viewportRef:l,imgRef:u}),L.map(Q=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Q.type];return t.jsxs("div",{style:{position:"absolute",left:Q.x,top:Q.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 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(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Q.id)})]}),t.jsx(Ml,{inputMode:j,onToggleInputMode:Z,isImeOpen:w,setIsImeOpen:_,isMenuOpen:S,setIsMenuOpen:h,imeText:f,setImeText:v,handleImeSubmit:z,isConnActive:B,zoom:I,isMobile:g,mobileFillZoom:y,onZoomOut:()=>M(Q=>Math.max(.5,Q-.25)),onZoomReset:ie,onZoomIn:()=>M(Q=>Math.min(5,Q+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),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 Ur(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const p=Math.floor(u/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Vo=e=>Ur(e);function Pl(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Rs(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function zr(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Pl(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return s}function Mr(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 Xn(e,s,r){var L,d;const n=Mr(e,s),a=Rs(e),i=e.sessionId&&((L=r==null?void 0:r.notificationStateBySessionId)==null?void 0:L.get(e.sessionId))||((d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(e.tabKey)),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,p=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||p,f=n.inboxBucket==="working"||u,N=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:N,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":N?"task_complete":"idle"}}function Dl(e,s,r){return Xn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Go({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Rs(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(ds,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const p=c(l).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),f=/^(reject|deny|delete|remove|abort)/.test(p),v=r===l,N=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:N,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${N&&!v?"opacity-40":"opacity-100"} ${N?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?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:v?"⏳ ...":c(l)},u)})})]})]})}var El=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function $l(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if($l(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":El.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 qo(e){return jt(e)==="generating"}function nt(e){return e?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"IDE"}function Bl(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 a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function rn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Fr(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function Kl(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 Wl(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Ol(e){return Kl(e.trim().replace(/\.local$/i,""))}function Hl(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Yo(e,s={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Wl(c));if(r&&r!=="Unknown")return Ol(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Ct(e,s={}){return Hl(e)||Yo(e,s)}function Xo(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 Qo(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function us(e,s){return Xo(e).join(" · ")}function Xs(e){return e.transport==="pty"}function ws(e){return e.transport==="acp"}function Ul(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:nt(e)}function Ea(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=nt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function zl(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Fl(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 a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(a),c=jt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function Vl(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 Gl(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&&Vl(s.receivedAt)||0}function ql(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Mn(e){return Math.max(ql(e),Gl(e.activeChat))}function Yl(e,s,r,n,a,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Qn(e,s){return Yl(Mn(e),Mn(s),Ct(e,{fallbackId:e.id}),Ct(s,{fallbackId:s.id}),e.id,s.id)}const Jo="adhdev_notification_prefs",$a={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Xl(){try{const e=localStorage.getItem(Jo);if(e){const s=JSON.parse(e);return{...$a,...s}}}catch{}return{...$a}}function Ql(e){try{localStorage.setItem(Jo,JSON.stringify(e))}catch{}}let Wt=Xl(),wr=[];function Jl(){wr.forEach(e=>e())}function Zl(e){Wt={...Wt,...e},Ql(Wt),Jl()}function ed(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return wr.push(r),()=>{wr=wr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Zl(r)},[]);return[{...Wt},s]}function Us(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const td={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function sd(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Zo(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;async function rd(){if(Jt!==null)return Jt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Jt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Jt=!!await e.pushManager.getSubscription(),Jt):(Jt=!1,!1)}catch{return Jt=!1,!1}}function Ln(e,s,r){if(Zo())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 nd(e,s={}){const r={...td,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{rd().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Ln(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!Zo())&&Us("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,jt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=jt(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&Us("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const v=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,v.slice(0,120),`approval-${u.id}`)}r.onComplete&&Us("completion")&&qo(p)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&m==="error"&&p!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const ad=/^(run|approve|accept|yes|allow|always)/,od=/^(run|approve|accept|yes|allow|always|proceed|save)/,id=/^(reject|deny|delete|remove|abort|cancel|no)/;function Jn(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function cd(e){const s=Jn(e).toLowerCase();return ad.test(s)?"primary":id.test(s)?"danger":"default"}function ld(e){return od.test(Jn(e).toLowerCase())?"approve":"reject"}function dd(e){return e.map((s,r)=>({label:Jn(s),variant:cd(s),action:ld(s),button:s,buttonIndex:r}))}function ud(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(a=>`[${a}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
28
|
-
${n}`}function md(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function pd(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class fd{constructor(){ft(this,"dedupMap",new Map);ft(this,"DEDUP_WINDOW_MS",5e3);ft(this,"DEDUP_MAX_SIZE",50);ft(this,"DEDUP_CLEANUP_AGE_MS",1e4);ft(this,"toastCallbacks",[]);ft(this,"systemMessageCallbacks",[]);ft(this,"clearSystemMessageCallbacks",[]);ft(this,"resolveActionFn",null);ft(this,"viewRequestRespondFn",null);ft(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 a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,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[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.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(a=>(a==null?void 0:a.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),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(u==null?void 0:u.type)||"";let m=nt(p);const f=this.resolveOwningDaemon(s);if(f){const b=Ct(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let v="",N="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";v=`✅ ${m} agent task completed${b}`,N="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(v=`⚡ ${m} approval needed`,N="warning",n&&!((L=s.modalButtons)!=null&&L.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:ud(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const S=this.resolveActionFn,h=dd(s.modalButtons).map(g=>({label:g.label,variant:g.variant,onClick:()=>{S(b,"resolve_action",{action:g.action,button:g.button,buttonIndex:g.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),w=md(m,s.modalMessage,v),_=Date.now();this.emitToast({id:_,message:w,type:N,timestamp:_,targetKey:n||b,actions:h,duration:15e3}),v=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";v=`⚠️ ${m} agent is taking a long time${b}`,N="warning",Us("browser")&&!document.hasFocus()&&Ln(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",S=s.requestId,h=s.orgId;if(v=`👁️ ${b} wants to view your session`,N="warning",S&&h&&this.viewRequestRespondFn){const w=Date.now(),_=pd(h,S,this.viewRequestRespondFn,(g,j)=>console.error(`[EventManager] ${g} view request failed:`,j));this.emitToast({id:w,message:v,type:N,timestamp:w,actions:_,duration:3e4}),v=""}Us("browser")&&!document.hasFocus()&&Ln("👁️ View Request",`${b} wants to view your session`,`view-request-${S}`)}else s.event==="team:view_request_approved"?(v="✅ View request approved",N="success"):s.event==="team:view_request_rejected"&&(v=`❌ ${s.targetName||"Team member"} declined your view request`,N="warning");if(v){const b=Date.now();this.emitToast({id:b,message:v,type:N,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const it=new fd,Ba=new Map;function Cs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ei(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function xd(e){return!Cs(e)||!Cs(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function ir(e){return!Cs(e)||!Cs(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Es(e){if(!(!Cs(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function cr(e){return Cs(e)&&e.success===!1}function hd(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function bd(e,s){return e&&ei(e.currentValue)?e.currentValue:s}function jr(e,s){return e.options||s[e.id]||[]}function nn(e,s){return{value:s}}function gd(e,s,r){var a;return r?((a=jr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const yd={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function vd({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=_t(),u=`${e}:${s||n}`,p=yd[n]||"#94a3b8",[m,f]=o.useState({}),v=o.useRef(0),N={};for(const R of i||[])R.defaultValue!==void 0&&(N[R.id]=R.defaultValue);const L={...N,...c||{},...Date.now()<v.current?m:{}};o.useEffect(()=>{c&&Date.now()>v.current&&f({})},[c]);const[d,b]=o.useState(Ba.get(u)||{}),[S,h]=o.useState(null),[w,_]=o.useState(null),g=o.useCallback(async(R,C={})=>{const H={...C,...s&&{targetSessionId:s}};return await l(e,R,H)},[e,s,l]),j=o.useCallback(async(R,C={})=>{const H=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await g("invoke_provider_script",{...H,scriptName:R,...C})},[g,n,r,s]),k=o.useCallback((R,C,H)=>{const G=bd(H,C);f(A=>({...A,[R.id]:G})),hd(H==null?void 0:H.effects)},[]),y=o.useCallback((R,C)=>{f(H=>{const G={...H};return C===void 0?delete G[R.id]:G[R.id]=C,G}),v.current=0},[]);if(!i||i.length===0)return null;const x=i.filter(R=>R.placement==="bar"&&R.hidden!==!0).sort((R,C)=>(R.order??50)-(C.order??50));if(x.length===0)return null;const E=async R=>{if(S===R.id){h(null);return}if(jr(R,d).length>0){h(R.id);return}if(R.dynamic&&R.listScript){_(R.id);try{const H=await j(R.listScript,{}),G=xd(H);if(!G){const $=Es(H);$&&it.showToast($,"warning");return}const A=G.options;if(b($=>{const B={...$,[R.id]:A};return Ba.set(u,B),B}),ei(G.currentValue)){const $=G.currentValue;f(B=>({...B,[R.id]:$}))}h(R.id)}catch(H){const G=H instanceof Error?H.message:`Could not load ${R.label}`;it.showToast(G,"warning")}finally{_(null)}}},I=async(R,C)=>{h(null);const H=(c==null?void 0:c[R.id])??N[R.id];f(G=>({...G,[R.id]:C})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const G=await j(R.setScript,nn(R,C)),A=ir(G);if(A&&!A.ok||cr(G))throw new Error((A==null?void 0:A.error)||Es(G)||`Could not update ${R.label}`);k(R,C,A)}catch(G){y(R,H);const A=G instanceof Error?G.message:`Could not update ${R.label}`;it.showToast(A,"warning")}},M=async R=>{const C=jr(R,d).map(O=>O.value);if(C.length===0)return;const H=String(L[R.id]||""),A=(C.indexOf(H)+1)%C.length,$=C[A];if(typeof $!="string")return;const B=(c==null?void 0:c[R.id])??N[R.id];f(O=>({...O,[R.id]:$})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const O=await j(R.setScript,nn(R,$)),X=ir(O);if(X&&!X.ok||cr(O))throw new Error((X==null?void 0:X.error)||Es(O)||`Could not update ${R.label}`);k(R,$,X)}catch(O){y(R,B);const X=O instanceof Error?O.message:`Could not update ${R.label}`;it.showToast(X,"warning")}},T=async R=>{const H=!L[R.id],G=(c==null?void 0:c[R.id])??N[R.id];f(A=>({...A,[R.id]:H})),v.current=Date.now()+5e3;try{if(!R.setScript)return;const A=await j(R.setScript,nn(R,H)),$=ir(A);if($&&!$.ok||cr(A))throw new Error(($==null?void 0:$.error)||Es(A)||`Could not update ${R.label}`);k(R,H,$)}catch(A){y(R,G);const $=A instanceof Error?A.message:`Could not update ${R.label}`;it.showToast($,"warning")}},W=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const H=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(A=>typeof A=="string"&&A.trim().length>0);if(!window.confirm(H.join(`
|
|
29
|
-
|
|
30
|
-
`)))return}const C=(c==null?void 0:c[R.id])??N[R.id];try{const H=await j(R.invokeScript),G=ir(H);if(G&&!G.ok||cr(H))throw new Error((G==null?void 0:G.error)||Es(H)||`Could not run ${R.label}`);G&&k(R,C??!0,G)}catch(H){y(R,C);const G=H instanceof Error?H.message:`Could not run ${R.label}`;it.showToast(G,"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:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),x.map(R=>{const C=String(L[R.id]||""),H=gd(R,d,C),G=S===R.id,A=w===R.id,$=jr(R,d);switch(R.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:G?`${p}55`:"transparent",border:"1px solid",color:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>E(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),A?"...":H||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>h(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:R.label.toUpperCase()}),$.map(B=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:B.value===C?`${p}18`:"transparent",color:B.value===C?p:"var(--text-secondary)",fontWeight:B.value===C?600:400,borderLeft:B.value===C?`2px solid ${p}`:"2px solid transparent"},title:B.description||B.label,onMouseEnter:O=>{O.currentTarget.style.background=`${p}12`},onMouseLeave:O=>{O.currentTarget.style.background=B.value===C?`${p}18`:"transparent"},onClick:()=>I(R,B.value),children:B.label},B.value))]})]})]},R.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:C?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),title:`Click to cycle: ${$.map(B=>B.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),H||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},R.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:C?`${p}44`:"transparent",background:C?`${p}14`:"var(--surface-tertiary)",color:C?p:"var(--text-muted)"},onClick:()=>T(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.label]},R.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:()=>W(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&C?`${R.label}: ${C}`:R.label]},R.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:C?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),C?`${R.label}: ${C}`:R.label]},R.id);default:return null}})]})}const wd=o.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:a,isActive:i=!0}){const c=o.useRef(null),[l,u]=o.useState("");o.useEffect(()=>{u("")},[s]),o.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const p=()=>{const m=l.trim();!m||n||(u(""),a(m))};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:m=>u(m.target.value),onPaste:m=>{const f=m.clipboardData.getData("text");f&&u(v=>v+f),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),p()}},onBlur:m=>{if(window.innerWidth<768){const f=m.relatedTarget;if((f==null?void 0:f.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:p,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"})})})]})})}),Ze=e=>e.transport==="pty",Is=(e,s)=>Ze(e)?e.mode||"terminal":"chat",ti=(e,s)=>Ze(e)&&Is(e)==="terminal",qe=e=>e.transport==="acp";function Vt(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 si(e){return e.machineName||""}function Lr(e){return qt(e)}function Lt(e){return e.agentType||""}function _r(e){return e.hostIdeType||""}function Zn(e){return e.displayPrimary||e.agentName||"Agent"}function ri(e){return[e.displaySecondary,si(e)].filter(Boolean)}function ms(e){return e.agentName||nt(Lt(e))}function jd(e){var s,r;if(!Vt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return nt(_r(e)||Lt(e))}function ea(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Ka(e){return Vt(e)?"native":e.tabKey}function kd(e){return e.sessionId}function Nd(e,s){if(s)return Vt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Sd(e,s){const r=Lt(e),n=Vt(e),a=Ze(e)||qe(e),i=n?a?ms(e)||(s==null?void 0:s.cliName)||nt(_r(e)||r):s!=null&&s.type?nt(s.type):nt(_r(e)||r):ms(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:qe(e),isCliTerminal:ti(e),providerType:r,displayLabel:i,targetEntry:Nd(e,s)}}function ni({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ls(),c=qt(e),l=si(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,m=!p&&(e.transport==="pty"||e.transport==="acp"),f=ms(e),v=jd(e),N=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),L=o.useCallback(()=>{if(r){r();return}const d=ea(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:L,title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]}):t.jsxs("span",{className:"conversation-meta-chip",title:v,children:[t.jsx(It,{size:12}),t.jsx("span",{children:v})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}))]})}function Wa(e,s){return`${e}:${s}`}function Cd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function lr(e,s){Cd()&&console.debug(`[subscription-manager] ${e}`,s)}class Id{constructor(){ft(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=Wa(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const m={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,m),lr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var v;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};lr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=s.sendData)==null||v.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=Wa(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,cs.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),cs.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;lr("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 a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);lr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const Gt=new Id;function Ad(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function Td(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,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,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 dr(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,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Ad(e.activeChat,s==null?void 0:s.activeChat),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 Md(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else s.push(n);return{topLevel:s,childrenByParent:r}}function Rr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:m}=Md(u),f=Td(i,n),v=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,N=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),L=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...v&&{machine:v,platform:v.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:N.some(b=>!!b.cdpConnected)});for(const b of N){const S=f.get(b.id),h=dr(b,S),w=(m.get(b.id)||[]).map(_=>dr(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(S==null?void 0:S.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:h.workspace,terminals:0,childSessions:w,agents:w.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of L){const S=f.get(b.id),h=dr(b,S);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(S==null?void 0:S.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:h.mode||(S==null?void 0:S.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const S=f.get(b.id),h=dr(b,S);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(S==null?void 0:S.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const an=new Map,on=new Map,cn=new Set,zs=new Map,Ld=1200;function _d(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 a=n.status;if(a&&typeof a=="object")return a}return s}function Oa(e,s){const r=zs.get(e);!r||r.size===0||(zs.delete(e),r.forEach(n=>n(s)))}function Rd(e,s){return new Promise(r=>{const n=zs.get(e)||new Set;zs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&zs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function er(){const{sendCommand:e,sendData:s}=_t(),{injectEntries:r,getIdes:n}=Tr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=on.get(a)||0;if(!(i!=null&&i.force)&&cn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=an.get(a);if(u)return u;const p=(async()=>{if(s&&!cn.has(a)&&(cn.add(a),Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),S=b.find(w=>w.id===a),h=Rr(d.status,{daemonId:a,existingDaemon:S,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),on.set(a,Date.now()),Oa(a,!0)}),!(i!=null&&i.force)&&await Rd(a,Ld)))return;const m=await e(a,"get_status_metadata"),f=_d(m);if(!f)return;const v=n(),N=v.find(d=>d.id===a),L=Rr(f,{daemonId:a,existingDaemon:N,existingEntries:v,timestamp:f.timestamp||Date.now()});L.length>0&&r(L,{authoritativeDaemonIds:[a]}),on.set(a,Date.now()),Oa(a,!0)})().finally(()=>{an.delete(a)});return an.set(a,p),p},[n,r,e,s])}function Ut(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function ta(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 a=Ss(e.content),i=Ss(s.content);if(!a||a!==i)return!1;const c=Ut(e),l=Ut(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function Ha(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Ut(e)&&(s+=1),s}function As(e){return Ss(e==null?void 0:e.content)}function _n(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function Pd(e,s){const r=As(e),n=As(s);return!r||!n||r===n?null:_n(r,n)?e:_n(n,r)?s:null}function Dd(e,s){const r=Pd(e,s);if(r)return r;const n=Ha(e),a=Ha(s);return a!==n?a>n?s:e:As(s).length>=As(e).length?s:e}function Qs(e){const s=[];for(const r of e){const n=s.findIndex(a=>ta(a,r));if(n>=0){s.splice(n,1,Dd(s[n],r));continue}s.push(r)}return s}function Ed(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:Qs([...r,...n])}function Ua(e){return[...e].sort((s,r)=>{const n=Ut(s),a=Ut(r);return n&&a&&n!==a?n-a:0})}function za(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const a=r.findIndex(i=>ta(i,n));return a>=0?(r.splice(a,1),!1):!0})}function $d(e,s){return e.filter(r=>{const n=As(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Ut(r);return!s.some(c=>{if(ta(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=As(c);if(!_n(u,n)&&u!==n)return!1;const p=Ut(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const Bd=60,Kd=200;function Wd(e={}){return e.isCliLike?Kd:Bd}function Od(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Hd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Fa(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 ai(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return Hd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function Ud(e){return{knownMessageCount:e.length,lastMessageSignature:ai(e[e.length-1])}}function zd(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Qs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Qs([...e.slice(0,n),...r])}case"full":default:return r}}const Va=60;function Rn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:a,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:u=!1,scrollToBottomRequestNonce:p,isInputActive:m=!0}){var _e,ae;const f=o.useRef(new Map),v=o.useRef(new Map),N=o.useRef(new Map),{sendCommand:L,sendData:d}=_t(),b=er();Zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const S=rt.useMemo(()=>Rs(e),[e.status,e.connectionState]),h=o.useMemo(()=>Sd(e,s),[e,s]),w=Wd({isCliLike:h.isCli||h.isAcp}),_=o.useRef(new Map),g=o.useCallback(ee=>(_.current.has(ee)||_.current.set(ee,{messages:[],offset:0,hasMore:!0,error:null,visibleLiveCount:w}),_.current.get(ee)),[w]),j=o.useCallback((ee,se)=>{const ue=g(ee);_.current.set(ee,{...ue,...se}),k(re=>re+1)},[g]),[,k]=o.useState(0),y=e.tabKey,x=g(y),E=x.messages,I=x.hasMore,M=x.error,T=v.current.get(y),W=Ed(T,e.messages);o.useEffect(()=>{x.visibleLiveCount>=w||j(y,{visibleLiveCount:w})},[w,x.visibleLiveCount,y,j]);const R=Math.max(0,W.length-x.visibleLiveCount),C=Zn(e),H=Lr(e),G=e.sessionId||"",A=e.providerSessionId||G,[$,B]=o.useState(!1);o.useEffect(()=>{const ee=h.targetEntry;H&&(!ee||ee.providerControls===void 0||ee.controlValues===void 0)&&b(H,{minFreshMs:3e4}).catch(()=>{})},[H,h.isAcp,(_e=h.targetEntry)==null?void 0:_e.providerControls,(ae=h.targetEntry)==null?void 0:ae.controlValues,b]),o.useEffect(()=>{if(!H||!G||!d)return;const ee=v.current.get(y)||[],se=N.current.get(y),ue=se&&se.knownMessageCount?se:Ud(ee),re=`daemon:${H}:session:${G}`;return Gt.subscribe({sendData:d},H,{type:"subscribe",topic:"session.chat_tail",key:re,params:{targetSessionId:G,historySessionId:A,knownMessageCount:ue.knownMessageCount,lastMessageSignature:ue.lastMessageSignature,...ue.knownMessageCount?{}:{tailLimit:Va}}},le=>{const Z=v.current.get(y)||[],ie=zd(Z,le),Q=Math.max(ie.length,Number(le.totalMessages||0));N.current.set(y,{knownMessageCount:Q,lastMessageSignature:typeof le.lastMessageSignature=="string"?le.lastMessageSignature:ai(ie[ie.length-1])}),Fa(Z)!==Fa(ie)&&(v.current.set(y,ie),cs.record({interactionId:le.interactionId,kind:"dashboard.chat_tail_applied",topic:"session.chat_tail",payload:{sessionId:G,syncMode:le.syncMode,previousCount:Z.length,nextCount:ie.length}}),k(oe=>oe+1))})},[H,A,d,G,y]);const O=o.useCallback(async()=>{if($)return;const ee=e.tabKey,se=g(ee);if(W.length>se.visibleLiveCount){j(ee,{visibleLiveCount:Math.min(W.length,se.visibleLiveCount+Va),error:null});return}B(!0),j(ee,{error:null});try{const ue=Lr(e);if(!ue){j(ee,{hasMore:!1});return}const re=Lt(e),z=await L(ue,"chat_history",{agentType:re,offset:se.offset,limit:30,targetSessionId:e.sessionId,historySessionId:e.providerSessionId||e.sessionId}),le=Od(z),Z=le.messages||[];if(Z.length>0){const ie=g(ee);j(ee,{messages:[...Z,...ie.messages],offset:ie.offset+Z.length,hasMore:!!le.hasMore})}else j(ee,{hasMore:!!le.hasMore})}catch(ue){const re=(ue==null?void 0:ue.message)||"";re.includes("P2P not available")||re.includes("channel not open")||re.includes("P2P not connected")||re.includes("timeout")?j(ee,{error:"Connection not ready — tap to retry"}):j(ee,{hasMore:!1,error:"Failed to load history"})}finally{B(!1)}},[$,e,W.length,L,g,j]),{allMessages:X,receivedAtMap:je}=o.useMemo(()=>{const ee=R>0?W.slice(-x.visibleLiveCount):W;if(E.length===0){const z=Ua(Qs(ee)),le={};return z.forEach((Z,ie)=>{const Q=`${e.tabKey}:${vs(Z,ie)}`;let de=Ut(Z)||f.current.get(Q)||0;de||(de=Date.now(),f.current.set(Q,de)),le[vs(Z,ie)]=de}),{allMessages:z,receivedAtMap:le}}const se=$d(E,ee),ue=Ua(Qs([...se,...ee])),re={};return ue.forEach((z,le)=>{const Z=`${e.tabKey}:${vs(z,le)}`;let ie=Ut(z)||f.current.get(Z)||0;ie||(ie=Date.now(),f.current.set(Z,ie)),re[vs(z,le)]=ie}),{allMessages:ue,receivedAtMap:re}},[e.tabKey,R,E,W,x.visibleLiveCount]),$e=o.useMemo(()=>c.filter(ee=>ee.routeId===e.tabKey).sort((ee,se)=>ee.timestamp-se.timestamp),[c,e.tabKey]),me=o.useMemo(()=>{if(W.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((S.isGenerating||e.status==="streaming")&&B(!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(Ys,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ns,{size:14})," Open ",C," 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(Ko,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ns,{size:14})," Open ",C," 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"&&!$)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,a,i,$,W.length,C,S.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[u&&t.jsx(ni,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Sl,{messages:X,actionLogs:$e,agentName:ms(e)||C||"Agent",userName:l,isCliMode:h.isCli||h.isAcp,isWorking:S.isGenerating,contextKey:e.tabKey,receivedAtMap:je,onLoadMore:O,isLoadingMore:$,hasMoreHistory:I,hiddenLiveCount:R,loadError:M??void 0,emptyState:me,scrollToBottomRequestNonce:p}),m&&!h.isCliTerminal&&(()=>{var ee,se;return t.jsx(vd,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(ee=h.targetEntry)==null?void 0:ee.providerControls,controlValues:(se=h.targetEntry)==null?void 0:se.controlValues})})(),!h.isCliTerminal&&t.jsx(wd,{contextKey:e.tabKey,panelLabel:C,isSending:n,onSend:r,isActive:m})]})}let oi=ls;function ii(){return oi()}class Fd{constructor(){ft(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(a=>a(...r))}}let ci=new Fd;class Vd{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){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 mt=new Vd;function Gd(e){e.dashboardWS&&(ci=e.dashboardWS),e.connectionManager&&(mt=e.connectionManager),e.useDaemonsHook&&(oi=e.useDaemonsHook)}function ct(e){return Zn(e)}function ps(e){return ri(e).join(" · ")}function li(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=Ss(s==null?void 0:s.content);return r||(e.title?e.title:ps(e)||"No messages yet")}function di(e,s){const{isReconnecting:r,isConnecting:n}=Rs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function qd(e,s){const r=["Chat",...ri(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return di(e)||ps(e)}function Yd(e){return`${ct(e)} · ${li(e)}`}function Xd(e){const s=_r(e),r=s?nt(s):ms(e);return`${ct(e)} — ${r||"Agent"}`}function Qd(e){return ms(e)||"CLI"}function ui(e){return e.title||ms(e)||e.routeId}function mi(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function Jd({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,isVisible:i=!0}){var $;const{ides:c}=ls(),l=o.useRef(null),{sendCommand:u,sendData:p}=_t(),[m,f]=o.useState(""),[v,N]=o.useState(!1),[L,d]=o.useState(1),b=o.useRef(!1),S=o.useRef(0),h=o.useRef(!1),w=o.useRef(""),_=o.useRef(null),g=o.useRef(!1),j=o.useRef(null),k=e.tabKey,y=e.sessionId||"",x=e.daemonId||(($=e.routeId)==null?void 0:$.split(":")[0])||e.routeId||"",E=c.find(B=>B.id===x&&B.type==="adhdev-daemon"),I=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",M=.6,T=1.15,W=()=>{if(typeof window>"u")return 1;const B=window.innerWidth||0;return B<=360?.68:B<=390?.74:B<=430?.82:B<=480?.9:1},R=()=>{var B,O;S.current=0,h.current=!1,w.current="",_.current=null,g.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),N(!1),(O=(B=r.current)==null?void 0:B.reset)==null||O.call(B)},C=()=>{var B,O;S.current=0,h.current=!1,w.current="",_.current=null,g.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),N(!0),(O=(B=r.current)==null?void 0:B.reset)==null||O.call(B)},H=()=>{var O;if(j.current=null,!i)return;const B=w.current;B&&(w.current="",(O=r.current)==null||O.write(B))},G=B=>{B&&(w.current+=B,i&&j.current===null&&(j.current=requestAnimationFrame(H)))},A=(B,O=0,X,je)=>{var $e,me,_e,ae,ee;O>0&&S.current>=O||O===0&&h.current||(S.current=O,N(!0),typeof X=="number"&&typeof je=="number"&&X>0&&je>0&&((me=($e=r.current)==null?void 0:$e.resize)==null||me.call($e,X,je)),(ae=(_e=r.current)==null?void 0:_e.reset)==null||ae.call(_e),B&&((ee=r.current)==null||ee.write(B)))};return o.useEffect(()=>{R()},[y]),o.useEffect(()=>{var O;if(!y)return;const B=((O=mt.onRuntimeEvent)==null?void 0:O.call(mt,y,X=>{if(!(!X||X.sessionId!==y)){if(X.type==="runtime_snapshot"){if(!i){_.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}A(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){h.current=!0,typeof X.seq=="number"&&(S.current=Math.max(S.current,X.seq)),v||N(!0),typeof X.data=="string"&&G(X.data);return}if(X.type==="session_cleared"){if(!i){g.current=!0,w.current="",_.current=null;return}C()}}}))||(()=>{});return()=>{B()}},[x,y,r,i,v]),o.useEffect(()=>{var O,X,je;if(!y)return;x&&((O=mt.getState)==null?void 0:O.call(mt,x))==="connected"&&(N(!0),(X=mt.requestRuntimeSnapshot)==null||X.call(mt,x,y).catch(()=>{}));const B=(je=mt.onStateChange)==null?void 0:je.call(mt,($e,me)=>{var _e;$e!==x||me!=="connected"||(N(!0),(_e=mt.requestRuntimeSnapshot)==null||_e.call(mt,x,y).catch(()=>{}))});return()=>{B==null||B()}},[x,y,r]),o.useEffect(()=>{s&&R()},[s,k,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const B=()=>{b.current||d(W())};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),o.useEffect(()=>{var O;if(!i){(O=l.current)==null||O.blur();return}g.current&&(g.current=!1,C());const B=_.current;B&&(_.current=null,A(B.text,B.seq,B.cols,B.rows)),w.current&&j.current===null&&(j.current=requestAnimationFrame(H)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const B=O=>{var je;const X=O.detail;X!=null&&X.sessionId&&X.sessionId!==y||v&&((je=r.current)==null||je.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[v,y,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(B=>Math.max(M,Number((B-.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(B=>Math.min(T,Number((B+.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(zo,{ref:r,readOnly:!v||!i,sizingMode:I,onInput:B=>{v&&(p!=null&&p(x,{type:"pty_input",sessionId:y,targetSessionId:y,data:B})||u(x,"pty_input",{targetSessionId:y,data:B}).catch(console.error))}})})}),!v&&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 ${ct(e)}...`,value:m,disabled:!v||!i||a,onChange:B=>f(B.target.value),onPaste:B=>{const O=B.clipboardData.getData("text");O&&f(X=>X+O),B.preventDefault()},onKeyDown:B=>{if(B.key!=="Enter")return;if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault();const O=m.trim();!v||!O||a||(f(""),n(O))},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 B=m.trim();!v||!B||a||(f(""),n(B))},disabled:!v||!i||!m.trim()||a,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{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:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function Zd({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",a=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[a],borderBottom:c[a],color:l[a]},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 eu({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"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:u,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 sa({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(Or,{size:n}):t.jsx(Ht,{size:n})})}function Ga({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function qa({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Ur(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function tu({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:v,onShowAllHidden:N,onResetPanelsToMain:L,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:S,onHiddenOpenChange:h,onOpenNewSession:w,actionShortcuts:_,notifications:g,notificationUnreadCount:j,onOpenNotification:k,onMarkNotificationRead:y,onMarkNotificationUnread:x,onDeleteNotification:E}){const{ides:I,p2pStates:M={}}=ls(),T=!!e&&Ze(e)&&!qe(e),W=!!e&&qe(e),R=u||(e?ti(e)?"terminal":"chat":null),[C,H]=o.useState(!1),G=o.useRef(null),A=o.useRef(null),$=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",B=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",O=I.filter(z=>z.type==="adhdev-daemon"),X=Object.values(M),je=X.filter(z=>z==="connected").length,$e=X.filter(z=>z==="connecting"||z==="new"||z==="checking").length,_e=r!=="connected"||O.length===0?null:$e>0&&je===0?"P2P connecting...":je>0&&s===0?"Waiting for IDE...":null,ae=o.useMemo(()=>g.filter(z=>!z.readAt),[g]),ee=o.useMemo(()=>g.filter(z=>!!z.readAt),[g]),se=o.useMemo(()=>ae.slice(0,9),[ae]),ue=j;o.useEffect(()=>{if(!d)return;const z=le=>{var Z;(Z=G.current)!=null&&Z.contains(le.target)||b(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,b]),o.useEffect(()=>{if(!S)return;const z=le=>{var Z;(Z=A.current)!=null&&Z.contains(le.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[S,h]),o.useEffect(()=>{if(!S&&!d)return;const z=le=>{if(!le.altKey)return;const Z=le.code.match(/^Digit([1-9])$/);if(!Z)return;const ie=Number(Z[1])-1,Q=S?f[ie]:void 0,de=d?se[ie]:void 0;if(!(!Q&&!de)){if(le.preventDefault(),le.stopPropagation(),Q){v==null||v(Q),h(!1);return}de&&(k(de),b(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,S,d,se,h,b,k,v]);const re=z=>{if(!z)return;const le=a.find(Z=>Z.tabKey===z);le&&(m==null||m(le))};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(Ht,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ct(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:B}})})]}),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:B}}),_e&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",_e]}),w&&t.jsx("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(rl,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||W||!qe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ps(e)||ct(e),children:ct(e)}),(T||W)&&l&&t.jsxs(t.Fragment,{children:[T&&p&&R&&t.jsx(sa,{mode:R,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:W?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(kt,{size:14})})]}),!qe(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Gn,{size:14})}),!T&&!qe(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:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:A,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),H(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",H(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||H(!1)},onDrop:z=>{const le=z.dataTransfer.getData("text/tab-key");z.preventDefault(),H(!1),re(le)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!S),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${_!=null&&_.toggleHiddenTabs?` (${_.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Wo,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),S&&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(Ga,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[L&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:L,children:"Reset panels"}),f.length>0&&N&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{N(),h(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(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(Ga,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(z=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{v==null||v(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(z)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(z)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(z)+1]}):null,ps(z)]})]},z.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Hr,{size:16}),ue>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ae.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ae.map(z=>t.jsx(qa,{notification:z,shortcutIndex:se.indexOf(z)>=0?se.indexOf(z)+1:void 0,onOpen:()=>k(z),onMarkRead:()=>y(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),ee.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ee.map(z=>t.jsx(qa,{notification:z,onOpen:()=>k(z),onMarkRead:()=>y(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),g.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function su(e,s){return String(e||"")!==String(s||"")}function ru(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
31
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Xo(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function nu(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function pi(e,s={}){return nu(ru(e,s),s.sortMode||"recent")}function Pr(e){return e?"Resume saved history":"Start fresh"}function ra(e){return e?"Resuming saved history…":"Starting fresh…"}function au(){return"Start fresh"}function fi(e,s=!1){return e==="cli"?Pr(s):e==="ide"?"Start IDE":"Start ACP session"}function xi(e,s=!1){return e==="cli"?ra(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ou(){return"Recover hosted runtime"}function iu(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function cu(){return"Open saved history"}function lu(){return"Saved History"}function na(){return"Use saved history when you want continuity in the same provider conversation."}function du(){return"No saved history found yet."}function uu(){return"Refresh saved history"}function mu(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(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 Ts(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function aa(e){return`Resume saved history with ${e}?`}function oa(){return"Review or change the target workspace before resuming saved history."}function pu(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 ia({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:v,onResumeSavedSession:N}){var y;const L=s.find(x=>x.id===e.routeId),d=(L==null?void 0:L.chats)||[],b=(y=L==null?void 0:L.activeChat)==null?void 0:y.id,S=Ze(e)&&!qe(e),[h,w]=o.useState(()=>gt()),_=l||h,g=x=>{if(u){u(x);return}w(x)},j=o.useMemo(()=>pi(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),k=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:S?lu():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Xd(e)}),S&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:na()})]}),t.jsx("button",{onClick:p,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 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),S?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:_.textQuery,onChange:x=>g({..._,textQuery:x.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:_.workspaceQuery,onChange:x=>g({..._,workspaceQuery:x.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:_.modelQuery,onChange:x=>g({..._,modelQuery:x.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:_.sortMode,onChange:x=>g({..._,sortMode:x.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:_.resumableOnly,onChange:x=>g({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),j.map(x=>{const E=e.providerSessionId===x.providerSessionId,I=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!N||N(x)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"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 ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:pu(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.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:[x.workspace||"Workspace unknown",us(x.summaryMetadata)?` · ${us(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):d.map(x=>t.jsxs("div",{onClick:()=>{f(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===x.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===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.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:[x.id.substring(0,12),"..."]}),b===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(S&&!i&&j.length===0||!S&&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(il,{size:32})}),t.jsx("div",{className:"text-[13px]",children:S?a.length>0?"No saved history matches these filters.":du():"No recent chat sessions found."})]}),S&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:mu()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:v,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(_s,{size:13})," ",S?uu():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Ya={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 hi({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 a=Ya[n.type]||Ya.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, ${a.accent}, color-mix(in srgb, ${a.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:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.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 fu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function xu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function hu(e){return e.sessionId||e.instanceId||e.agentType}function ln(e,s){return e||s}function Xa(e,s){const r=new Set,n=[];for(const a of s)if(a)for(const i of e[a]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((a,i)=>a.timestamp-i.timestamp)}function bi(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function gi(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function ca(e,s,r={}){return bu(e,s,gi(e,r))}function bu(e,s,r={}){var N,L,d,b,S,h;const n=[],a=r.machineName,i=r.connectionState,c=xu(e),l=Ul(e.type,{agentName:e.cliName}),u=Ze(e)||qe(e)?l:nt(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var _,g;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,transport:w.transport,agentType:w.providerType,agentName:w.providerName||nt(w.providerType),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((_=w.activeChat)==null?void 0:_.messages)||[],activeModal:((g=w.activeChat)==null?void 0:g.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,surfaceHidden:w.surfaceHidden}}):[],m=fu(e),f=e.activeChat||{title:""},v=f.title&&String(f.title).trim()?String(f.title).trim():"";if(m){const w=e.sessionId||e.instanceId,_=l,g=(N=e.activeChat)==null?void 0:N.activeModal,j=g&&Array.isArray(g.buttons)&&g.buttons.length>0,k=jt((L=e.activeChat)==null?void 0:L.status,{activeModal:(d=e.activeChat)==null?void 0:d.activeModal})||jt((S=(b=e.agents)==null?void 0:b[0])==null?void 0:S.status)||"idle",y=e.activeChat||{title:"",messages:[]};let x=y.title&&String(y.title).trim()?String(y.title).trim():"";const E=(h=e.activeChat)==null?void 0:h.id,I=e.chats;if(E&&Array.isArray(I)&&I.length>0){const H=I.find(G=>G.id===E||G.id&&String(G.id)===String(E));H!=null&&H.title&&String(H.title).trim()&&(x=String(H.title).trim())}const M=(Ze(e)||qe(e),e.type),T=(Ze(e)||qe(e))&&Ea(x,_,M)?"":x,W=y.messages||[],R=Xa(s,[e.id,w]),C=za(W,R);n.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,mode:Ze(e)?e.mode||"terminal":"chat",agentName:_,agentType:M,status:k,title:T,messages:[...W,...C],resume:e.resume,hostIdeType:!Ze(e)&&!qe(e)?e.type:void 0,workspaceName:c,displayPrimary:c||T||(Ze(e)?e.mode==="chat"?_:"Terminal":_),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:j?g.buttons:void 0,modalMessage:j?g.message:void 0,streamSource:"native",tabKey:ln(w,e.id),machineName:a,connectionState:i})}if(m&&(Ze(e)||qe(e)))return n;for(const w of p){const _=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,g=zl(w),j=hu(w),k=`${e.id}:${j}`,y=w.title&&String(w.title).trim()||"",x=Ea(y,w.agentName,w.agentType)?"":y,E=w.messages||[],I=Xa(s,[k,w.sessionId,w.instanceId]),M=za(E,I);(w.transport==="cdp-webview"||w.sessionId||w.providerSessionId||E.length>0||M.length>0||_||x||!["idle","panel_hidden","disconnected","not_monitored"].includes(g))&&n.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:g,title:x,messages:[...E,...M],hostIdeType:e.type,workspaceName:c,displayPrimary:c||v||x||u,displaySecondary:`${u} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,modalButtons:_?w.activeModal.buttons:void 0,modalMessage:_?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ln(w.sessionId||w.instanceId,k),machineName:a,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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ln(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function gu(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 yu(e,s){const r=gu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const yi=[{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:"🏄"}],vi=[{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:"🧩"}],wi=[{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:"🟠"}],vu=yi,wu=vi,ju=wi;function fs(...e){return _c(Rc(e))}function ku({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:fs("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})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function ji({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(ku,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:fs("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Dt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:fs("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]",a),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 ki({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:fs("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),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 Nu={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"},Su={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Cu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:fs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Nu[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Su[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 Iu={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"},Au={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Tu({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:fs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Iu[e],r),children:[t.jsx("span",{className:fs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Au[e])}),n]})}const Pn="adhdev:themechange";function Mu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ys(e){return e==="system"?Mu():e}function Ni(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(Pn,{detail:{preference:e,theme:s}}))}function Lu(){const e=gs(),s=ys(e);Ni(s),kr(e,s)}function la(){const[e,s]=o.useState(gs),[r,n]=o.useState(()=>ys(gs()));o.useEffect(()=>{Ni(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),kr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,f=p.theme;s(m==="dark"||m==="light"||m==="system"?m:gs()),n(f==="dark"||f==="light"?f:ys(gs()))},l=u=>{if(u.key!=="theme")return;const p=gs(),m=ys(p);s(p),n(m)};return window.addEventListener(Pn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Pn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ys(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}kr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=ys(l);n(u);try{localStorage.setItem("theme",l)}catch{}return kr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Qa={dark:"Dark",light:"Light",system:"System"};function _u({collapsed:e}){const{preference:s,cycleTheme:r}=la(),n=s==="dark"?t.jsx(ll,{size:16}):s==="light"?t.jsx(cl,{size:16}):t.jsx(dl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Qa[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Qa[s]})]})}function es({label:e,description:s,checked:r,disabled:n,onChange:a,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:()=>a(!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 Ru({onPrefChange:e}){const[s,r]=ed(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Hr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:a=>n("globalEnabled",a)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(es,{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:a=>n("browserNotifications",a)}),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(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ul,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ml,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:a=>n("disconnectAlert",a)})]}),!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 Dr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Pu(e,s){const r=Dr(e),n=Dr(s);if(!r||!n)return e.localeCompare(s);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Si(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Fs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Pu(r,s)>=0)return!1;const n=Dr(r),a=Dr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Du(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function dn(e,s){return e instanceof Error?e.message:s}function Eu({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(ki,{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(Bu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Ja({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return qs.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:a,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 $u(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...vu,...wu,...ju].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Bu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,R;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,v]=o.useState("idle"),[N,L]=o.useState(""),d=e.version||null,b=((W=e.machine)==null?void 0:W.platform)||((R=e.system)==null?void 0:R.platform)||"",S=Ct(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",w=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),g=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),j=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=Du(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(dn(C,"Connection lost during upgrade"))}}},y=async()=>{if(m(null),!!n){v("loading");try{await n(e.id),v("done"),L("Machine disconnected.")}catch(C){v("error"),L(dn(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){v("loading");try{await a(e.id),v("done"),L("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){v("error"),L(dn(C,"Failed to revoke token"))}}},E="0.8.66",I=Si(e,E),M=Fs(e,E),T=w.length+_.length+g.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:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:S}),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:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Tu,{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:[j&&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 ${j.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?"connecting...":j.state||"off"]}),j.peers!==void 0&&j.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(C=>{const H=$u(C.type),G=C.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}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>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:C.cliName||"CLI"})]},C.id)),g.map(C=>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:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||N)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:N||l})]}),p==="disconnect"&&t.jsx(Ja,{title:"🔌 Disconnect Machine",message:`Disconnect "${S}" 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:y,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(Ja,{title:"⚠️ Remove Machine",message:`Remove "${S}" 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:x,onCancel:()=>m(null)})]})}const Ku=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Wu(){const{preference:e,setPreference:s}=la();return t.jsx("div",{className:"flex gap-2",children:Ku.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 Ou(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 Hu(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function un(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Za(e){const{r:s,g:r,b:n}=Hu(e);return .2126*un(s)+.7152*un(r)+.0722*un(n)}function eo(e,s){const r=Za(e),n=Za(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Ci(e){const s=Ou(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return eo(s,r)>=eo(s,n)?r:n}const Dn={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},En={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},Uu=[{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"}}}],Ii="adhdev-chat-theme",Ai="adhdev-chat-theme-custom";function Nr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ii)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Ai);if(s){const r=JSON.parse(s);return{...e==="dark"?Dn:En,...r[e]}}}catch{}return e==="dark"?Dn:En}function ur(e,s){try{localStorage.setItem(Ai,JSON.stringify({dark:e,light:s}))}catch{}}function Tt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function Er(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),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const zu={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,s){var a;const r=(a=zu[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Er(r,24)),n.style.setProperty("--accent-on-primary",Ci(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Er(r,18)})`),n.style.setProperty("--border-accent",Tt(r,.35)),n.style.setProperty("--nav-active-bg",Tt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Tt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Tt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Tt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Tt(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",Tt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Tt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Er(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Ci(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Er(e.accentColor,40)})`),s.style.setProperty("--border-accent",Tt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Tt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Tt(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 ${Tt(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 da(){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 Fu(e){try{localStorage.setItem(Ii,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else da(),Vs(e,as()?"dark":"light")}function Vu(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Nr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else da(),Vs(e,as()?"dark":"light")}function as(){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 $s({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 Gu({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?ur(p,f):ur(f,p),ns(p),s(p),p})},[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($s,{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($s,{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($s,{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($s,{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($s,{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?Dn:En,u=Et(e?"light":"dark");e?ur(c,u):ur(u,c),a(c),ns(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 qu(){const[e,s]=o.useState(Nr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const f=as();n(f);const v=Nr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=as();n(f);const v=Nr();v==="custom"?ns(Et(f?"dark":"light")):Vs(v,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Et(r?"dark":"light")):(da(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=u=>{s(u),Fu(u)},l=[...Uu,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,f=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},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:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&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:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Gu,{dark:r,onColorsChange:u=>i(u)})]})}const Ti="adhdev_mobileDashboardMode_v1";function Mi(){try{return localStorage.getItem(Ti)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Yu(e){try{localStorage.setItem(Ti,e)}catch{}}function Xu(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Mi()==="chat")},[]),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{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),Yu(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function Qu(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 Ju(e,s){const{sendData:r}=_t(),{injectEntries:n,getIdes:a}=Tr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(v=>v.id===u),f=Qu(m,u,p);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Zu=4e3;function Li(e,s){const{sendData:r}=_t(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Gt.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}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Zu):c(!1),()=>{l&&clearTimeout(l),u()}},[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:a}}function em(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function _i(e){const{sendData:s}=_t(),[r,n]=o.useState({});return o.useEffect(()=>{const a=em(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),cs.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 Ri="adhdev_hiddenTabs";function tm(){try{const e=localStorage.getItem(Ri);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function hs(e){try{localStorage.setItem(Ri,JSON.stringify([...e]))}catch{}}function sm(){const[e,s]=o.useState(tm),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),hs(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),hs(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),hs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return hs(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const v=new Set(f);for(const N of m)v.add(N);return hs(v),v})},[]),l=o.useCallback((p,m)=>{s(f=>{const v=new Set(f);for(const N of m)v.delete(N);return hs(v),v})},[]),u=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function to(e,s){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=s[r];return!n||e.mode===n?e:{...e,mode:n}}function rm(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=to(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>to(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Pi(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function nm(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))Pi(s,a)===i&&(delete n[a],r=!0);return r?n:e}function am({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{sd()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:ui(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return nd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,f]of Object.entries(l))u-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function om(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 os(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||om(s==null?void 0:s.receivedAt)||0}function $n(e,s=0){return os(e)||e.lastUpdated||s||0}function Di(e){return os(e)||e.lastUpdated||0}function Ei(e,s,r=Di){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;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 Bn(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 im(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Bn(e)&&!e.title.trim()}function cm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Bn(r))-Number(Bn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Ei(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,a=r.filter(c=>c.streamSource==="agent-stream"),i=cm(a);return n?i&&im(n)?i:n:i||r[0]||null}function lm(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function mn(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 so(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Ss(r.content).slice(0,240):"";return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function dm(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastUpdated||""),so(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),so(r.activeChat)].join(":"))].join("|")}function um(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function mm(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 a of e.childSessions||[]){const i=a.id||a.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:a.id,ref:s[a.id]})}return r}function pm(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 fm(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function xm(e){const s=fm(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=Ss(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function hm({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>lm(e),[e]),c=o.useMemo(()=>bi(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),v=o.useMemo(()=>{const g=new Map,j=[];for(const E of i){const{connectionState:I="new",machineName:M}=gi(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=mm(E,r),W=dm(E),R=m.current.get(E.id);if(R&&R.ide===E&&R.sourceSignature===W&&R.connectionState===I&&R.machineName===M&&pm(R.localRefs,T)){g.set(E.id,R),j.push(...R.conversations);continue}const C=ca(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),H={ide:E,sourceSignature:W,connectionState:I,machineName:M,localRefs:T,conversations:C};g.set(E.id,H),j.push(...C)}m.current=g;const k=new Map,y=E=>{const I=xm(E),M=f.current.get(E.tabKey);if(M&&M.signature===I)return k.set(E.tabKey,M),M.timestamp;const T={signature:I,timestamp:Di(E)||(M==null?void 0:M.timestamp)||0};return k.set(E.tabKey,T),T.timestamp},x=[...j].sort((E,I)=>Ei(E,I,y));return f.current=k,x},[i,r,s,c]),N=o.useMemo(()=>{const g=um(v,n);return mn(l.current,g)?l.current:(l.current=g,g)},[v,n]),L=o.useMemo(()=>{const g=new Map,j=Array.from(new Set(N.map(k=>k.routeId)));for(const k of j){const y=Bt(N,k);y&&g.set(k,y)}return g},[N]),d=o.useMemo(()=>{const g=new Map;for(const j of N)if(j.sessionId&&g.set(j.sessionId,j),j.streamSource==="native"&&j.sessionId){const k=L.get(j.routeId);k&&g.set(j.sessionId,k)}return g},[N,L]),b=o.useMemo(()=>{const g=new Map;for(const j of N)j.sessionId&&g.set(j.sessionId,j),g.set(j.routeId,L.get(j.routeId)||j),g.set(j.tabKey,j);return g},[N,L]),S=o.useCallback(g=>{if(g)return d.get(g)},[d]),h=o.useCallback(g=>{if(g)return b.get(g)},[b]),w=o.useMemo(()=>{const g=N.filter(j=>!a.has(j.tabKey));return mn(u.current,g)?u.current:(u.current=g,g)},[N,a]),_=o.useMemo(()=>{const g=w.map(j=>j.tabKey);return mn(p.current,g)?p.current:(p.current=g,g)},[w]);return{chatIdes:i,conversations:N,visibleConversations:w,visibleTabKeys:_,resolveConversationBySessionId:S,resolveConversationByTarget:h}}function bm({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function gm({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=it.onToast(u=>{r(m=>m.some(v=>v.message===u.message&&u.timestamp-v.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=it.onSystemMessage((u,p)=>{var N,L;const m=a(u),f=(N=p._localId)==null?void 0:N.startsWith("sys_approval_"),v=!!(m&&(m.status==="waiting_approval"||(L=m.modalButtons)!=null&&L.length||m.modalMessage));f&&v||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=it.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(v=>{var N;return!(v.role==="system"&&((N=v._localId)!=null&&N.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=ci.on("status_event",c=>{it.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const v=Number(u.buttonIndex),N=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[v])||"Approve",L=String(N).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);s(f,"resolve_action",{action:d?"approve":"reject",button:N,...Number.isFinite(v)&&{buttonIndex:v},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(S=>console.error("[SW Action] approval failed:",S))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const ym="adhdev_dashboardLayout_v1",vm="adhdev_dashboardDockview_v1",wm="adhdev_dashboardDockviewHiddenRestore_v1",Bs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ua(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function $i(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Bi(e){return`${ym}:${e}`}function jm(e){const s=Bi(e);return ua(s,null)}function km(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=Bi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Ki(e){return`${vm}:${e}`}function Nm(e){const s=Ki(e);return ua(s,null)}function Sm(e,s){try{const r=Ki(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Wi(e){return`${wm}:${e}`}function Cm(e){const s=Wi(e);return ua(s,{})}function Im(e,s){try{const r=Wi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Am(){return{groupAssignments:[...Bs.groupAssignments],focusedGroup:Bs.focusedGroup,groupActiveTabIds:{...Bs.groupActiveTabIds},groupTabOrders:{...Bs.groupTabOrders},groupSizes:[...Bs.groupSizes]}}function Tm(){const[e]=o.useState(()=>$i(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[f,v]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[N,L]=o.useState(!1),d=o.useCallback(()=>{if(N)return;const b=jm(e)??Am();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),L(!0)},[N,e]);return o.useEffect(()=>{N&&km(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[N,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),S=h=>v(h.matches);return b.addEventListener("change",S),()=>b.removeEventListener("change",S)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:N,hydrateStoredLayout:d}}function Mm(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Lm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:v,handleRefreshHistory:N}){const L=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),S=o.useRef(!1);o.useEffect(()=>{if(!e||L.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const w=n.get(h.tabKey)??0;c(_=>({..._,[w]:h.tabKey})),l(w),L.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const g=new URLSearchParams(_);return g.delete("activeTab"),g},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&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||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){S.current=!1;return}if(!m||S.current||f)return;const h=v.find(w=>w.id===m.routeId);h&&(!h.chats||h.chats.length===0||Mm(h.chats,m))&&(S.current=!0,N())},[p,m,f,v,N]),o.useEffect(()=>{if(!m)return;let h=null,w=0,_=-1,g=0;const j=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(k.length===0){w<18&&(w+=1,h=requestAnimationFrame(j));return}let y=0;for(const x of k)x.scrollTop=x.scrollHeight,y+=x.scrollHeight;y===_?g+=1:(g=0,_=y),w+=1,!(g>=2||w>=18)&&(h=requestAnimationFrame(j))};return h=requestAnimationFrame(j),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function _m({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),v=o.useMemo(()=>{if(e||!n)return null;const S=l(n);return S&&!Ze(S)&&!qe(S)?S:null},[e,n,l]),N=o.useMemo(()=>{const S=u==null?void 0:u.routeId;if(!S)return null;const h=u!=null&&u.tabKey?i.find(w=>w.tabKey===u.tabKey):a?i.find(w=>w.tabKey===a):null;return(h==null?void 0:h.routeId)===S?h:Bt(i,S)},[i,u,a]),L=o.useMemo(()=>{if(N)return c.find(S=>S.id===N.routeId)},[c,N]);o.useEffect(()=>{v&&(p({routeId:v.routeId,tabKey:Ka(v)}),f(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const d=o.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:Ka(S)}),f(S))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:N,remoteDialogIdeEntry:L,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function js(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Ze(e)||qe(e)?{agentType:Lt(e)}:e.streamSource==="agent-stream"?{agentType:Lt(e)}:s}function Js(e){return e?Lr(e):""}function Ks(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function pn(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(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ro({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),v=o.useCallback(async(d,b)=>{try{const S=d||(s==null?void 0:s.daemonId)||"",h=await e(S,"switch_chat",{id:b,sessionId:b,...js(s)}),w=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||w==="switched"||w==="switched-by-title")return;w===!1||w==="not_found"?Ks(a,"⚠️ Session tab not found — try refreshing history"):typeof w=="string"&&w.startsWith("error:")?Ks(a,`⚠️ Switch error: ${w}`):Ks(a,"⚠️ Session switch failed")}catch(S){console.error("Switch failed",S),Ks(a,`❌ Switch failed: ${S.message||"connection error"}`)}},[s,e,a]),N=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=Js(s);await e(d,"new_chat",{...js(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),L=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const S=Js(s),h=async()=>e(S,"list_chats",{forceExpand:!0,...js(s)});let w=await h(),_=(w==null?void 0:w.chats)||((d=w==null?void 0:w.result)==null?void 0:d.chats);pn(_,s)&&(await new Promise(g=>setTimeout(g,450)),w=await h(),_=(w==null?void 0:w.chats)||((b=w==null?void 0:w.result)==null?void 0:b.chats)),w!=null&&w.success&&Array.isArray(_)&&(n(s.routeId,_),pn(_,s)&&!pn(r,s)&&Ks(a,"⚠️ History dialog did not fully open — try once more"))}catch(S){console.error("Refresh history failed",S)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:v,handleNewChat:N,handleRefreshHistory:L}}function Rm(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 Pm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function no(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}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 a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function ao(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Dm(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Em(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function oo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function io(e){return Array(e).fill(100/e)}function $m({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),f=o.useMemo(()=>mr(e,p),[e,p]),v=f.assignments,N=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),L=N>1,d=o.useCallback((g,j)=>{s(k=>{const y=new Map(mr(k,p).assignments);return j===0?y.delete(g):y.set(g,j),y}),n(k=>({...k,[j]:g})),r(j)},[s,p,n,r]),b=o.useCallback(g=>{s(j=>{const k=mr(j,p).assignments,y=new Map;for(const[x,E]of k)E!==g&&(E>g?y.set(x,E-1):y.set(x,E));return y}),c(j=>{if(j.length<=1)return[];const k=[...j];k.splice(g,1);const y=k.reduce((x,E)=>x+E,0);return y>0?k.map(x=>x/y*100):[]}),r(0)},[s,p,c,r]),S=o.useCallback((g,j)=>{j.preventDefault();const k=m.current;if(!k)return;const y=j.clientX,x=k.offsetWidth,E=i.length===N?[...i]:io(N),I=T=>{const R=(T.clientX-y)/x*100,C=[...E];C[g]=Math.max(15,E[g]+R),C[g+1]=Math.max(15,E[g+1]-R),c(C)},M=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",M),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",M)},[i,N,c]),h=o.useCallback((g,j,k)=>{if(N>=4)return;const y=k==="left"?j:j+1;s(x=>{const E=mr(x,p).assignments,I=new Map;for(const M of u){const T=E.get(M.tabKey)??0,W=T>=y?T+1:T;W>0&&I.set(M.tabKey,W)}return y>0&&I.set(g,y),I}),c(x=>{const E=x.length===N?[...x]:io(N),I=E[j]??100/N,M=Math.max(15,I/2),T=Math.max(15,I/2),W=[...E];W[j]=M,W.splice(y,0,T);const R=W.reduce((C,H)=>C+H,0);return W.map(C=>C/R*100)}),n(x=>{const E=oo(x,y);return E[y]=g,E}),a(x=>{const E=oo(x,y);return E[y]=[g],E}),r(y)},[N,s,p,u,c,n,a,r]);o.useEffect(()=>{Rm(e,v)||s(v)},[e,v,s]),o.useEffect(()=>{const{mapping:g,usedGroups:j}=f;n(k=>{const y=ao(k,g);return no(k,y)?k:y}),a(k=>{const y=ao(k,g);return no(k,y)?k:y}),r(k=>{const y=l?0:Dm(k,j,g);return k===y?k:y}),c(k=>{const y=l?[]:Em(k,j,f.groupCount);return Pm(k,y)?k:y})},[f,l,n,a,r,c]);const w=o.useMemo(()=>{const g=Array.from({length:N},()=>[]);for(const j of u){const k=v.get(j.tabKey)??0,y=Math.min(k,N-1);g[y].push(j)}return g},[u,v,N]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:v,numGroups:N,isSplitMode:L,groupedConvs:w,moveTabToGroup:d,closeGroup:b,handleResizeStart:S,splitTabRelative:h,clearAllSplits:_}}function Bm({ides:e,sendDaemonCommand:s}){const r="0.8.66",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Si(m,r)).sort((m,f)=>Number(Fs(f,r))-Number(Fs(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>Fs(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,v;u(N=>({...N,[m]:"upgrading"}));try{const N=await s(m,"daemon_upgrade",{});(f=N==null?void 0:N.result)!=null&&f.upgraded||(v=N==null?void 0:N.result)!=null&&v.success?u(L=>({...L,[m]:"done"})):u(L=>({...L,[m]:"error"}))}catch{u(N=>({...N,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Kn="adhdev_dashboard_notifications_v1",ma=80;function Sr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function $r(e){return{...e,createdAt:Sr(e.createdAt),updatedAt:Sr(e.updatedAt,e.createdAt),lastEventAt:Sr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Km(e){return[e.type,e.sessionId||e.tabKey||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Wm(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=(i==null?void 0:i.inboxBucket)||"idle",l=c==="needs_attention"?"needs_attention":c==="task_complete"&&(i!=null&&i.unread)?"task_complete":null;if(!l)continue;const u=Sr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Km({type:l,sessionId:a.sessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push($r({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,tabKey:a.tabKey,title:a.title||a.displayPrimary||a.agentName||a.tabKey,preview:a.lastMessagePreview||a.displaySecondary||"",createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function Om(e,s,r=ma){const n=new Map;for(const a of e)a.deletedAt||n.set(a.id,$r(a));for(const a of s){const i=$r(a),c=n.get(i.id);if(!c){n.set(i.id,i);continue}n.set(i.id,{...c,...i,createdAt:c.createdAt,readAt:c.readAt,deletedAt:c.deletedAt})}return Array.from(n.values()).filter(a=>!a.deletedAt).sort((a,i)=>{const c=i.updatedAt-a.updatedAt;return c!==0?c:i.createdAt-a.createdAt}).slice(0,Math.max(0,r))}function Hm(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Um(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function zm(e,s,r=Date.now()){return e.map(n=>{const a=!!s.sessionId&&n.sessionId===s.sessionId,i=!!s.tabKey&&n.tabKey===s.tabKey;return!a&&!i?n:{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}})}function Fm(e,s){return e.filter(r=>r.id!==s)}function Vm(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Gm(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=r.sessionId||r.tabKey;if(!n)continue;const a=s.get(n),i=r.readAt?0:1;if(!a){s.set(n,{unreadCount:i,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(n,{unreadCount:a.unreadCount+i,latestNotificationAt:Math.max(a.latestNotificationAt,r.updatedAt),latestRecordId:a.latestNotificationAt>=r.updatedAt?a.latestRecordId:r.id})}return s}function qm(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Kn),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>$r(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function Ym(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,ma);if(s.length===0){window.localStorage.removeItem(Kn);return}window.localStorage.setItem(Kn,JSON.stringify(s))}catch{}}function Xm(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.updatedAt===a.updatedAt&&r.createdAt===a.createdAt&&r.readAt===a.readAt&&r.preview===a.preview&&r.title===a.title&&r.deletedAt===a.deletedAt:!1})}function Qm(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=ma}=e,a=o.useMemo(()=>Wm(s,r),[s,r]),[i,c]=o.useState(()=>qm());o.useEffect(()=>{c(N=>{const L=Om(N,a,n);return Xm(N,L)?N:L})},[a,n]),o.useEffect(()=>{Ym(i)},[i]);const l=o.useMemo(()=>Vm(i),[i]),u=o.useMemo(()=>Gm(i),[i]),p=o.useCallback((N,L)=>{c(d=>Hm(d,N,L))},[]),m=o.useCallback(N=>{c(L=>Um(L,N))},[]),f=o.useCallback((N,L)=>{c(d=>zm(d,N,L))},[]),v=o.useCallback(N=>{c(L=>Fm(L,N))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:f,deleteNotification:v}}function co(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function pa(e){return e instanceof Error?e.message:String(e||"")}function lo(e){const s=pa(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function uo(e,s){const r=pa(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Vr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),p=o.useRef(!1),m=o.useRef(null),f=o.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||p.current)return;const S=s.tabKey,h=Date.now(),w=m.current;if(w&&w.tabKey===S&&w.message===b&&h-w.timestamp<2e3)return;p.current=!0,u(!0),m.current={tabKey:S,message:b,timestamp:h};const _=`${h}-${Math.random().toString(36).slice(2,8)}`,g={role:"user",content:b,timestamp:h,_localId:_},j=!(Ze(s)||qe(s));j&&r(k=>({...k,[S]:[...k[S]||[],g]}));try{const k=Js(s);if(!k)return;const y=await e(k,"send_chat",{message:b,...js(s)}),x=co(y);if(j&&(x!=null&&x.deduplicated||(x==null?void 0:x.sent)===!1)){r(E=>({...E,[S]:(E[S]||[]).filter(I=>I._localId!==_)}));return}if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Send failed");setTimeout(()=>{const E=Date.now()-6e4;r(I=>{const M=I[S];if(!M)return I;const T=M.filter(W=>W.timestamp>E);return T.length===M.length?I:{...I,[S]:T}})},6e4)}catch(k){const y=pa(k);y.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",y):console.error("Send failed",k),j&&r(x=>({...x,[S]:(x[S]||[]).filter(E=>E._localId!==_)}))}finally{p.current=!1,u(!1)}},[s,e,r]),v=o.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]),N=o.useCallback(async d=>{if(s)try{const S=(s.modalButtons||[]).indexOf(d),h=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(h),_=Js(s);if(!_)return;const g=await e(_,"resolve_action",{button:d,action:w?"approve":"reject",...S>=0&&{buttonIndex:S},...js(s)}),j=co(g);j.success||n(k=>[...k,{routeId:s.tabKey,text:uo(d,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){lo(b)||console.error("[ModalButton] Error:",b),n(S=>[...S,{routeId:s.tabKey,text:lo(b)?uo(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),L=o.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:f,handleRelaunch:v,handleModalButton:N,handleFocusAgent:L}}const fa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:N,scrollToBottomRequestNonce:L,isInputActive:d=!0}){const b=_i(s),S=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(Go,{activeConv:S,onModalButton:c}),S.transport!=="pty"&&S.transport!=="acp"&&S.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(ds,{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,S.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(Jd,{activeConv:S,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Rn,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:N,scrollToBottomRequestNonce:L,isInputActive:d})})]}):t.jsx(Rn,{activeConv:S,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:v,userName:N,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 Jm({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:u,onOpenNativeConversation:p,onOpenMachine:m,onOpenHistory:f,onOpenRemote:v,onHideConversation:N,onStopCli:L,cliViewMode:d,onSetCliViewMode:b,handleSendChat:S,handleFocusAgent:h,handleModalButton:w,handleRelaunch:_}){const g=o.useRef(null),j=Ze(e)&&!s,k=j&&d==="terminal",y=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${y} 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:u,type:"button","aria-label":"Back",children:t.jsx(Fn,{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)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(ni,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>m(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&d&&t.jsx(sa,{mode:d,onChange:b,compact:!0}),j&&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:()=>f(e),type:"button",children:t.jsx(Gn,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(It,{size:14})}),N&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(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(fa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:g,handleModalButton:w,handleRelaunch:_,handleSendChat:S,isSendingChat:c,handleFocusAgent:h,isFocusingAgent:l,actionLogs:a,userName:i})})]})}const fn={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 Zm(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Oi(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Zm())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(fn[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:fn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:fn[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:a?"✓":"📋"})]}),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 Hi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:It},{key:"chats",label:"Chats",icon:Ht}];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:a,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:a})]},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 bs({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 Ws({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 a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=Rs(e.conversation),m=ct(e.conversation),f=ps(e.conversation),v=di(e.conversation,{requiresAction:s==="needs_attention"}),N=a?"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=a?"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",S=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",w="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] ${N}`,onClick:()=>n(e.conversation),type:"button",children:[a||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:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),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:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:Vo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${w} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):v==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:w,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),a&&!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 mo({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 ep({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:N,onSectionChange:L,wsStatus:d="connected",isStandalone:b=!1}){const S=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,w=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",g=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=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 ${g}`,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:_}),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(Hr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:N,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(Wr,{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] ${j}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:S?t.jsx(Ws,{icon:t.jsx(mo,{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(Ws,{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(Oi,{})})}):t.jsx(bs,{children:c.map((k,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(k.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(k.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:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.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(bs,{children:s.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.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(bs,{children:r.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.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(bs,{children:n.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(pr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(bs,{children:a.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(fr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):w?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):S?t.jsx(Ws,{icon:t.jsx(mo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Ws,{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(Ht,{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(Ws,{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:m,children:"Restore all"})]}),t.jsx(bs,{className:"bg-bg-secondary/25",children:i.map((k,y)=>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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(k),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(ct(k))}),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:ct(k)}),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:ps(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&f&&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:f,"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(Hi,{section:e,onSectionChange:L})]})}function tp(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 Ui(e){const s=[e.workspace||"Workspace unknown"],r=us(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=tp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Gr(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function sp(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(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function qr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=sp(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 rp(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 np(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Yr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=np(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function Xr({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const v=rp(r),N=m.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm: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:()=>{!v||a||u(v)},disabled:!v||a,children:[t.jsx(Fn,{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:m,onChange:L=>f(L.target.value),onKeyDown:L=>{L.key!=="Enter"||!N||a||(L.preventDefault(),u(N))},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:()=>{!N||a||u(N)},disabled:!N||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?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:()=>u(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(Ns,{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-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",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:()=>p(N||r),disabled:!N&&!r||a,children:c})]})]})})}function xa({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:v,modelValue:N,onModelChange:L,historyProviderNode:d,onConfirm:b,onCancel:S}){const h=n==null?void 0:n.find(w=>w.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm: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:"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:S,"aria-label":"Close launch confirmation",children:t.jsx(kt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm: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:a||"",onChange:w=>i(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(w=>t.jsx("option",{value:w.key,children:w.label},w.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(w=>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:w.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),v&&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:N||"",onChange:w=>L(w.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&f&&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:m||"",onChange:w=>f(w.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:u,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:u,children:[t.jsx(qn,{size:14}),u?l:c]})]})]})})}function po(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${po(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:po(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function ap(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function op(e){return[ap(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ip(e){return e.lastLaunchedAt?Ur(e.lastLaunchedAt):""}function zi(e){return{metaText:op(e),updatedLabel:ip(e)}}function xn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function cp({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var lt,dt,xt,at;const c=er(),[l,u]=o.useState(!1),p=(((lt=e.detectedIdes)==null?void 0:lt.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(pe=>({id:pe.id,path:pe.path,label:pe.label})),[e]),f=e.defaultWorkspaceId||null,[v,N]=o.useState(f||((dt=m[0])==null?void 0:dt.id)||""),[L,d]=o.useState(""),[b,S]=o.useState(""),[h,w]=o.useState([]),[_,g]=o.useState(!1),[j,k]=o.useState(""),[y,x]=o.useState(!1),[E,I]=o.useState(xn(p,s.length,r.length)),M=o.useRef(null),[T,W]=o.useState(null),R=o.useRef("__home__"),[C,H]=o.useState("__home__"),[G,A]=o.useState(""),[$,B]=o.useState(""),[O,X]=o.useState(""),[je,$e]=o.useState([]),[me,_e]=o.useState(()=>gt().textQuery),[ae,ee]=o.useState(()=>gt().workspaceQuery),[se,ue]=o.useState(()=>gt().modelQuery),[re,z]=o.useState(()=>gt().resumableOnly),[le,Z]=o.useState(()=>gt().sortMode),[ie,Q]=o.useState(!1),[de,oe]=o.useState(!1),ge=o.useRef(null),fe=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const D=v==="__custom__"?L.trim():((xt=m.find(pe=>pe.id===v))==null?void 0:xt.path)||"",ye=v==="__custom__"&&!!D&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),be=v!=="__custom__"&&((at=m.find(pe=>pe.id===v))==null?void 0:at.path)||"",Ne=o.useMemo(()=>(e.recentLaunches||[]).map(pe=>pe.workspace),[e]),J=o.useCallback(async pe=>{g(!0),k("");try{const Fe=await a(pe);S(Fe.path),d(Fe.path),w(Fe.directories)}catch(Fe){k(Fe instanceof Error?Fe.message:"Could not load folder")}finally{g(!1)}},[a]),Se=o.useCallback(()=>{var Fe;N("__custom__"),x(!0);const pe=qr(e.platform,Gr(L.trim(),be,Ne,e.defaultWorkspacePath,(Fe=m.find(Qe=>Qe.id===f))==null?void 0:Fe.path,m.map(Qe=>Qe.path)));J(pe)},[L,f,J,Ne,be,e.platform,m]),Ue=o.useCallback(pe=>{if(pe!=null&&pe.workspaceId){N(pe.workspaceId),d("");return}if(pe!=null&&pe.workspacePath){N("__custom__"),d(pe.workspacePath);return}N(""),d("")},[]),De=o.useCallback(pe=>{if(N(pe),pe==="__custom__"){Se();return}d("")},[Se]),Ve=o.useCallback(pe=>{N("__custom__"),d(pe)},[]),Ye=o.useCallback((pe,Fe)=>{M.current=Fe,R.current=pe.selectedWorkspaceKey||"__home__",H(pe.selectedWorkspaceKey||"__home__"),A(pe.initialArgs||""),B(pe.initialModel||""),X(""),$e([]);const Qe=pe.providerType?`${e.id}:${pe.providerType}`:null;if(su(fe.current,Qe)){const et=gt();_e(et.textQuery),ee(et.workspaceQuery),ue(et.modelQuery),z(et.resumableOnly),Z(et.sortMode)}fe.current=Qe,W(pe),pe.providerType&&i&&(Q(!0),i(pe.providerType).then(et=>$e(et||[])).catch(et=>console.warn("Failed to load saved sessions",et)).finally(()=>Q(!1)))},[i,e.id]),Xe=o.useMemo(()=>pi(je,{textQuery:me,workspaceQuery:ae,modelQuery:se,resumableOnly:re,sortMode:le}),[se,re,je,le,me,ae]);o.useEffect(()=>{O&&(Xe.some(pe=>pe.providerSessionId===O)||X(""))},[Xe,O]);const pt=o.useCallback(()=>{M.current&&(oe(!0),M.current().finally(()=>{M.current=null,oe(!1),W(null)}))},[]),Ge=o.useCallback(()=>{M.current=null,W(null)},[]),bt=o.useCallback(pe=>{R.current=pe,H(pe)},[]);return o.useEffect(()=>{var pe;ge.current!==e.id&&(ge.current=e.id,N(f||((pe=m[0])==null?void 0:pe.id)||"__custom__"),d(""),S(""),w([]),k(""),x(!1),_e(gt().textQuery),ee(gt().workspaceQuery),ue(gt().modelQuery),z(gt().resumableOnly),Z(gt().sortMode),fe.current=null,I(xn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var pe;v!=="__custom__"&&(v&&m.some(Fe=>Fe.id===v)||N(f||((pe=m[0])==null?void 0:pe.id)||"__custom__"))},[f,v,m]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||I(xn(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:v,customWorkspacePath:L,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:j,browseDialogOpen:y,activeLauncherKind:E,launchConfirm:T,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:C,launchConfirmArgs:G,launchConfirmModel:$,launchConfirmResumeId:O,launchConfirmSavedSessions:je,launchConfirmTextFilter:me,launchConfirmWorkspaceFilter:ae,launchConfirmModelFilter:se,launchConfirmResumableOnly:re,launchConfirmSortMode:le,filteredLaunchConfirmSavedSessions:Xe,launchConfirmSessionsLoading:ie,launchConfirmBusy:de,resolvedWorkspacePath:D,canCreateMissingWorkspace:ye,openBrowseDialog:Se,loadBrowsePath:J,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Ve,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:I,openLaunchConfirm:Ye,handleConfirmLaunch:pt,closeLaunchConfirm:Ge,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:bt,setLaunchConfirmArgs:A,setLaunchConfirmModel:B,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:_e,setLaunchConfirmWorkspaceFilter:ee,setLaunchConfirmModelFilter:ue,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:Z}}function lp({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:v,onOpenConversation:N,onOpenRecent:L,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:S,onAddWorkspace:h,onBrowseDirectory:w,onLaunchWorkspaceProvider:_,onListSavedSessions:g}){const j=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",k=r.slice(0,4),y=s.slice(0,3),x=cp({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:w,onListSavedSessions:g}),E=o.useMemo(()=>k.map(C=>{const{metaText:H,updatedLabel:G}=zi(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:H,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:$}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?ss("restart-ide",C.label):C.providerSessionId?aa(C.label):ss("start-fresh",C.label),description:C.kind==="ide"?rs("restart-ide"):C.providerSessionId?oa():rs("start-fresh"),confirmLabel:C.kind==="ide"?Ts("restart-ide"):C.providerSessionId?Pr(!0):Ts("start-fresh"),busyLabel:C.kind==="ide"?Ms("restart-ide"):C.providerSessionId?ra(!0):Ms("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:$,details:[{label:"Mode",value:j(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const B=A.find(O=>O.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(B),await L({...C,workspace:(B==null?void 0:B.workspacePath)??null})})}}}),[x,L,k]),I=o.useMemo(()=>y.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ct(C.conversation),secondary:qd(C.conversation,{timestampLabel:C.timestamp?Vo(C.timestamp):null}),unread:C.unread,onClick:()=>N(C.conversation)})),[N,y]),M=x.showAllRecent?E:E.slice(0,4),T=E.length>0,W=I.length>0,R=u?"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 ${R} 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:f,type:"button","aria-label":"Back",children:t.jsx(Fn,{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:[W&&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(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),T&&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:M.map(C=>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:C.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:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.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:()=>x.setShowAllRecent(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.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:x.workspaceChoice,onChange:C=>x.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",Fr(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.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(Ns,{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:x.resolvedWorkspacePath||x.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:x.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:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.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:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.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:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>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:G}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:H,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const A=H.find($=>$.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),S(C.type,{workspacePath:(A==null?void 0:A.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>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=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${H.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:H.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:H==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=G.find(B=>B.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption($),_(H,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.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,x.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:()=>h(x.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"})]})]})]})]}),x.browseDialogOpen&&t.jsx(Xr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(xa,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?Pr(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.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"}),x.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:na()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.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:x.launchConfirmResumableOnly,onChange:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:au()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const C=x.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const H=Ui(C);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:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Hi,{section:p,onSectionChange:v})]})}function Fi(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 dp(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:us(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,u,p,m;const a=Xs(n)?"cli":ws(n)?"acp":"ide",i=us(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ws(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function up(e,s){const r=new Map;for(const n of s){const a=qt(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,v)=>v.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Mn(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=Fi(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Yd(c):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const i=n.latestTimestamp||n.fallbackActivityAt||0,c=a.latestTimestamp||a.fallbackActivityAt||0;return c!==i?c-i:n.label.localeCompare(a.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 mp({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:v,onRequestedMobileSectionConsumed:N,setSelectedTabKey:L,setScreen:d,setSelectedMachineId:b,setSection:S,setMachineBackTarget:h,resetMachineAction:w,markNotificationTargetRead:_}){const g=o.useRef(null),j=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const y=Mr(k,c),x=Math.max(Date.now(),os(k),y.lastUpdated||0);xr("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:ct(k),inboxBucket:y.inboxBucket,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:os(k),readAt:x}),_({sessionId:k.sessionId,tabKey:k.tabKey}),l(qt(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:x}).then(E=>{xr("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:E})}).catch(E=>{xr("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var y;if(!n){d("inbox"),L(((y=e[0])==null?void 0:y.tabKey)||null),g.current=null;return}if(i!=="chat"){g.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;g.current!==k&&(g.current=k,j(n))},[e,j,i,n,d,L]),o.useEffect(()=>{if(!u)return;const k=e.find(y=>y.tabKey===u);k&&(L(k.tabKey),d("chat"),p==null||p())},[e,p,u,d,L]),o.useEffect(()=>{if(!m)return;const k=s.find(y=>y.id===m);k&&(b(k.id),w(),S("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,w,h,d,S,b]),o.useEffect(()=>{v&&(S(v),d("inbox"),N==null||N())},[N,v,d,S]),o.useEffect(()=>{const k=r.filter(y=>y.inboxBucket==="task_complete"||y.unread);k.length!==0&&xr("inbox_state",{screen:i,selectedTabKey:a,items:k.map(y=>{const x=Mr(y.conversation,c);return{liveState:x,tabKey:y.conversation.tabKey,sessionId:y.conversation.sessionId,displayPrimary:ct(y.conversation),serverBucket:x.inboxBucket,computedBucket:y.inboxBucket,serverUnread:x.unread,computedUnread:y.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:os(y.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function pp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function fo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function xp({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,w,_)=>{var g;try{i("loading"),l(`Launching ${w}…`);const j={ideType:w,enableCdp:!0};(g=_==null?void 0:_.workspacePath)!=null&&g.trim()&&(j.workspace=_.workspacePath.trim()),await e(h,"launch_ide",j),i("done"),l(`${w} launch requested`)}catch(j){i("error"),l(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),v=o.useCallback(async(h,w,_)=>{if(w.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(h,"workspace_add",{path:w.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),N=o.useCallback(async h=>{var w,_,g,j,k,y;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((w=x==null?void 0:x.result)!=null&&w.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((g=x==null?void 0:x.result)!=null&&g.upgraded||(j=x==null?void 0:x.result)!=null&&j.success){i("done"),l(`Upgrade to v${((k=x==null?void 0:x.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((y=x==null?void 0:x.result)==null?void 0:y.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),L=o.useCallback(async(h,w,_,g)=>{var y,x,E;const j=Date.now(),k={machineId:h,kind:w,providerType:_,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:j};try{i("loading"),l(`Launching ${_}…`),p(k);const I={cliType:_};(y=g==null?void 0:g.workspacePath)!=null&&y.trim()?I.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(I.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(I.resumeSessionId=g.resumeSessionId),(x=g==null?void 0:g.args)!=null&&x.trim()&&(I.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(E=g==null?void 0:g.model)!=null&&E.trim()&&(I.initialModel=g.model.trim());const M=await e(h,"launch_cli",I),T=(M==null?void 0:M.result)||M,W=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(M!=null&&M.success&&W){p(null),i("done"),l(`${_} launched`),s(`/dashboard?activeTab=${encodeURIComponent(W)}`);return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(T==null?void 0:T.error)||`Could not launch ${w.toUpperCase()} workspace`)}catch(I){if(fp(I)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${w.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,w)=>{try{const _=await e(h,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),g=(_==null?void 0:_.result)??_;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,w)=>Yr(e,h,w),[e]);o.useEffect(()=>{var g;if(!u)return;const h=fo(u.workspacePath),w=r.find(j=>{var M,T,W,R;if(!j||j.type==="adhdev-daemon"||pp(j.daemonId||j.id)!==u.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==u.kind||String(j.agentType||j.type||"")!==u.providerType)return!1;const E=String(j.providerSessionId||"");if(u.resumeSessionId&&E)return E===u.resumeSessionId;if(h){const C=fo(j.workspace||j.runtimeWorkspaceLabel);return C?C===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((R=(W=(T=(M=j.activeChat)==null?void 0:M.messages)==null?void 0:T.at)==null?void 0:W.call(T,-1))==null?void 0:R.timestamp)||0)>=u.startedAt-5e3});if(!w)return;const _=typeof w.sessionId=="string"&&w.sessionId?w.sessionId:typeof w.instanceId=="string"&&w.instanceId?w.instanceId:(g=n.find(j=>j.routeId===w.id))==null?void 0:g.sessionId;_&&(p(null),i("done"),l(`${u.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(_)}`))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(w=>!w||w.startedAt!==u.startedAt?w:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const S=o.useCallback(async(h,w)=>{if(w.kind==="ide"&&w.providerType){await f(h,w.providerType,{workspacePath:w.workspace||null});return}(w.kind==="cli"||w.kind==="acp")&&w.providerType&&await L(h,w.kind,w.providerType,{workspacePath:w.workspace||null,resumeSessionId:w.providerSessionId||null})},[f,L]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:v,handleMachineUpgrade:N,handleLaunchWorkspaceProvider:L,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:S}}function hp({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(S=>{i(S.tabKey),c("chat"),n(S)},[n,c,i]),f=o.useCallback(S=>{const h=e.find(w=>w.routeId===S.routeId&&w.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),v=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),N=o.useCallback((S,h="inbox")=>{l(S),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),L=o.useCallback(S=>{const h=qt(S);h&&N(h,"chat")},[N]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(S=>{u(S),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:v,openMachine:N,openConversationMachine:L,backFromMachine:d,changeMachineSection:b}}function bp(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function gp(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 yp({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:N,onRequestedMobileSectionConsumed:L,onOpenHistory:d,onOpenRemote:b,onStopCli:S,wsStatus:h,isConnected:w,onShowHiddenConversation:_,onShowAllHiddenConversations:g,onHideConversation:j,onOpenNewSession:k,notificationStateBySessionId:y,onMarkNotificationTargetRead:x}){const[E,I]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[M,T]=o.useState(()=>e[0]?"chat":"inbox"),[W,R]=o.useState("chats"),[C,H]=o.useState(null),[G,A]=o.useState("inbox"),$=Ls(),B="0.8.66",O=o.useMemo(()=>e.find(J=>J.tabKey===E)||e[0]||null,[e,E]),X=o.useMemo(()=>O?r.find(J=>J.id===O.routeId):void 0,[r,O]),je=o.useMemo(()=>!O||qe(O)||!Ze(O)?null:Is(O),[O]),$e=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(Qn),[r]),me=o.useMemo(()=>$e.find(J=>J.id===C)||null,[$e,C]),_e=o.useMemo(()=>zr(r),[r]),ae=Vr({sendDaemonCommand:a,activeConv:O||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ee=xp({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),se=o.useMemo(()=>e.map(J=>{const Se=M==="chat"&&(O==null?void 0:O.tabKey)===J.tabKey,Ue=Xn(J,_e,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Se,notificationStateBySessionId:y}),De=os(J),Ve=li(J);return{conversation:J,timestamp:De,preview:Ve,unread:Ue.unread,requiresAction:Ue.requiresAction,isWorking:Ue.isWorking,inboxBucket:Ue.inboxBucket}}),[e,_e,y,M,O]),{markConversationRead:ue}=mp({conversations:e,machineEntries:$e,items:se,selectedConversation:O,selectedTabKey:E,screen:M,liveSessionInboxState:_e,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:v,requestedMobileSection:N,onRequestedMobileSectionConsumed:L,setSelectedTabKey:I,setScreen:T,setSelectedMachineId:H,setSection:R,setMachineBackTarget:A,resetMachineAction:ee.resetMachineAction,markNotificationTargetRead:x}),re=hp({conversations:e,selectedConversation:O,machineBackTarget:G,markConversationRead:ue,resetMachineAction:ee.resetMachineAction,setSelectedTabKey:I,setScreen:T,setSelectedMachineId:H,setSection:R,setMachineBackTarget:A}),z=o.useMemo(()=>hr(se.filter(J=>J.requiresAction)),[se]),le=o.useMemo(()=>hr(se.filter(J=>J.unread&&!J.requiresAction)),[se]),Z=o.useMemo(()=>hr(se.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[se]),ie=o.useMemo(()=>hr(se.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[se]),Q=o.useMemo(()=>me?se.filter(J=>qt(J.conversation)===me.id):[],[se,me]),de=o.useMemo(()=>dp(me,r),[r,me]),oe=(me==null?void 0:me.version)||null,ge=!!me&&!!oe&&!0&&oe!==B,fe=o.useMemo(()=>(me==null?void 0:me.availableProviders)||[],[me]),D=o.useMemo(()=>fe.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[fe]),ye=o.useMemo(()=>fe.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[fe]),be=o.useMemo(()=>up($e,se),[se,$e]),Ne=o.useCallback(async J=>{me&&await ee.handleOpenRecent(me.id,J)},[ee,me]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&O?t.jsx(Jm,{selectedConversation:O,isAcp:qe(O),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:u,isSendingChat:ae.isSendingChat,isFocusingAgent:ae.isFocusingAgent,handleModalButton:ae.handleModalButton,handleRelaunch:ae.handleRelaunch,onBack:re.backFromConversation,onOpenNativeConversation:re.openNativeConversation,onOpenMachine:re.openConversationMachine,onHideConversation:j,onOpenHistory:d,onOpenRemote:b,onStopCli:S,cliViewMode:je,onSetCliViewMode:async J=>{if(O&&je!==J)try{await a(qt(O)||O.routeId,"set_cli_view_mode",{targetSessionId:O.sessionId,cliType:Lt(O),mode:J})}catch(Se){gp(Se)?console.warn("Skipped CLI view mode switch:",Se instanceof Error?Se.message:String(Se)):console.error("Failed to switch CLI view mode:",Se)}},handleSendChat:ae.handleSendChat,handleFocusAgent:ae.handleFocusAgent}):M==="machine"&&me?t.jsx(lp,{selectedMachineEntry:me,selectedMachineConversations:Q,selectedMachineRecentLaunches:de,cliProviders:D,acpProviders:ye,selectedMachineNeedsUpgrade:ge,appVersion:B,machineAction:ee.machineAction,isStandalone:l,section:W,showBottomNav:G==="inbox",onBack:re.backFromMachine,onSectionChange:re.changeMachineSection,onOpenConversation:re.openConversation,onOpenRecent:Ne,onOpenMachineDetails:()=>$(`/machines/${me.id}`),onMachineUpgrade:()=>ee.handleMachineUpgrade(me.id),onLaunchDetectedIde:(J,Se)=>ee.handleLaunchDetectedIde(me.id,J,Se),onAddWorkspace:(J,Se)=>ee.handleAddWorkspace(me.id,J,Se),onBrowseDirectory:J=>ee.handleBrowseDirectory(me.id,J),onLaunchWorkspaceProvider:(J,Se,Ue)=>ee.handleLaunchWorkspaceProvider(me.id,J,Se,Ue),onListSavedSessions:J=>ee.handleListSavedSessions(me.id,J)}):t.jsx(ep,{section:W,attentionItems:z,unreadItems:le,workingItems:Z,completedItems:ie,hiddenConversations:s,machineCards:be,getAvatarText:bp,onOpenConversation:re.openConversation,onShowConversation:_,onShowAllHidden:g,onOpenNewSession:k,onOpenMachine:re.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:R,wsStatus:h,isConnected:w,isStandalone:l})})}function hn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function vp({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const v=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),N=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!hn(s,r)){m("merge");return}const S=b.currentTarget.getBoundingClientRect(),h=b.clientX-S.left,w=S.width/3;h<w?m("split-left"):h>w*2?m("split-right"):m("merge")},[s,r]),L=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const S=b.dataTransfer.getData("text/tab-key"),h=S?e.some(_=>_.tabKey===S):!1,w=p;if(m(null),i(),!!S){if(b.preventDefault(),w==="split-left"&&hn(s,r)){r==null||r(S,"split-left");return}if(w==="split-right"&&hn(s,r)){r==null||r(S,"split-right");return}if(h){a(S);return}n==null||n(S)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:v,handleDragOver:N,handleDragLeave:L,handleDrop:d}}function wp(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function jp({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),v=o.useRef(null),N=o.useRef(n),L=o.useRef(a);o.useEffect(()=>{N.current=n},[n]),o.useEffect(()=>{L.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(k=>{const y=wp(k,e);return y.length===k.length&&y.every((x,E)=>x===k[E])?k:y})},[e]);const d=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const y=new Map(k.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const I=y.get(x.tabKey)??999,M=y.get(E.tabKey)??999;return I-M})},[e,p,l]);o.useEffect(()=>{var y,x;if(d.length===0){i!==null&&(c(null),(y=N.current)==null||y.call(N,null));return}if(i&&d.some(E=>E.tabKey===i))return;const k=d[0].tabKey;k!==i&&(c(k),(x=N.current)==null||x.call(N,k))},[d,i]);const b=o.useMemo(()=>d.find(k=>k.tabKey===i),[d,i]),S=o.useCallback(k=>{var y;c(k),(y=N.current)==null||y.call(N,k)},[]),h=o.useCallback((k,y,x)=>{u(E=>{var W;const I=E.filter(R=>R!==k),M=I.indexOf(y);if(M<0)return E;const T=x==="left"?M:M+1;return I.splice(T,0,k),(W=L.current)==null||W.call(L,I),I}),m(null)},[]),w=o.useCallback((k,y,x)=>{const I=(l.length>0?l:e.map(W=>W.tabKey)).filter(W=>W!==k),M=I.indexOf(y);if(M<0)return;const T=x==="left"?M:M+1;I.splice(T,0,k),f.current=I,m(I)},[l,e]),_=o.useCallback(()=>{var y;const k=f.current;k&&(u(k),(y=L.current)==null||y.call(L,k))},[]),g=o.useCallback(()=>{f.current=null,m(null)},[]),j=o.useCallback(k=>{u(y=>{var E;const x=y.filter(I=>I!==k);return x.push(k),(E=L.current)==null||E.call(L,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:v,selectTab:S,handleTabReorder:h,updatePreviewOrder:w,commitPreviewOrder:_,clearPreviewOrder:g,moveTabToEnd:j,setDraggingTabKey:k=>{v.current=k}}}function kp({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 ha({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1}){if(a)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(Oi,{}),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 Vi="adhdev-tab-shortcuts";function Gi(){try{return JSON.parse(localStorage.getItem(Vi)||"{}")}catch{return{}}}function qi({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Gi()),[l,u]=o.useState(null),p=o.useCallback(f=>{const v=[];return f.metaKey&&v.push(a?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(a?"⌥":"Alt"),f.shiftKey&&v.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(f.key.length===1?f.key.toUpperCase():f.key),v.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(Vi,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){u(null);return}const N=p(v);if(!N)return;const L={...i};for(const[d,b]of Object.entries(L))b===N&&delete L[d];L[l]=N,m(L),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[N,L]of Object.entries(i))if(s.includes(N)&&p(v)===L){v.preventDefault(),r(),n(N);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const Np=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:v,onCommitPreviewOrder:N,onClearPreviewOrder:L,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:S,onOpenContextMenu:h,longPressTimer:w,isGroupActive:_}){const g=Rs(s),j=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",k=g.isReconnecting,y=o.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]),x=o.useCallback(()=>{l.current=null,b(null),N(),L(),d()},[l,b,N,L,d]),E=o.useCallback(H=>{const G=l.current;if(!(!G||G===s.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const A=H.currentTarget.getBoundingClientRect(),$=H.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,$)}},[s.tabKey,l,f]),I=o.useCallback(H=>{H.preventDefault(),H.stopPropagation();const G=H.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=H.currentTarget.getBoundingClientRect(),$=H.clientX<A.left+A.width/2?"left":"right";c.includes(G)?v(G,s.tabKey,$):S&&S(G)}L()},[s.tabKey,c,v,S,L]),M=o.useCallback(H=>{H.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(H=>{H.preventDefault(),h(H.clientX,H.clientY,s.tabKey)},[s.tabKey,h]),W=o.useCallback(H=>{const G=H.touches[0];w.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,w,h]),R=o.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),C=["adhdev-dockview-tab",j,r&&"is-active",_&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:y,onDragEnd:x,onDragOver:E,onDrop:I,onClick:M,onContextMenu:T,onTouchStart:W,onTouchEnd:R,onTouchMove:R,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:g.isGenerating?t.jsx("div",{className:"tab-spinner"}):g.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.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:ct(s),children:ct(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):g.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(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 Sp({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:N,onReceiveTab:L,onHideTab:d,isGroupActive:b,allowTabShortcuts:S=!0}){const[h,w]=o.useState(null),_=o.useRef(null),g=o.useRef(null),j=o.useMemo(()=>e.map(T=>T.tabKey),[e]);Zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:y,shortcutListening:x,setShortcutListening:E,saveShortcuts:I}=qi({enabled:S,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const T=W=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(W.target)||w(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[h]),o.useEffect(()=>{const T=g.current;if(!T)return;const W=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),T.scrollLeft+=R.deltaY)};return T.addEventListener("wheel",W,{passive:!1}),()=>T.removeEventListener("wheel",W)},[]);const M=o.useCallback((T,W,R)=>{w({x:T,y:W,tabKey:R})},[]);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:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(Np,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:S?y[T.tabKey]:void 0,conversationKeys:j,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:v,onDragTabKeyChange:N,onReceiveTab:L,onOpenContextMenu:M,longPressTimer:_,isGroupActive:b},T.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.y},children:[S&&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:T=>{T.stopPropagation(),E(h.tabKey),w(null)},children:["⌨ ",y[h.tabKey]?`Change shortcut (${y[h.tabKey]})`:"Set shortcut"]}),y[h.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 T={...y};delete T[h.tabKey],I(T),w(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[S&&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(h.tabKey),w(null)},children:"🚫 Hide from Dashboard"})]})]}),S&&x&&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:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.stopPropagation(),children:[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. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+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 Cp({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:v,numGroups:N,onMoveTab:L,onReceiveTab:d,style:b,onActiveTabChange:S,initialActiveTabId:h,initialTabOrder:w,onTabOrderChange:_,onHideTab:g,isFocused:j,allowTabShortcuts:k=!0}){const{sendCommand:y}=_t(),x=o.useRef(null),{activeTabId:E,activeConv:I,sortedConversations:M,draggingTabRef:T,selectTab:W,handleTabReorder:R,updatePreviewOrder:C,commitPreviewOrder:H,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:$}=jp({conversations:e,initialActiveTabId:h,initialTabOrder:w,onActiveTabChange:S,onTabOrderChange:_}),B=Vr({sendDaemonCommand:a,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:O,dropAction:X,resetDragState:je,handleDragEnter:$e,handleDragOver:me,handleDragLeave:_e,handleDrop:ae}=vp({conversations:e,numGroups:N,onMoveTab:L,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),ee=I&&!qe(I)&&Is(I)==="terminal",se=o.useMemo(()=>I?s.find(Z=>Z.id===I.routeId):void 0,[s,I]),ue=o.useMemo(()=>I?n.filter(Z=>Z.routeId===I.tabKey):[],[n,I]),re=o.useMemo(()=>zr(s),[s]),z=o.useMemo(()=>new Set(M.filter(Z=>Dl(Z,re,{isOpenConversation:Z.tabKey===E})).map(Z=>Z.tabKey)),[E,re,M]);Zs("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:E,dragOver:O});const le=o.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&y(Z.routeId,"focus_session",{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[y]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:O?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Sp,{conversations:M,activeTabId:E,groupIndex:m,numGroups:N,unreadTabKeys:z,draggingTabRef:T,onFocus:f,onSelectTab:W,onConversationActivated:le,onPreviewReorder:C,onReorderTab:R,onCommitPreviewOrder:H,onClearPreviewOrder:G,onDragStateReset:je,onDragTabKeyChange:$,onMoveTab:L,onReceiveTab:d,onHideTab:g,isGroupActive:j??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:$e,onDragOver:me,onDragLeave:_e,onDrop:ae,children:[O&&t.jsx(kp,{dropAction:X,canSplit:!!(N<4&&L)}),I?t.jsx(fa,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ee,ideEntry:se,terminalRef:x,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,isSendingChat:B.isSendingChat,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:ue,userName:p,isInputActive:!v||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ha,{conversationsCount:e.length,isSplitMode:v,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Ip({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:v,userName:N,focusedGroup:L,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:S,closeGroup:h,handleResizeStart:w,groupActiveTabIds:_,setGroupActiveTabIds:g,groupTabOrders:j,setGroupTabOrders:k,toggleHiddenTab:y,allowTabShortcuts:x=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((E,I)=>{const M=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(rt.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:T=>w(I-1,T),onDoubleClick:()=>h(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(Cp,{style:s?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:E,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:v,userName:N,groupIndex:I,isFocused:s&&L===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(T,W)=>{W==="left"&&I>0?b(T,I-1):W==="right"&&I<r-1?b(T,I+1):W==="split-left"&&r<4?S(T,I,"left"):W==="split-right"&&r<4&&S(T,I,"right")},onReceiveTab:T=>b(T,I),onActiveTabChange:T=>g(W=>(W[I]??null)===(T??null)?W:{...W,[I]:T}),initialActiveTabId:_[I],initialTabOrder:j[I],onTabOrderChange:T=>k(W=>{const R=W[I]||[];return R.length===T.length&&R.every((C,H)=>C===T[H])?W:{...W,[I]:T}}),onHideTab:y,allowTabShortcuts:x})]},I)})})}function Yi({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?mt.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const v=new FileReader;v.onload=()=>i(v.result),v.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=mt.onStatus)==null?void 0:m.call(mt,(f,v)=>{f===e&&v!=null&&v.screenshotUsage&&l(v.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?mt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?mt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Xi="adhdev-dashboard-action-shortcuts",Ap=1200,Tp={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Mp(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(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 Qi(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function Wn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Br(e){const s=Object.fromEntries(Qi(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Xi)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Tp))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Ji(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Lp({enabled:e=!0,onTrigger:s}){const r=Mp(),[n,a]=o.useState(()=>Br(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.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(Ji(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(Xi,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Br(r),b=Object.entries(n),S=Object.entries(d);b.length===S.length&&b.every(([h,w])=>d[h]===w)||f(d)},[n,r,f]);const v=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),N=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Ap))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const S=m(b);if(!S)return;const w=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(S);if(l.length===0&&w){u([S]);return}const g=[...l,S].slice(0,2).join(" "),j={...n};for(const[k,y]of Object.entries(j))y===g&&delete j[k];j[i]=g,f(j),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const S=m(b);if(!S)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Wn(b.target)&&!h)return;const w=p.current.parts,_=h?[S]:[...w.slice(-1),S].slice(-2),g=_.join(" "),j=_[_.length-1],k=Object.entries(n).filter(([,M])=>!!M),y=k.find(([,M])=>M===g);if(y){b.preventDefault(),v(),s(y[0]);return}if(k.some(([,M])=>M.startsWith(`${g} `))){b.preventDefault(),p.current.parts=_,N();return}const E=k.find(([,M])=>M===j);if(E){b.preventDefault(),v(),s(E[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){b.preventDefault(),p.current.parts=[j],N();return}v()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,N,e,m,s,v,i]),o.useEffect(()=>()=>v(),[v]);const L=o.useMemo(()=>Qi(r),[r]);return{isMac:r,actionDefinitions:L,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function _p({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut"}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}const Zi=o.createContext(null);function Qr(){const e=o.useContext(Zi);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Cr(e){return ct(e)||e.tabKey}function Rp(e){return`remote:${e}`}function Ft(e){return e.startsWith("remote:")}function xo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function bn(e){var r,n,a,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=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function br(e,s){e.classList.remove(In.className,An.className),e.classList.add(s==="light"?In.className:An.className)}function ho(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 Pp(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Dp(e,s,r){var l;const n=[s];let a;for(const u of n){let p;for(const m of u){const f=e.addPanel({id:m.tabKey,component:"conversation",title:Cr(m),params:{kind:"conversation",tabKey:m.tabKey},...p?{position:{referencePanel:p,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});p||(p=f.id)}a=p??a}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 bo(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 a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Cr(n)&&a.api.setTitle(Cr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Cr(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 go(e,s,r){var u,p;const n=r?Rp(r):null;for(const m of[...e.panels])Ft(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=mi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(m=>!Ft(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Ep({params:e,api:s}){var f;const r=Qr(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Vr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const v=[s.onDidActiveChange(N=>i(N.isActive)),s.onDidActiveGroupChange(N=>{if(!s.isActive&&!N.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const N of v)N.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(v=>v.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(v=>v.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(ha,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!qe(c)&&Is(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(fa,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function $p({params:e}){var u;const s=Qr(),r=o.useMemo(()=>Bt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Yi({doId:a,targetSessionId:r?ea(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(Fo,{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 Bp(){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(ha,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Kp(e){var N,L;Pp(e);const s=Qr(),r=o.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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,S=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${S?" 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 a=((L=e.api.group.activePanel)==null?void 0:L.id)===e.api.id,i=e.api.isGroupActive,c=Xn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,v=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(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:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?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:"○"}):u?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:ct(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),v&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function Wp({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:v,registerActionHandlers:N,onActiveTabChange:L,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:S,scrollToBottomRequest:h,notificationStateBySessionId:w}){var q,Be,Re;const{theme:_}=la(),{sendCommand:g}=_t(),j=o.useRef(null),k=o.useRef(null),y=o.useRef(!1),x=o.useRef(!1),E=o.useRef(!1),I=o.useRef(null),M=o.useRef([]),[T,W]=o.useState(null),[R,C]=o.useState(!1),[H,G]=o.useState(!1),[A,$]=o.useState(0),B=o.useRef(null),O=o.useMemo(()=>$i(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:Cm(O)),je=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),$e=o.useMemo(()=>zr(r),[r]),me=o.useMemo(()=>{const K=j.current;return K?K.groups.some(U=>{try{const F=U.model.location.type;return F!=="floating"&&F!=="popout"?!1:U.panels.some(V=>je.has(V.id))}catch{return!1}}):!1},[je,A,e]),_e=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),ae=o.useCallback(K=>{const U=document,F=K.document;for(const Ce of U.querySelectorAll('link[rel="stylesheet"]')){const We=F.createElement("link");We.rel="stylesheet",We.href=Ce.href,Ce.crossOrigin&&(We.crossOrigin=Ce.crossOrigin),F.head.appendChild(We)}for(const Ce of U.querySelectorAll("style")){const We=F.createElement("style");We.textContent=Ce.textContent,F.head.appendChild(We)}const V=[];for(const Ce of U.styleSheets)try{for(const We of Ce.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&V.push(We.cssText)}catch{}if(V.length>0){const Ce=F.createElement("style");Ce.textContent=V.join(`
|
|
44
|
-
`),F.head.appendChild(Ce)}const ne=U.documentElement.getAttribute("data-theme");ne&&F.documentElement.setAttribute("data-theme",ne),F.documentElement.style.colorScheme=ne==="light"?"light":"dark",F.body.className=U.body.className;const we=U.documentElement.getAttribute("style");we&&F.documentElement.setAttribute("style",we);const Ie=F.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),br(Ie,_))},[_]),ee=o.useCallback(()=>{var U;const K=j.current;if(K)for(const F of K.groups)try{const V=(U=F.element)==null?void 0:U.ownerDocument;if(!V||V===document)continue;const ne=V.getElementById("dv-popout-window");ne instanceof HTMLElement&&(ne.classList.add("adhdev-dockview"),br(ne,_));const we=document.documentElement.getAttribute("data-theme");we&&V.documentElement.setAttribute("data-theme",we),V.documentElement.style.colorScheme=we==="light"?"light":"dark",V.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie?V.documentElement.setAttribute("style",Ie):V.documentElement.removeAttribute("style")}catch{}},[_]),se=o.useCallback(()=>{var U;const K=j.current;if(K)for(const F of K.groups)try{const V=(U=F.element)==null?void 0:U.ownerDocument;if(!V||V===document)continue;const ne=V.getElementById("dv-popout-window");if(!(ne instanceof HTMLElement))continue;ne.classList.add("adhdev-dockview"),br(ne,_),ne.classList.toggle("is-showing-dockview-overlay",H),ne.classList.toggle("is-dragging-dockview",R)}catch{}},[R,H,_]),ue=o.useCallback(K=>{const U=j.current;if(!U)return;const F=U.getPanel(K);F&&U.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{ae(V),ge();const ne=je.get(K);V.document.title=ne?`${ct(ne)} — ADHDev`:"ADHDev — Popout"}})},[je,ae]),re=o.useCallback(K=>{const U=j.current,F=U==null?void 0:U.getPanel(K);if(!U||!F)return;const V=U.groups.filter(ne=>{var we;try{return((we=ne.element)==null?void 0:we.ownerDocument)===document}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),z=o.useCallback(K=>{var V;const U=j.current;if(!U)return!1;const F=U.getPanel(K);if(!F)return!1;try{return((V=F.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),le=o.useCallback(K=>{z(K)&&re(K),f(K)},[z,re,f]),Z=o.useCallback(K=>{const U=j.current,F=U==null?void 0:U.getPanel(K);!U||!F||U.addFloatingGroup(F,{width:600,height:500})},[]),ie=o.useCallback(K=>{var F;const U=(F=j.current)==null?void 0:F.getPanel(K);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),Q=o.useCallback(()=>{var U,F;const K=(F=(U=j.current)==null?void 0:U.activePanel)==null?void 0:F.id;return!K||Ft(K)?null:je.has(K)?K:null},[je]),de=o.useCallback(K=>{const U=j.current,F=U==null?void 0:U.getPanel(K);if(!U||!F)return;const V=U.groups.filter(ne=>{try{return ne.model.location.type==="grid"}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),oe=o.useCallback(()=>{var we;const K=j.current;if(!K)return;const F=K.groups.filter(Ie=>{var Ce;try{return((Ce=Ie.element)==null?void 0:Ce.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...K.panels];for(const Ie of V){const Ce=(we=Ie.group.element)==null?void 0:we.ownerDocument,We=Ie.group.model.location.type;Ce===document&&We==="grid"||(F&&F.id!==Ie.group.id?Ie.api.moveTo({group:F,position:"center"}):Ie.api.moveTo({position:"center"}))}const ne=K.activePanel;ne&&(ne.group.model.openPanel(ne),ne.api.setActive()),bn(document)},[]),ge=o.useCallback(()=>{var U,F;const K=j.current;if(K)for(const V of K.groups){const ne=(U=V.element)==null?void 0:U.ownerDocument;if(!ne||ne===document)continue;const we=ne.getElementById("dv-popout-window");if(!(we instanceof HTMLElement))continue;let Ie=null,Ce=ne.title||"ADHDev",We="Popout workspace";const Oe=V.activePanel;if(Oe)if(Ie=Oe.id,Ft(Oe.id)){const Ae=((F=Oe.params)==null?void 0:F.routeId)||Oe.id.slice(7),Ke=Bt([...je.values()],Ae);Ce=mi(Ke),We=Ke!=null&&Ke.machineName?`Remote view · ${Ke.machineName}`:"Remote view"}else{const Ae=je.get(Oe.id);Ce=Ae?ct(Ae):Oe.title||Oe.id,We=Ae?ts(Ae):"Dockview panel"}ne.title=`${Ce} — ADHDev`;let Je=ne.getElementById("adhdev-popout-header");Je instanceof HTMLElement||(Je=ne.createElement("div"),Je.id="adhdev-popout-header",ne.body.appendChild(Je)),Je.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(";")),Je.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;">${xo(Ce)}</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;">${xo(We)}</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
|
-
`,we.style.top="52px",we.style.height="calc(100% - 52px)";const Le=Je.querySelector("[data-adhdev-popout-focus]");Le&&(Le.onclick=()=>{window.focus()});const te=Je.querySelector("[data-adhdev-popout-dock]");te&&(te.disabled=!Ie,te.style.opacity=Ie?"1":"0.5",te.style.cursor=Ie?"pointer":"default",te.onclick=()=>{var Ae;Ie&&re(Ie),(Ae=ne.defaultView)==null||Ae.focus()})}},[je,re]),fe=o.useCallback(K=>{var V;const U=j.current,F=U==null?void 0:U.getPanel(K);if(!(!U||!F)){F.group.model.openPanel(F),F.api.setActive();try{const ne=F.group.model.location;ne.type==="popout"?ne.getWindow().focus():bn((V=F.group.element)==null?void 0:V.ownerDocument)}catch{}}},[]),D=o.useCallback(K=>{const U=j.current,F=U==null?void 0:U.activePanel,V=(U==null?void 0:U.activeGroup)||(F==null?void 0:F.group);if(!U||!F||!V)return;const ne=V.panels||[];if(ne.length<=1)return;const we=ne.findIndex(We=>We.id===F.id);if(we<0)return;const Ie=(we+K+ne.length)%ne.length,Ce=ne[Ie];Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive())},[]),ye=o.useCallback(K=>{var te;const U=j.current,F=(U==null?void 0:U.activeGroup)||((te=U==null?void 0:U.activePanel)==null?void 0:te.group);if(!U||!F)return;const V=U.groups||[],ne=V.find(Ae=>Ae.id===F.id);if(!ne)return;const we=ne.element.getBoundingClientRect(),Ie=we.left+we.width/2,Ce=we.top+we.height/2,We=(Ae,Ke,P,Y)=>Math.max(0,Math.min(Ke,Y)-Math.max(Ae,P)),Oe=Ae=>{const Ke=Ae.element.getBoundingClientRect(),P=Ke.left+Ke.width/2,Y=Ke.top+Ke.height/2;let ce=0,Pe=0,Te=0,Ee=!1;if(K==="left"?(Ee=P<Ie,ce=Math.max(0,we.left-Ke.right),Pe=Math.abs(Y-Ce),Te=We(we.top,we.bottom,Ke.top,Ke.bottom)):K==="right"?(Ee=P>Ie,ce=Math.max(0,Ke.left-we.right),Pe=Math.abs(Y-Ce),Te=We(we.top,we.bottom,Ke.top,Ke.bottom)):K==="above"?(Ee=Y<Ce,ce=Math.max(0,we.top-Ke.bottom),Pe=Math.abs(P-Ie),Te=We(we.left,we.right,Ke.left,Ke.right)):(Ee=Y>Ce,ce=Math.max(0,Ke.top-we.bottom),Pe=Math.abs(P-Ie),Te=We(we.left,we.right,Ke.left,Ke.right)),!Ee)return Number.POSITIVE_INFINITY;const ve=Te>0?0:120;return ce*3+Pe+ve};let Je=null,Le=Number.POSITIVE_INFINITY;for(const Ae of V){if(Ae.id===ne.id)continue;const Ke=Oe(Ae);Number.isFinite(Ke)&&(Ke>=Le||(Le=Ke,Je=Ae))}return Je||void 0},[]),be=o.useCallback(K=>{var V;const U=ye(K);if(!U)return;const F=U.activePanel||U.panels[0];F&&(U.model.openPanel(F),F.api.setActive(),bn((V=U.element)==null?void 0:V.ownerDocument))},[ye]),Ne=o.useCallback((K,U)=>{const F=j.current,V=F==null?void 0:F.activePanel,ne=(F==null?void 0:F.activeGroup)||(V==null?void 0:V.group);if(!F||!V||!ne)return;let we=ye(K);!we&&(U!=null&&U.createGroupIfMissing)&&(we=F.addGroup({referenceGroup:ne,direction:K})),we&&(V.api.moveTo({group:we,position:"center"}),V.group.model.openPanel(V),V.api.setActive())},[ye]),{isMac:J,tabShortcuts:Se,shortcutListening:Ue,setShortcutListening:De,saveShortcuts:Ve}=qi({sortedTabKeys:e.map(K=>K.tabKey),onFocus:_e,onSelectTab:fe}),Ye=o.useCallback(()=>{var F;const K=j.current;if(!K)return;const U=K.activePanel;if(U){if(Ft(U.id)){const V=((F=U.params)==null?void 0:F.routeId)||U.id.slice(7),ne=Bt(e,V);ne!=null&&ne.tabKey&&De(ne.tabKey);return}je.has(U.id)&&De(U.id)}},[je,fe,De,e]),Xe=o.useCallback(K=>{const U=[];return K.metaKey&&U.push(J?"⌘":"Meta"),K.ctrlKey&&U.push("Ctrl"),K.altKey&&U.push(J?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&U.push(J?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(U.push(Ji(K.key)),U.join("+"))},[J]),pt=o.useCallback(K=>{var U,F;switch(K){case"splitActiveTabRight":Ne("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ne("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=Q();V&&Z(V);return}case"popoutActiveTab":{const V=Q();V&&ue(V);return}case"dockActiveTab":{const V=Q();if(!V)return;z(V)?re(V):ie(V)&&de(V);return}case"focusLeftPane":be("left");return;case"focusRightPane":be("right");return;case"focusUpPane":be("above");return;case"focusDownPane":be("below");return;case"moveActiveTabToLeftPane":Ne("left");return;case"moveActiveTabToRightPane":Ne("right");return;case"moveActiveTabToUpPane":Ne("above");return;case"moveActiveTabToDownPane":Ne("below");return;case"selectPreviousGroupTab":D(-1);return;case"selectNextGroupTab":D(1);return;case"setActiveTabShortcut":Ye();return;case"hideCurrentTab":{const V=(F=(U=j.current)==null?void 0:U.activePanel)==null?void 0:F.id;V&&!Ft(V)&&le(V);return}default:return}},[D,de,be,Z,Q,le,ie,z,re,Ne,ue,Ye]);o.useEffect(()=>{if(!T)return;const K=T.sourceDocument,U=K.defaultView??window,F=V=>{const ne=K.querySelector("[data-dockview-tab-context-menu]");ne&&ne.contains(V.target)||W(null)};return U.addEventListener("mousedown",F,!0),U!==window&&window.addEventListener("mousedown",()=>W(null),!0),()=>{U.removeEventListener("mousedown",F,!0),U!==window&&window.removeEventListener("mousedown",()=>W(null),!0)}},[T]);const Ge=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:je,hasDetachedConversationPanels:me,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:$e,notificationStateBySessionId:w,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:le,userName:m,scrollToBottomRequest:h,tabShortcuts:Se,openTabContextMenu:({x:K,y:U,tabKey:F,sourceDocument:V})=>W({x:K,y:U,tabKey:F,sourceDocument:V??document}),popoutTab:ue,moveTabBackToMain:re,isTabInPopout:z,floatTab:Z,isTabFloating:ie}),[n,s,je,me,r,l,u,$e,w,a,c,i,le,m,h,Se,ue,re,z,Z,ie]),bt=T?_p({isTabInPopout:z(T.tabKey),isTabFloating:ie(T.tabKey),tabShortcut:Se[T.tabKey],actionShortcuts:v}):[],lt=o.useCallback(K=>{if(!K)return!1;const U=j.current;if(!U)return!1;const F=U.getPanel(K);return F?(F.group.model.openPanel(F),F.api.setActive(),S==null||S(),!0):!1},[S]),dt=o.useCallback(()=>{if(E.current)return!1;const K=lt(I.current);return K&&(E.current=!0),K},[lt]),xt=o.useCallback(()=>{var U;const K=j.current;K&&Sm(O,{activeTabId:((U=K.activePanel)==null?void 0:U.id)??null,layout:K.toJSON()})},[O]),at=o.useCallback(()=>{Im(O,X.current)},[O]),pe=o.useCallback(K=>{var V,ne,we,Ie;const U=j.current;if(!U)return{kind:"grid"};const F=U.toJSON();for(const Ce of F.floatingGroups||[])if((ne=(V=Ce.data)==null?void 0:V.views)!=null&&ne.includes(K)&&Ce.position)return{kind:"floating",position:Ce.position};for(const Ce of F.popoutGroups||[])if((Ie=(we=Ce.data)==null?void 0:we.views)!=null&&Ie.includes(K))return{kind:"popout",position:Ce.position,popoutUrl:Ce.url};return{kind:"grid"}},[]),Fe=o.useCallback(K=>{const U=j.current;if(!U)return;const F=U.getPanel(K),V=X.current[K];if(!F||!V||V.kind==="grid")return;if(F.group.model.location.type===V.kind){delete X.current[K],at();return}if(V.kind==="floating"){U.addFloatingGroup(F,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete X.current[K],at();return}delete X.current[K],at()},[at]);o.useEffect(()=>(N==null||N({setShortcutForActiveTab:Ye,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:fe,resetAllPanelsToMain:oe,activatePreviousTabInGroup:()=>D(-1),activateNextTabInGroup:()=>D(1),floatActiveTab:()=>{const K=Q();K&&Z(K)},popoutActiveTab:()=>{const K=Q();K&&ue(K)},dockActiveTab:()=>{const K=Q();K&&(z(K)?re(K):ie(K)&&de(K))},splitActiveTabRight:()=>Ne("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ne("below",{createGroupIfMissing:!0}),focusLeftPane:()=>be("left"),focusRightPane:()=>be("right"),focusUpPane:()=>be("above"),focusDownPane:()=>be("below"),moveActiveTabToLeftPane:()=>Ne("left"),moveActiveTabToRightPane:()=>Ne("right"),moveActiveTabToUpPane:()=>Ne("above"),moveActiveTabToDownPane:()=>Ne("below")}),()=>N==null?void 0:N(null)),[D,de,Z,be,Q,ie,z,Ne,re,ue,N,oe,Fe,fe,Ye]);const Qe=o.useCallback(()=>{const K=k.current;if(!K)return;const U=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of U)F.setAttribute("data-adhdev-force-hidden","true")},[]),et=o.useCallback(()=>{const K=k.current;if(!K)return;const U=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of U)F.removeAttribute("data-adhdev-force-hidden")},[]),ht=o.useCallback(()=>{const K=k.current;if(!K)return;const U=K.querySelectorAll(".dv-drop-target-container");for(const ne of U)ne.remove();const F=K.querySelectorAll(".dv-drop-target-dropzone");for(const ne of F)ne.remove();const V=K.querySelectorAll(".dv-drop-target");for(const ne of V)ne.classList.remove("dv-drop-target")},[]),yt=o.useCallback(()=>{C(!1),G(!1),et(),Qe(),ht(),!(typeof window>"u")&&(B.current!=null&&window.clearTimeout(B.current),window.requestAnimationFrame(()=>{Qe(),ht()}),B.current=window.setTimeout(()=>{Qe(),ht(),B.current=null},80))},[et,Qe,ht]),Rt=o.useCallback(K=>{var F;j.current=K.api;const U=Nm(O);I.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&K.api.fromJSON(U.layout,{reuseExistingPanels:!1}),x.current=!!(U!=null&&U.layout)&&!p&&e.length===0,x.current||(bo(K.api,e),go(K.api,e,b)),K.api.totalPanels===0&&e.length>0?Dp(K.api,e,d):!x.current&&!lt(d)&&dt(),y.current=!0,K.api.onDidActivePanelChange(V=>{var we;if(I.current=(V==null?void 0:V.id)??null,E.current=!0,ge(),V&&Ft(V.id)){const Ie=((we=V.params)==null?void 0:we.routeId)||V.id.slice(7),Ce=Bt(e,Ie);L((Ce==null?void 0:Ce.tabKey)??null),xt();return}if(L((V==null?void 0:V.id)??null),xt(),!V)return;const ne=je.get(V.id);(ne==null?void 0:ne.streamSource)==="agent-stream"&&ne.agentType&&g(ne.routeId,"focus_session",{agentType:ne.agentType,...ne.sessionId&&{targetSessionId:ne.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{xt(),ge(),$(V=>V+1)}),K.api.onWillDragPanel(()=>{C(!0),G(!1),Qe()}),K.api.onWillDragGroup(()=>{C(!0),G(!1),Qe()}),K.api.onWillShowOverlay(()=>{et(),G(!0)}),K.api.onDidMovePanel(yt),K.api.onDidDrop(yt),K.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var ne,we;try{const Ie=(ne=V.element)==null?void 0:ne.ownerDocument;if(!Ie||Ie===document)return;(we=Ie.getElementById("dv-popout-window"))==null||we.classList.add("adhdev-dockview");const Ce=document.documentElement.getAttribute("data-theme");Ce&&Ie.documentElement.setAttribute("data-theme",Ce),Ie.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&Ie.documentElement.setAttribute("style",We)}catch{}ge(),$(Ie=>Ie+1)})}),L(((F=K.api.activePanel)==null?void 0:F.id)??null)},[lt,yt,et,je,p,O,Qe,ht,L,xt,d,b,g,ge,e]);o.useLayoutEffect(()=>{const K=j.current;if(!K||!y.current||x.current&&!p)return;x.current&&(x.current=!1);const U=M.current,F=new Set(U),V=e.map(Oe=>Oe.tabKey),ne=new Set(V);let we=!1;for(const Oe of U)ne.has(Oe)||(X.current[Oe]=pe(Oe),we=!0);we&&at(),bo(K,e),go(K,e,b);const Ie=V.filter(Oe=>!F.has(Oe));let Ce=!1;for(const Oe of Ie){const Je=K.getPanel(Oe),Le=X.current[Oe];if(!Je||!Le||Le.kind==="grid")continue;if(Je.group.model.location.type===Le.kind){delete X.current[Oe],Ce=!0;continue}if(Le.kind==="floating"){K.addFloatingGroup(Je,{x:Le.position.left??24,y:Le.position.top??24,width:Le.position.width,height:Le.position.height}),delete X.current[Oe],Ce=!0;continue}}if(Ce&&at(),M.current=V,d&<(d))return;!K.activePanel&&K.panels[0]&&(K.panels[0].group.model.openPanel(K.panels[0]),K.panels[0].api.setActive()),!!(K.activePanel&&K.getPanel(K.activePanel.id))||dt()},[lt,dt,p,at,pe,d,b,e]),o.useEffect(()=>{y.current&<(d)},[lt,d]),o.useEffect(()=>{if(!R||typeof window>"u")return;const K=()=>yt();return window.addEventListener("pointerup",K),window.addEventListener("mouseup",K),window.addEventListener("dragend",K),()=>{window.removeEventListener("pointerup",K),window.removeEventListener("mouseup",K),window.removeEventListener("dragend",K)}},[yt,R]),o.useEffect(()=>()=>{typeof window>"u"||B.current!=null&&window.clearTimeout(B.current)},[]),o.useEffect(()=>{const K=F=>{const V=F.target;if(!V)return;const ne=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(ne){const we=ne.getAttribute("data-tab-key");if(we&&F.dataTransfer){const Ie=V.closest(".dv-tab")||ne.closest(".dv-tab")||ne;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",we),Ie instanceof HTMLElement&&F.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",K);const U=ho(j.current);for(const F of U)F.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const F of U)F.removeEventListener("dragstart",K)}},[A]),o.useEffect(()=>{var U;const K=(U=k.current)==null?void 0:U.querySelector(".adhdev-dockview");K instanceof HTMLElement&&br(K,_),ee(),ge(),se()},[ge,se,ee,_]),o.useEffect(()=>{ge(),se()},[ge,se]),o.useEffect(()=>{const K=U=>{if(U.defaultPrevented||Ue)return;const F=Xe(U);if(!F)return;const V=U.metaKey||U.ctrlKey||U.altKey;Wn(U.target)&&!V||Br(J).setActiveTabShortcut!==F||(U.preventDefault(),U.stopPropagation(),Ye())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[Xe,J,Ue,Ye]),o.useEffect(()=>{const K=k.current;if(!K)return;const U=F=>{var Ce,We;if(!F.isTrusted)return;const V=(We=(Ce=F.target)==null?void 0:Ce.closest)==null?void 0:We.call(Ce,".dv-scrollable");if(!V)return;F.preventDefault(),F.stopPropagation();const ne=Math.abs(F.deltaX),we=Math.abs(F.deltaY),Ie=ne>we?F.deltaX:F.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",U,{capture:!0})},[]),o.useEffect(()=>{const K=ho(j.current);if(K.length===0)return;const U=K.map(F=>{let V=[],ne=null;const we=()=>{ne!=null&&F.clearTimeout(ne),ne=null,V=[]},Ie=()=>{ne!=null&&F.clearTimeout(ne),ne=F.setTimeout(()=>{ne=null,V=[]},1200)},Ce=Oe=>{if(!Oe.ctrlKey&&!Oe.metaKey&&!Oe.altKey)return;const Je=Xe(Oe);if(!Je)return;const Le=Gi();for(const[te,Ae]of Object.entries(Le))if(e.some(Ke=>Ke.tabKey===te)&&Ae===Je){Oe.preventDefault(),fe(te);return}},We=Oe=>{if(Oe.defaultPrevented||Ue)return;const Je=Xe(Oe);if(!Je)return;const Le=Oe.metaKey||Oe.ctrlKey||Oe.altKey;if(Wn(Oe.target)&&!Le)return;const te=Br(J),Ae=Object.entries(te).filter(([ve,tt])=>!!tt&&(ve==="splitActiveTabRight"||ve==="splitActiveTabDown"||ve==="floatActiveTab"||ve==="popoutActiveTab"||ve==="dockActiveTab"||ve==="focusLeftPane"||ve==="focusRightPane"||ve==="focusUpPane"||ve==="focusDownPane"||ve==="moveActiveTabToLeftPane"||ve==="moveActiveTabToRightPane"||ve==="moveActiveTabToUpPane"||ve==="moveActiveTabToDownPane"||ve==="selectPreviousGroupTab"||ve==="selectNextGroupTab"||ve==="setActiveTabShortcut"||ve==="hideCurrentTab")),Ke=Le?[Je]:[...V.slice(-1),Je].slice(-2),P=Ke.join(" "),Y=Ke[Ke.length-1],ce=Ae.find(([,ve])=>ve===P);if(ce){Oe.preventDefault(),we(),pt(ce[0]);return}if(Ae.some(([,ve])=>ve.startsWith(`${P} `))){Oe.preventDefault(),V=Ke,Ie();return}const Te=Ae.find(([,ve])=>ve===Y);if(Te){Oe.preventDefault(),we(),pt(Te[0]);return}if(Ae.some(([,ve])=>ve.startsWith(`${Y} `))){Oe.preventDefault(),V=[Y],Ie();return}we()};return F.addEventListener("keydown",Ce),F.addEventListener("keydown",We),()=>{we(),F.removeEventListener("keydown",Ce),F.removeEventListener("keydown",We)}});return()=>{for(const F of U)F()}},[Xe,J,A,fe,Ue,pt,e]);const Nt=_==="light"?In:An,At=((Re=(Be=(q=j.current)==null?void 0:q.activePanel)==null?void 0:Be.group.element)==null?void 0:Re.ownerDocument)??document;return t.jsxs(Zi.Provider,{value:Ge,children:[t.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Pc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${H?" is-showing-dockview-overlay":""}`,components:{conversation:Ep,remote:$p},defaultTabComponent:Kp,watermarkComponent:Bp,onReady:Rt,singleTabMode:"default",tabAnimation:"smooth",theme:Nt,popoutUrl:"/popout.html"})}),T&&qs.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:bt.map(K=>{if(K.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let U=t.jsx(bl,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":U=t.jsx(yl,{size:13,className:"shrink-0 opacity-70"}),F=()=>{de(T.tabKey),W(null)};break;case"moveBackToMain":U=t.jsx(hl,{size:13,className:"shrink-0 opacity-70"}),F=()=>{re(T.tabKey),W(null)};break;case"floatAsPanel":U=t.jsx(gl,{size:13,className:"shrink-0 opacity-70"}),F=()=>{Z(T.tabKey),W(null)};break;case"openInNewWindow":U=t.jsx(xl,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(T.tabKey),W(null)};break;case"setShortcut":F=V=>{V.stopPropagation(),De(T.tabKey),W(null)};break;case"removeShortcut":U=t.jsx(kt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const V={...Se};delete V[T.tabKey],Ve(V),W(null)};break;case"hideTab":U=t.jsx(Wo,{size:13,className:"shrink-0 opacity-70"}),F=()=>{le(T.tabKey),W(null)};break}return 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 ${K.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[U,t.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),T.sourceDocument.body),Ue&&qs.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:()=>De(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.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"})]})}),At.body)]})}const ec="adhdev-recent-launch-args-v1",Op=8;function Hp(e){return String(e||"").trim().replace(/\s+/g," ")}function tc(e,s){return`${e.trim()}::${s.trim()}`}function sc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ec)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Up(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ec,JSON.stringify(e))}catch{}}function rc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=sc().byKey[tc(r,n)])==null?void 0:i.items)||[]}function nc(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=Hp(r);if(!n||!a||!i)return;const c=sc(),l=tc(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Op);c.byKey[l]={items:p},Up(c)}function zp(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 ba(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 ac(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=ba((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function oc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ks(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 gn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Fp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function yo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function vo(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 a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Vp(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Gp(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 qp(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Yp({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var G;const[l,u]=o.useState(n||((G=e[0])==null?void 0:G.id)||null),[p,m]=o.useState(""),[f,v]=o.useState(null),[N,L]=o.useState(!1);o.useEffect(()=>{var A;u(n||((A=e[0])==null?void 0:A.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(A=>A.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const $=Fp(A.daemonId||A.id);return!!(d!=null&&d.id)&&$===d.id}),[d==null?void 0:d.id,r]),S=Li(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=S.diagnostics,w=S.loading,_=S.applyDiagnostics,g=o.useMemo(()=>{const A=new Map;for(const $ of b){const B=s.find(O=>O.sessionId===$.sessionId||O.routeId===$.id);$.sessionId&&B&&A.set($.sessionId,B)}return A},[b,s]),j=o.useCallback(async()=>{if(d!=null&&d.id){L(!0);try{const A=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),$=gn(A);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Could not load hosted runtime diagnostics");_($.diagnostics||$.result||null),m("")}catch(A){const $=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";m($)}finally{L(!1)}}},[d==null?void 0:d.id,_,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||w||N||j()},[d==null?void 0:d.id,h,w,j,N]);const k=o.useCallback(async(A,$)=>{if(!(d!=null&&d.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${$.displayName}?
|
|
55
|
-
This will terminate the hosted runtime.`))return;const B=`${A}:${$.sessionId}`;v(B);try{const O=await a(d.id,A,{sessionId:$.sessionId}),X=gn(O);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const je=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${je}: ${$.displayName}`,"success"),await j()}catch(O){const X=O instanceof Error?O.message:"Session host action failed";m(X),it.showToast(X,"warning")}finally{v(O=>O===B?null:O)}},[d==null?void 0:d.id,j,a]),y=o.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.`))){v("session_host_prune_duplicate_sessions");try{const $=await a(d.id,"session_host_prune_duplicate_sessions",{}),B=gn($);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Duplicate prune failed");const O=B.result||{},X=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,je=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;it.showToast(`Pruned ${X} duplicate runtime(s) across ${je} group(s)`,"success"),await j()}catch($){const B=$ instanceof Error?$.message:"Duplicate prune failed";m(B),it.showToast(B,"warning")}finally{v($=>$==="session_host_prune_duplicate_sessions"?null:$)}}},[d==null?void 0:d.id,j,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((A,$)=>($.lastActivityAt||0)-(A.lastActivityAt||0)),[h==null?void 0:h.sessions]),E=o.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:ac(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),I=E.liveRuntimes,M=E.recoverySnapshots,T=E.inactiveRecords,W=o.useMemo(()=>qp(I),[I]),R=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[h==null?void 0:h.recentLogs]),C=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),H=(A,$)=>{var se,ue;const B=g.get(A.sessionId),O=b.find(re=>re.sessionId===A.sessionId),X=f===`session_host_resume_session:${A.sessionId}`,je=f===`session_host_restart_session:${A.sessionId}`,$e=f===`session_host_stop_session:${A.sessionId}`,me=ba(A.meta),_e=typeof((se=A.meta)==null?void 0:se.runtimeRecoveryError)=="string"?String(A.meta.runtimeRecoveryError):"",ae=$==="recovery"?"Recover":"Resume",ee=oc($);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:A.displayName||(O==null?void 0:O.runtimeDisplayName)||(O==null?void 0:O.cliName)||A.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Gp(A.lifecycle)}`,children:A.lifecycle}),me&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:me})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(O==null?void 0:O.runtimeWorkspaceLabel)||A.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:A.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ue=A.writeOwner)==null?void 0:ue.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Vp(A.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(Vn,{size:11})," ",A.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",vo(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:"",` · Next: ${ee}`]}),_e&&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:_e})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[B&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(B),c()},children:"Open chat"}),$==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{k("session_host_resume_session",A)},children:X?`${ae}ing…`:ae}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{k("session_host_restart_session",A)},children:je?"Restarting…":"Restart"}),$==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.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:!!f,onClick:()=>{k("session_host_stop_session",A)},children:$e?"Stopping…":"Stop"})]})]},A.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:A=>A.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(Ot,{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:()=>{j()},disabled:w||N,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(_s,{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(A=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${A.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:()=>u(A.id),children:A.label},A.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:[p&&!h&&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(ds,{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:p})]})]})}),h&&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:h.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:M.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:vo(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:yo(h.hostStartedAt)})]})]}),R&&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(ds,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:R.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(Or,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[W>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{y()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${W}`}),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:ks("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(A=>H(A,"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:ks("recovery")}),M.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:M.map(A=>H(A,"recovery"))})]}),T.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:ks("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:T.map(A=>H(A,"inactive"))})]}),C.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:C.map(A=>{const $=x.find(B=>B.sessionId===A.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:($==null?void 0:$.displayName)||A.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:yo(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Hs({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.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 ic({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Ui(n):null;return t.jsxs(Hs,{title:"Saved history",description:na(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:a,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:cu()})]}),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 yn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xp({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Nt,At;const f=er(),v=o.useMemo(()=>[...e].sort(Qn),[e]),[N,L]=o.useState(((Nt=v[0])==null?void 0:Nt.id)||""),d=o.useMemo(()=>v.find(q=>q.id===N)||v[0],[N,v]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[d]),S=(d==null?void 0:d.defaultWorkspaceId)||null,[h,w]=o.useState(""),[_,g]=o.useState(""),[j,k]=o.useState(yn(v[0])),[y,x]=o.useState(""),[E,I]=o.useState(""),[M,T]=o.useState([]),[W,R]=o.useState(""),[C,H]=o.useState([]),[G,A]=o.useState(!1),[$,B]=o.useState(""),[O,X]=o.useState(!1),[je,$e]=o.useState(()=>gt()),[me,_e]=o.useState(!1),[ae,ee]=o.useState(null),[se,ue]=o.useState(!1),[re,z]=o.useState(""),[le,Z]=o.useState(!1),[ie,Q]=o.useState(""),[de,oe]=o.useState([]),[ge,fe]=o.useState(!1),[D,ye]=o.useState(""),[be,Ne]=o.useState(!1),J=o.useRef(null),Se=o.useRef(0);o.useEffect(()=>{var q;!N&&((q=v[0])!=null&&q.id)&&L(v[0].id)},[N,v]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ue=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[d]),De=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[d]),Ve=o.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]),Ye=o.useMemo(()=>j==="cli"?Ue.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):j==="acp"?De.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):Ve,[De,j,Ue,Ve]);o.useEffect(()=>{var Be;if(!d)return;if(J.current!==d.id){J.current=d.id,w(S||((Be=b[0])==null?void 0:Be.id)||"__home__"),g(""),k(yn(d)),x(""),I(""),R(""),H([]),B(""),$e(gt()),z("");return}w(Re=>{var K;return Re==="__custom__"||Re==="__home__"||b.some(U=>U.id===Re)?Re:S||((K=b[0])==null?void 0:K.id)||"__home__"}),k(Re=>Re==="ide"&&Ve.length>0||Re==="cli"&&Ue.length>0||Re==="acp"&&De.length>0?Re:yn(d))},[De.length,Ue.length,S,Ve.length,d,b]),o.useEffect(()=>{var q;j&&(Ye.some(Be=>Be.id===y)||x(((q=Ye[0])==null?void 0:q.id)||""))},[j,Ye,y]);const Xe=o.useCallback(async(q,Be)=>{const Re=Se.current+1;return Se.current=Re,A(!0),B(""),u(q,Be).then(K=>{Se.current===Re&&H(K)}).catch(K=>{Se.current===Re&&(H([]),B(K instanceof Error?K.message:"Could not load saved sessions"))}).finally(()=>{Se.current===Re&&A(!1)})},[u]),pt=o.useCallback((q,Be)=>{T(rc(q,Be))},[]);o.useEffect(()=>{if(R(""),$e(gt()),!d||!y||j==="ide"?T([]):pt(d.id,y),j!=="cli"){H([]),B(""),A(!1);return}if(!d||!y){H([]),B(""),A(!1);return}Xe(d.id,y)},[j,pt,Xe,d,y]),o.useEffect(()=>{if(!W)return;const q=C.find(Be=>Be.providerSessionId===W);q!=null&&q.canResume||R("")},[C,W]);const Ge=h==="__custom__"?_.trim():h==="__home__"?"":((At=b.find(q=>q.id===h))==null?void 0:At.path)||"",bt=o.useMemo(()=>d?r.filter(q=>q.id!==d.id&&q.daemonId===d.id).map(q=>q.workspace):[],[r,d]),lt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(q=>q.workspace),[d]),dt=o.useCallback(q=>{const Be=String(q.workspace||"").trim();if(!Be)return;const Re=b.find(K=>gr(K.path)===gr(Be));if(Re){w(Re.id),g("");return}w("__custom__"),g(Be)},[b]),xt=o.useCallback(q=>{const Be=String(q.workspace||"").trim();if(!Be)return{workspaceId:null,workspacePath:null};const Re=b.find(K=>gr(K.path)===gr(Be));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Be}},[b]),at=o.useMemo(()=>C.find(q=>q.providerSessionId===W)||null,[C,W]),pe=o.useMemo(()=>{var Be;if(j!=="cli"||!d||!y)return null;const q=((Be=Ue.find(Re=>Re.type===y))==null?void 0:Be.displayName)||y;return{routeId:d.id,daemonId:d.id,providerSessionId:W||void 0,transport:"pty",mode:"chat",agentName:q,agentType:y,status:"idle",title:q,messages:[],ideType:y,workspaceName:Ge,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${y}`,machineName:Ct(d,{fallbackId:d.id})}},[j,Ue,Ge,d,W,y]),Fe=o.useCallback(()=>{var Be;if(!d)return;w("__custom__"),Z(!0),ye("");const q=qr(d.platform,Gr(_.trim(),Ge,bt,lt,d.defaultWorkspacePath,(Be=b.find(Re=>Re.id===S))==null?void 0:Be.path,b.map(Re=>Re.path)));fe(!0),a(d.id,q).then(Re=>{Q(Re.path),g(Re.path),oe(Re.directories)}).catch(Re=>{ye(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>fe(!1))},[_,S,lt,bt,a,Ge,d,b]),Qe=o.useCallback(q=>{d&&(fe(!0),ye(""),a(d.id,q).then(Be=>{Q(Be.path),g(Be.path),oe(Be.directories)}).catch(Be=>{ye(Be instanceof Error?Be.message:"Could not load folder")}).finally(()=>fe(!1)))},[a,d]),et=o.useCallback(async()=>{if(!d||!Ge)return;Ne(!0),z("");const q=await i(d.id,Ge);if(Ne(!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,Ge,d]),ht=o.useCallback(async()=>{if(!d||!j||!y)return;ue(!0),z("");const q=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Be=j==="ide"?await c(d.id,y,{workspacePath:Ge||null}):await l(d.id,j,y,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ge||null,resumeSessionId:j==="cli"&&W?W:null,cliArgs:q});if(ue(!1),!Be.ok){z(Be.error||"Could not start session");return}j!=="ide"&&E.trim()&&(nc(d.id,y,E),pt(d.id,y)),n()},[j,E,pt,n,c,l,Ge,d,W,y,h]),yt=j?fi(j,j==="cli"&&!!W):"Start",Rt=j?xi(j,j==="cli"&&!!W):"Starting…";return d?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm: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-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",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-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(Hs,{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:se,children:v.map(q=>t.jsx("option",{value:q.id,children:Ct(q,{fallbackId:q.id})},q.id))})}),j==="cli"&&t.jsx(Hs,{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:se||!d,onClick:()=>_e(!0),children:[t.jsx(Ot,{size:14}),ou()]})}),t.jsxs(Hs,{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:Fe,disabled:se,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:q=>{const Be=q.target.value;w(Be),Be==="__custom__"?Fe():z("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:se,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(q=>t.jsxs("option",{value:q.id,children:[q.id===S?"⭐ ":"",Fr(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:h==="__home__"?"Launch without a workspace.":Ge||"Select a workspace folder."}),h==="__custom__"&&Ge&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Fe,disabled:se,children:[t.jsx(Ns,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:se||be,children:be?"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:Ue.length>0},{id:"ide",label:"IDE",enabled:Ve.length>0},{id:"acp",label:"ACP",enabled:De.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${j===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>k(q.id),disabled:!q.enabled||se,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:j==="ide"?"Choose IDE":j==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ye.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${y===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(q.id),disabled:se,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)),Ye.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."})]})]}),j!=="ide"&&t.jsxs(Hs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:E,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:se}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>I(q),disabled:se,title:q,children:q},q))})]}),j==="cli"&&t.jsx(ic,{busy:se,savedSessionsLoading:G,savedSessionsError:$,selectedSession:at,onRefresh:()=>{!d||!y||Xe(d.id,y)},onOpenHistory:()=>{!d||!y||(X(!0),Xe(d.id,y))},onClearSelection:()=>R("")}),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-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:se,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:ht,disabled:se||!j||!y||h==="__custom__"&&!Ge,children:[t.jsx(qn,{size:14}),se?Rt:yt]})]})]})}),le&&t.jsx(Xr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ie,directories:de,busy:ge,error:D,onClose:()=>Z(!1),onNavigate:Qe,onConfirm:q=>{g(q),Q(q),w("__custom__"),Z(!1)}}),O&&pe&&t.jsx(ia,{activeConv:pe,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:C,isSavedSessionsLoading:G,isResumingSavedSessionId:ae,savedHistoryFilters:je,onSavedHistoryFiltersChange:$e,onClose:()=>X(!1),onNewChat:()=>{R(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!y||Xe(d.id,y)},onResumeSavedSession:q=>{if(!d||!y||ae||!q.canResume)return;const Be=xt(q);R(q.providerSessionId),dt(q),ee(q.providerSessionId),X(!1),ue(!0),z(""),l(d.id,"cli",y,{workspaceId:Be.workspaceId,workspacePath:Be.workspacePath,resumeSessionId:q.providerSessionId}).then(Re=>{if(!Re.ok){z(Re.error||"Could not resume session");return}n()}).finally(()=>{ue(!1),ee(Re=>Re===q.providerSessionId?null:Re)})}}),me&&d&&t.jsx(Yp,{machineCards:[{id:d.id,label:Ct(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Fi(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:q=>{_e(!1),n(),m(q)},onClose:()=>_e(!1)})]}):null}function Qp(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 Jp(e){return e instanceof Error?e.message:String(e||"")}function Zp(e){const s=Jp(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ef({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:v,ides:N,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:S,isStandalone:h,initialDataLoaded:w,userName:_,requestedMobileTabKey:g,onRequestedMobileTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:y,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,containerRef:I,isSplitMode:M,numGroups:T,groupSizes:W,groupedConvs:R,clearedTabs:C,focusedGroup:H,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:$,closeGroup:B,handleResizeStart:O,groupActiveTabIds:X,setGroupActiveTabIds:je,groupTabOrders:$e,setGroupTabOrders:me,toggleHiddenTab:_e,visibleConversations:ae,requestedDesktopTabKey:ee,onRequestedDesktopTabConsumed:se,onDesktopActiveTabChange:ue,onHideConversation:re,onShowHiddenConversation:z,onShowAllHiddenConversations:le,scrollToBottomRequest:Z,machineEntries:ie,onBrowseMachineDirectory:Q,onSaveMachineWorkspace:de,onLaunchMachineIde:oe,onLaunchMachineProvider:ge,onListMachineSavedSessions:fe,notifications:D,notificationUnreadCount:ye,notificationStateBySessionId:be,onMarkNotificationRead:Ne,onMarkNotificationUnread:J,onDeleteNotification:Se,onMarkNotificationTargetRead:Ue}){const De=rt.useRef(null),[Ve,Ye]=rt.useState(!1),[Xe,pt]=rt.useState(!1),[Ge,bt]=rt.useState(!1),[lt,dt]=rt.useState(!1),xt=rt.useCallback(te=>{var Ae;qs.flushSync(()=>{z(te)}),(Ae=De.current)==null||Ae.restoreHiddenTabToSavedLocation(te.tabKey)},[z]),at=rt.useCallback(te=>{var Ke;const Ae=f.find(P=>te.sessionId&&P.sessionId===te.sessionId?!0:!!te.tabKey&&P.tabKey===te.tabKey)||v.find(P=>te.sessionId&&P.sessionId===te.sessionId?!0:!!te.tabKey&&P.tabKey===te.tabKey);Ae&&(v.some(P=>P.tabKey===Ae.tabKey)&&xt(Ae),ue(Ae.tabKey),(Ke=De.current)==null||Ke.activateConversationTab(Ae.tabKey)),Ne(te.id),(te.sessionId||te.tabKey)&&Ue({sessionId:te.sessionId,tabKey:te.tabKey}),Ye(!1)},[xt,v,f,ue,Ne,Ue]),[pe,Fe]=rt.useState(!1),[Qe,et]=rt.useState("quickstart"),[ht,yt]=rt.useState("workspace"),Rt=!e&&!s,Nt=rt.useCallback(te=>{Ye(te),te&&pt(!1)},[]),At=rt.useCallback(te=>{pt(te),te&&Ye(!1)},[]),q=rt.useCallback(()=>{var Ae;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ae=De.current)==null||Ae.resetAllPanelsToMain(),pt(!1))},[]),Be=rt.useCallback(()=>{et(ae.length===0?"quickstart":"shortcuts"),yt("workspace"),bt(!0),Ye(!1),pt(!1)},[ae.length]),Re=rt.useCallback(async te=>{var ce;if(!r)return;const Ae=(ce=r.modalButtons)==null?void 0:ce[te];if(!Ae)return;const Ke=Js(r);if(!Ke)return;const P=Ae.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(P);try{await d(Ke,"resolve_action",{button:Ae,action:Y?"approve":"reject",buttonIndex:te,...js(r)})}catch(Pe){Zp(Pe)||console.error("[Shortcut approval] Failed:",Pe)}},[r,d]),{isMac:K,actionDefinitions:U,actionShortcuts:F,shortcutListening:V,shortcutListeningDraft:ne,setShortcutListening:we,setShortcutListeningDraft:Ie,saveShortcuts:Ce}=Lp({enabled:Rt&&!Ge,onTrigger:te=>{var Ae,Ke,P,Y,ce,Pe,Te,Ee,ve,tt,ot,zt,Yt,tr,Xt,sr;if(te==="openShortcutHelp"){Be();return}if(te==="hideCurrentTab"){r&&re(r);return}if(te==="toggleHiddenTabs"){At(!Xe);return}if(te==="openHistoryForActiveTab"){r&&!qe(r)&&c(r);return}if(te==="openRemoteForActiveTab"){r&&!Ze(r)&&!qe(r)&&l(r);return}if(te==="splitActiveTabRight"){(Ae=De.current)==null||Ae.splitActiveTabRight();return}if(te==="splitActiveTabDown"){(Ke=De.current)==null||Ke.splitActiveTabDown();return}if(te==="floatActiveTab"){(P=De.current)==null||P.floatActiveTab();return}if(te==="popoutActiveTab"){(Y=De.current)==null||Y.popoutActiveTab();return}if(te==="dockActiveTab"){(ce=De.current)==null||ce.dockActiveTab();return}if(te==="focusLeftPane"){(Pe=De.current)==null||Pe.focusLeftPane();return}if(te==="focusRightPane"){(Te=De.current)==null||Te.focusRightPane();return}if(te==="focusUpPane"){(Ee=De.current)==null||Ee.focusUpPane();return}if(te==="focusDownPane"){(ve=De.current)==null||ve.focusDownPane();return}if(te==="moveActiveTabToLeftPane"){(tt=De.current)==null||tt.moveActiveTabToLeftPane();return}if(te==="moveActiveTabToRightPane"){(ot=De.current)==null||ot.moveActiveTabToRightPane();return}if(te==="moveActiveTabToUpPane"){(zt=De.current)==null||zt.moveActiveTabToUpPane();return}if(te==="moveActiveTabToDownPane"){(Yt=De.current)==null||Yt.moveActiveTabToDownPane();return}if(te==="triggerPrimaryApprovalAction"){Re(0);return}if(te==="triggerSecondaryApprovalAction"){Re(1);return}if(te==="triggerTertiaryApprovalAction"){Re(2);return}if(te==="setActiveTabShortcut"){(tr=De.current)==null||tr.setShortcutForActiveTab();return}if(te==="selectPreviousGroupTab"){(Xt=De.current)==null||Xt.activatePreviousTabInGroup();return}if(te==="selectNextGroupTab"){(sr=De.current)==null||sr.activateNextTabInGroup();return}!r||!Ze(r)||qe(r)||te==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),We=rt.useCallback(()=>{bt(!1),we(null),Ie([])},[we,Ie]),Oe=rt.useMemo(()=>ht==="all"?U:U.filter(te=>Qp(te)===ht),[U,ht]),Je=rt.useCallback(()=>{const te=Object.fromEntries(U.map(Ae=>[Ae.id,""]));Ce(te)},[U,Ce]),Le=rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const te=Object.fromEntries(U.map(Ae=>[Ae.id,Ae.defaultShortcut]));Ce(te)},[U,Ce]);return rt.useEffect(()=>{const te=Ae=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ae.metaKey&&Ae.key.toLowerCase()==="w":Ae.ctrlKey&&Ae.key.toLowerCase()==="w")&&(Ae.preventDefault(),r&&re&&re(r))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[r,re]),rt.useEffect(()=>{if(!Ge||V)return;const te=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),We())};return window.addEventListener("keydown",te,!0),()=>window.removeEventListener("keydown",te,!0)},[We,Ge,V]),rt.useEffect(()=>{if(!Rt){Fe(!1);return}Fe(!0);const te=window.setTimeout(()=>{Fe(!1)},1e4);return()=>window.clearTimeout(te)},[Rt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(tu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:ae,hiddenConversations:v,onOpenHistory:c,onHideConversation:re,onShowConversation:xt,onShowAllHidden:le,onResetPanelsToMain:q,notifications:D,notificationUnreadCount:ye,onOpenNotification:at,onMarkNotificationRead:Ne,onMarkNotificationUnread:J,onDeleteNotification:Se,inboxOpen:Ve,onInboxOpenChange:Nt,hiddenOpen:Xe,onHiddenOpenChange:At,onOpenNewSession:s?void 0:()=>dt(!0),actionShortcuts:F,onOpenRemote:()=>{!r||Ze(r)||qe(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(yp,{conversations:f,hiddenConversations:v,ides:N,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:S,isStandalone:h,userName:_,requestedActiveTabKey:g,onRequestedActiveTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:y,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:xt,onShowAllHiddenConversations:le,onOpenNewSession:()=>dt(!0),notificationStateBySessionId:be,onMarkNotificationTargetRead:Ue}):s?t.jsx(Ip,{containerRef:I,isSplitMode:M,numGroups:T,groupSizes:W,groupedConvs:R,clearedTabs:C,ides:N,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:S,isStandalone:h,hasRegisteredMachines:ie.length>0,userName:_,focusedGroup:H,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:$,closeGroup:B,handleResizeStart:O,groupActiveTabIds:X,setGroupActiveTabIds:je,groupTabOrders:$e,setGroupTabOrders:me,toggleHiddenTab:_e,allowTabShortcuts:!1}):t.jsx(Wp,{visibleConversations:ae,clearedTabs:C,ides:N,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:S,isStandalone:h,hasRegisteredMachines:ie.length>0,initialDataLoaded:w,userName:_,toggleHiddenTab:_e,actionShortcuts:F,registerActionHandlers:te=>{De.current=te},notificationStateBySessionId:be,onActiveTabChange:ue,requestedActiveTabKey:ee,onRequestedActiveTabConsumed:se,scrollToBottomRequest:Z}),lt&&t.jsx(Xp,{machines:ie,conversations:f,ides:N,onClose:()=>dt(!1),onBrowseDirectory:Q,onSaveWorkspace:de,onLaunchIde:oe,onLaunchProvider:ge,onListSavedSessions:fe,sendDaemonCommand:d,onOpenConversation:te=>{dt(!1),z(te),ue(te.tabKey)}}),Ge&&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:We,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:te=>te.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:We,"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(te=>t.jsx("button",{type:"button",className:`btn btn-sm ${Qe===te.id?"btn-primary":"btn-secondary"}`,onClick:()=>et(te.id),children:te.label},te.id))}),Qe==="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 ",K?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Qe==="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."]})]})]})]}),Qe==="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(te=>t.jsx("button",{type:"button",className:`btn btn-sm ${ht===te.id?"btn-primary":"btn-secondary"}`,onClick:()=>yt(te.id),children:te.label},te.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,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:Le,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Oe.map(te=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${V===te.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:te.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:te.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:te.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:V===te.id?ne.length>0?`${ne.join(" ")} ...`:"Listening...":F[te.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{we(te.id),Ie([])},children:V===te.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ae={...F};Ae[te.id]="",Ce(Ae)},children:"Disable"})]})]})},te.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",K?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Be,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 ${pe?"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:"?"}),pe&&t.jsx("span",{children:"Guide"})]})]})}const vn=[{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 tf({onClose:e}){const[s,r]=o.useState(0),n=vn[s],a=s===vn.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:vn.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]}),a&&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:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"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 sf({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){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:()=>a("native"),children:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=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:()=>a(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"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 rf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>bi(s),[s]),p=o.useMemo(()=>e?ca(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(b=>b.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(b=>b.streamSource==="agent-stream"),[p]),v=o.useMemo(()=>e?Bt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!v)return;const b=v.streamSource==="native"?"native":v.tabKey;!b||c===b||c==="native"&&l(b)},[c,v,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(S=>S.tabKey===c)||l(((b=f[0])==null?void 0:b.tabKey)||"native"))},[c,f]),o.useEffect(()=>{c==="native"&&(m||f[0]&&l(f[0].tabKey))},[c,m,f]);const N=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||v||m||f[0],[c,m,v,f]),L=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:ui(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(S=>S.sessionId===b||S.routeId===b||S.tabKey===b)},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:N,conversations:p,extensionTabs:L,hasExtensions:L.length>0,resolveConversationByTarget:d}}function nf({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:p,userName:m,onOpenHistory:f,onConversationChange:v,onClose:N}){const[L,d]=o.useState("split"),[b,S]=o.useState(()=>Vt(e)?"native":e.tabKey),h=o.useRef(null),w=o.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>nt((w==null?void 0:w.type)||""),[w==null?void 0:w.type]),{conversations:g,extensionTabs:j,hasExtensions:k}=rf({ideData:w,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),y=o.useMemo(()=>w?Bt(g,w.id):null,[w,g]);o.useEffect(()=>{const A=h.current,$={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=$,!(A&&A.routeId===$.routeId&&A.tabKey===$.tabKey&&A.streamSource===$.streamSource)){if(Vt(e)){S("native");return}S(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(g.some(A=>A.streamSource==="native"))return;(y==null?void 0:y.streamSource)==="agent-stream"&&S(y.tabKey);return}if(!g.some(A=>A.tabKey===b)){if((y==null?void 0:y.streamSource)==="agent-stream"){S(y.tabKey);return}S("native")}},[g,b,y]);const x=o.useMemo(()=>b==="native"?g.find(A=>A.streamSource==="native")||e:g.find(A=>A.tabKey===b)||e,[e,g,b]),E=_i(x),I=o.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...x,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:x,[x,E]),M=Lr(I),T=Vr({sendDaemonCommand:c,activeConv:I,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:W,screenshotUsage:R,handleRemoteAction:C}=Yi({doId:M,targetSessionId:ea(I),connState:I.connectionState||"new",viewMode:L}),H=o.useMemo(()=>a.filter(A=>A.routeId===I.tabKey),[a,I.tabKey]);o.useEffect(()=>{v==null||v(I)},[I,v]),o.useEffect(()=>{const A=$=>{$.key==="Escape"&&N()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[N]);const G=o.useCallback(A=>{A.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:N,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:G,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:Zn(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:N,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(A=>{const $=L===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${$?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>d(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?t.jsx(sl,{size:15}):t.jsx(It,{size:15})},A)})}),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:()=>f(x),title:"Chat History",children:[t.jsx(Gn,{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:N,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(sf,{hasExtensions:k,ideName:_||"IDE",activeChatTab:b,extensionTabs:j,onSelectTab:S}),t.jsx(Go,{activeConv:I,onModalButton:T.handleModalButton}),t.jsx(Rn,{activeConv:I,ideEntry:w,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:H,userName:m})]}),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(Fo,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:W,screenshotUsage:R,transportType:I.transport,onAction:C})})]})]})})}function af({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Qd(e);return t.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm: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-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm: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:a,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 of({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:p,onSwitchHistorySession:m,onRefreshHistory:f,onResumeSavedHistorySession:v,remoteDialogConv:N,remoteDialogIdeEntry:L,connectionStates:d,actionLogs:b,localUserMessages:S,sendDaemonCommand:h,setLocalUserMessages:w,setActionLogs:_,isStandalone:g,userName:j,onOpenRemoteHistory:k,onRemoteConversationChange:y,onCloseRemoteDialog:x,cliStopDialogOpen:E,cliStopTargetConv:I,onCancelCliStop:M,onStopCliNow:T,onSaveCliAndStop:W,toasts:R,onDismissToast:C,onClickToast:H,showOnboarding:G,onCloseOnboarding:A}){var O;const[$,B]=rt.useState(()=>gt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(ia,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:$,onSavedHistoryFiltersChange:B,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:v}),N&&t.jsx(nf,{activeConv:N,ideEntry:L,ides:r,connectionStates:d,actionLogs:b,localUserMessages:S,sendDaemonCommand:h,setLocalUserMessages:w,setActionLogs:_,isStandalone:g,userName:j,onOpenHistory:k,onConversationChange:y,onClose:x}),E&&I&&(Ze(I)||qe(I))&&t.jsx(af,{activeConv:I,canSaveAndStop:Ze(I)&&!qe(I)&&!!((O=I.resume)!=null&&O.supported),onCancel:M,onStopNow:T,onSaveAndStop:W}),t.jsx(hi,{toasts:R,onDismiss:C,onClickToast:H}),G&&t.jsx(tf,{onClose:A})]})}function cf({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,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(_s,{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}),u=n[c.id],p=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),m&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:m?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:m?"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 lf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function wo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function df(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function uf(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 mf(){var ja,ka,Na,Sa,Ca;const{sendCommand:e}=_t(),s=er(),r=zn(),n=Ls(),[a,i]=Dc(),c=a.get("activeTab"),l=((ja=r.state)==null?void 0:ja.openRemoteForTabKey)||null,u=((ka=r.state)==null?void 0:ka.openMachineId)||null,p=((Na=r.state)==null?void 0:Na.mobileSection)||null,m=ii(),f=m.ides||[],v=m.initialLoaded??!0,{updateRouteChats:N,setToasts:L}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),S=m.toasts||[],h=m.wsStatus||"connected",w=m.isConnected??!0,_=m.connectionStates||{},g=m.showReconnected||!1,{groupAssignments:j,setGroupAssignments:k,focusedGroup:y,setFocusedGroup:x,groupActiveTabIds:E,setGroupActiveTabIds:I,groupTabOrders:M,setGroupTabOrders:T,groupSizes:W,setGroupSizes:R,isMobile:C,hasHydratedStoredLayout:H,hydrateStoredLayout:G}=Tm(),[A,$]=o.useState(!1),[B,O]=o.useState(!1),[X,je]=o.useState(null),[$e,me]=o.useState([]),[_e,ae]=o.useState(!1),[ee,se]=o.useState(null),[ue]=o.useState(()=>Mi()),[re,z]=o.useState([]),[le,Z]=o.useState({}),[ie,Q]=o.useState({}),[de,oe]=o.useState({}),[ge,fe]=o.useState(null),[D,ye]=o.useState(null),[be,Ne]=o.useState(null),J=o.useRef(null);Zs("Dashboard",{ideCount:f.length,toastCount:S.length,focusedGroup:y,groupCount:Object.keys(j).length,localMessageTabs:Object.keys(le).length,actionLogCount:re.length});const Se=f.find(he=>he.type==="adhdev-daemon"),Ue=o.useMemo(()=>f.filter(he=>he.type==="adhdev-daemon").sort(Qn),[f]),De=!!Se;o.useEffect(()=>{!Se||!(!Se.detectedIdes||!Se.availableProviders||!Se.recentLaunches||!Se.workspaces)||s(Se.id,{minFreshMs:3e4}).catch(()=>{})},[Se,s]);const Ve=(Se==null?void 0:Se.terminalBackend)||null,Ye=Se?Ct(Se,{fallbackId:Se.id}):null,Xe=(Se==null?void 0:Se.id)||null,pt=o.useMemo(()=>rm(f,ie),[f,ie]),{hiddenTabs:Ge,hideTab:bt,toggleTab:lt,showTab:dt,showAllTabs:xt}=sm(),{chatIdes:at,conversations:pe,visibleConversations:Fe,visibleTabKeys:Qe,resolveConversationBySessionId:et,resolveConversationByTarget:ht}=hm({ides:pt,connectionStates:_,localUserMessages:le,clearedTabs:de,hiddenTabs:Ge});o.useEffect(()=>{Object.keys(ie).length!==0&&Q(he=>nm(he,f))},[f,ie]);const yt=o.useMemo(()=>zr(f),[f]),{notifications:Rt,unreadCount:Nt,notificationStateBySessionId:At,markRead:q,markUnread:Be,markTargetRead:Re,deleteNotification:K}=Qm({conversations:pe,liveSessionInboxState:yt}),U=o.useRef(null),{containerRef:F,normalizedGroupAssignments:V,numGroups:ne,isSplitMode:we,groupedConvs:Ie,moveTabToGroup:Ce,closeGroup:We,handleResizeStart:Oe,splitTabRelative:Je}=$m({groupAssignments:j,setGroupAssignments:k,setFocusedGroup:x,setGroupActiveTabIds:I,setGroupTabOrders:T,groupSizes:W,setGroupSizes:R,isMobile:C,visibleConversations:Fe,visibleTabKeys:Qe}),Le=o.useMemo(()=>{var Me,ke;if(!C){if(ge){const xe=pe.find(ze=>ze.tabKey===ge);if(xe)return xe}return Fe[0]}const he=E[y];if(he){const xe=pe.find(ze=>ze.tabKey===he);if(xe)return xe}return((Me=Ie[y])==null?void 0:Me[0])||((ke=Ie[0])==null?void 0:ke[0])},[ge,C,E,y,pe,Ie,Fe]);o.useEffect(()=>{if(C){U.current=null;return}if(!(Le!=null&&Le.sessionId)){U.current=null;return}const he=`${Le.tabKey}:${Le.sessionId}`;if(U.current===he)return;const Me=()=>{if(document.visibilityState!=="visible"||U.current===he)return;U.current=he;const ke=Mr(Le,yt),xe=Math.max(Date.now(),os(Le),ke.lastUpdated||0);Re({sessionId:Le.sessionId,tabKey:Le.tabKey},xe),e(Le.daemonId||Le.routeId,"mark_session_seen",{sessionId:Le.sessionId,seenAt:xe}).catch(()=>{})};if(document.visibilityState==="visible"){const ke=setTimeout(Me,1500),xe=()=>{document.visibilityState!=="visible"&&clearTimeout(ke)};return document.addEventListener("visibilitychange",xe),()=>{clearTimeout(ke),document.removeEventListener("visibilitychange",xe)}}else{const ke=()=>{document.visibilityState==="visible"&&(setTimeout(Me,800),document.removeEventListener("visibilitychange",ke))};return document.addEventListener("visibilitychange",ke),()=>{document.removeEventListener("visibilitychange",ke)}}},[Le,C,yt,Re,e]);const{requestedDesktopTabKey:te,requestedMobileTabKey:Ae,consumeRequestedActiveTab:Ke}=bm({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:et,setSearchParams:i}),{remoteDialogConv:P,remoteDialogIdeEntry:Y,remoteDialogActiveConv:ce,setRemoteDialogActiveConv:Pe,openRemoteDialog:Te,closeRemoteDialog:Ee}=_m({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:te,conversations:pe,ides:f,resolveConversationByTarget:ht}),ve=ce||P||Le,tt=!!ve&&Ze(ve)&&!qe(ve),ot=o.useMemo(()=>{if(!ve||!tt)return null;const he=ve.daemonId||ve.routeId||"",Me=Lt(ve);return`${he}:${Me}`},[ve,tt]),zt=o.useMemo(()=>Fe,[Fe]),Yt=C&&ue==="chat",tr=o.useMemo(()=>pe.filter(he=>Ge.has(he.tabKey)),[pe,Ge]),Xt=o.useCallback(he=>{const Me=new URLSearchParams(a);Me.set("activeTab",he),i(Me,{replace:!0})},[a,i]),sr=o.useCallback(async(he,Me)=>Yr(e,he,Me),[e]),cc=o.useCallback(async(he,Me)=>{if(!Me.trim())return{ok:!1,error:"Choose a workspace path first."};try{const ke=await e(he,"workspace_add",{path:Me.trim()});return ke!=null&&ke.success?{ok:!0}:{ok:!1,error:(ke==null?void 0:ke.error)||"Could not save workspace"}}catch(ke){return{ok:!1,error:ke instanceof Error?ke.message:"Could not save workspace"}}},[e]),lc=o.useCallback(async(he,Me,ke)=>{var xe;try{const ze={ideType:Me,enableCdp:!0};(xe=ke==null?void 0:ke.workspacePath)!=null&&xe.trim()&&(ze.workspace=ke.workspacePath.trim());const ut=await e(he,"launch_ide",ze);return!(ut!=null&&ut.success)&&(ut==null?void 0:ut.success)!==void 0?{ok:!1,error:(ut==null?void 0:ut.error)||"Could not launch IDE"}:(Ne({machineId:he,kind:"ide",providerType:Me,workspacePath:(ke==null?void 0:ke.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(ze){return{ok:!1,error:ze instanceof Error?ze.message:"Could not launch IDE"}}},[e]),dc=o.useCallback(async(he,Me,ke,xe)=>{var ut,Ps,xs;const ze=Date.now();try{const Pt={cliType:ke};(ut=xe==null?void 0:xe.workspacePath)!=null&&ut.trim()?Pt.dir=xe.workspacePath.trim():xe!=null&&xe.workspaceId&&(Pt.workspaceId=xe.workspaceId),(Ps=xe==null?void 0:xe.resumeSessionId)!=null&&Ps.trim()&&(Pt.resumeSessionId=xe.resumeSessionId.trim()),Array.isArray(xe==null?void 0:xe.cliArgs)&&xe.cliArgs.length>0&&(Pt.cliArgs=xe.cliArgs),(xs=xe==null?void 0:xe.initialModel)!=null&&xs.trim()&&(Pt.initialModel=xe.initialModel.trim());const vt=await e(he,"launch_cli",Pt),St=(vt==null?void 0:vt.result)||vt,Ds=(St==null?void 0:St.sessionId)||(St==null?void 0:St.id);return vt!=null&&vt.success&&Ds?(Xt(Ds),{ok:!0}):vt!=null&&vt.success?(Ne({machineId:he,kind:Me,providerType:ke,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:ze}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||(St==null?void 0:St.error)||`Could not launch ${Me.toUpperCase()} session`}}catch(Pt){return df(Pt)?(Ne({machineId:he,kind:Me,providerType:ke,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:ze}),{ok:!0}):{ok:!1,error:Pt instanceof Error?Pt.message:`Could not launch ${Me.toUpperCase()} session`}}},[Xt,e]),uc=o.useCallback(async(he,Me)=>{if(!he||!Me)return[];try{const ke=await e(he,"list_saved_sessions",{providerType:Me,kind:"cli",limit:30}),xe=(ke==null?void 0:ke.result)??ke;return Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[]}catch(ke){return console.error("List saved sessions failed",ke),[]}},[e]);o.useEffect(()=>{var xe;if(!be)return;const he=wo(be.workspacePath),Me=f.find(ze=>{var vt,St,Ds,Ia;if(!ze||ze.type==="adhdev-daemon"||lf(ze.daemonId||ze.id)!==be.machineId||(Xs(ze)?"cli":ws(ze)?"acp":"ide")!==be.kind||String(ze.agentType||ze.type||"")!==be.providerType)return!1;if(be.resumeSessionId)return String(ze.providerSessionId||"")===be.resumeSessionId;if(he){const Zr=wo(ze.workspace||ze.runtimeWorkspaceLabel);return Zr?Zr===he:!1}return Number(ze.lastUpdated||ze._lastUpdate||ze.timestamp||((Ia=(Ds=(St=(vt=ze.activeChat)==null?void 0:vt.messages)==null?void 0:St.at)==null?void 0:Ds.call(St,-1))==null?void 0:Ia.timestamp)||0)>=be.startedAt-5e3});if(!Me)return;const ke=typeof Me.sessionId=="string"&&Me.sessionId?Me.sessionId:typeof Me.instanceId=="string"&&Me.instanceId?Me.instanceId:(xe=pe.find(ze=>ze.routeId===Me.id))==null?void 0:xe.sessionId;ke&&(Ne(null),Xt(ke))},[pe,Xt,f,be]),o.useEffect(()=>{if(!be)return;const he=window.setTimeout(()=>{Ne(Me=>!Me||Me.startedAt!==be.startedAt?Me:null)},45e3);return()=>window.clearTimeout(he)},[be]),am({visibleConversations:Fe,clearedTabs:de,setClearedTabs:oe,setActionLogs:z}),gm({ides:f,sendDaemonCommand:e,setToasts:L,setLocalUserMessages:Z,resolveConversationByTarget:ht});const{isRefreshingHistory:mc,handleRefreshHistory:pc}=ro({sendDaemonCommand:e,activeConv:Le,chats:(Sa=f.find(he=>he.id===(Le==null?void 0:Le.routeId)))==null?void 0:Sa.chats,updateRouteChats:N,setToasts:L,setLocalUserMessages:Z,setClearedTabs:oe}),{isCreatingChat:fc,isRefreshingHistory:xc,handleSwitchSession:hc,handleNewChat:bc,handleRefreshHistory:gc}=ro({sendDaemonCommand:e,activeConv:ve,chats:(Ca=f.find(he=>he.id===(ve==null?void 0:ve.routeId)))==null?void 0:Ca.chats,updateRouteChats:N,setToasts:L,setLocalUserMessages:Z,setClearedTabs:oe}),Jr=o.useCallback(async()=>{if(!(!ve||!tt||_e)){ae(!0);try{const he=ve.daemonId||ve.routeId,Me=Lt(ve),ke=await e(he,"list_saved_sessions",{agentType:Me,providerType:Me,kind:"cli",limit:50}),xe=(ke==null?void 0:ke.result)??ke;me(Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[])}catch(he){console.error("Refresh saved sessions failed",he),me([])}finally{ae(!1)}}},[ve,_e,tt,e]);o.useEffect(()=>{if(!A){J.current=null;return}if(!tt){J.current=null,me([]),ae(!1);return}!ot||_e||J.current!==ot&&(J.current=ot,Jr())},[Jr,A,_e,tt,ot]);const yc=o.useCallback(async he=>{if(!ve||!tt||!he.providerSessionId||!he.workspace)return;const Me=ve.daemonId||ve.routeId,ke=Lt(ve);try{se(he.providerSessionId);const xe=await e(Me,"launch_cli",{cliType:ke,dir:he.workspace,resumeSessionId:he.providerSessionId,initialModel:Qo(he.summaryMetadata,"model",{preferShortValue:!0})||void 0}),ze=(xe==null?void 0:xe.result)??xe,ut=typeof(ze==null?void 0:ze.sessionId)=="string"?ze.sessionId:typeof(ze==null?void 0:ze.id)=="string"?ze.id:"";ut&&i(Ps=>{const xs=new URLSearchParams(Ps);return xs.set("activeTab",ut),xs},{replace:!0}),$(!1)}catch(xe){console.error("Resume saved session failed",xe)}finally{se(null)}},[ve,tt,e,i]);Lm({urlActiveTab:C&&!Yt?c:null,conversations:pe,resolveConversationBySessionId:et,normalizedGroupAssignments:V,hasHydratedStoredLayout:C&&!Yt?H:!0,hydrateStoredLayout:C&&!Yt?G:()=>{},setGroupActiveTabIds:I,setFocusedGroup:x,setSearchParams:i,historyModalOpen:A,activeConv:Le,isRefreshingHistory:mc,ides:f,handleRefreshHistory:pc});const ga=o.useCallback(async(he,Me)=>{const ke=Me||X||Le;if(!ke||!Ze(ke)&&!qe(ke))return;const xe=Lt(ke),ze=ke.routeId||ke.daemonId||"";try{await e(ze,"stop_cli",{cliType:xe,targetSessionId:ke.sessionId,mode:he})}catch(ut){console.error("Stop CLI failed:",ut)}},[Le,X,e]),vc=o.useCallback(async he=>{const Me=he||Le;!Me||!Ze(Me)&&!qe(Me)||(je(Me),O(!0))},[Le]),wc=o.useMemo(()=>!Le||!Ze(Le)||qe(Le)?null:Is(Le),[Le]),jc=o.useCallback(async he=>{if(!Le||!Ze(Le)||qe(Le))return;const Me=Is(Le);if(Me===he)return;const ke=Le.sessionId;ke&&Q(xe=>({...xe,[ke]:he}));try{await e(qt(Le)||Le.routeId,"set_cli_view_mode",{targetSessionId:Le.sessionId,cliType:Lt(Le),mode:he})}catch(xe){ke&&Q(ze=>{const ut={...ze};return Me===Pi(f,ke)?delete ut[ke]:ut[ke]=Me,ut}),uf(xe)?console.warn("Skipped CLI view mode switch:",xe instanceof Error?xe.message:String(xe)):console.error("Failed to switch CLI view mode:",xe)}},[Le,f,e]),{versionMismatchDaemons:kc,hasRequiredVersionDaemons:ya,appVersion:Nc,versionBannerDismissed:Sc,setVersionBannerDismissed:Cc,upgradingDaemons:Ic,handleBannerUpgrade:Ac}=Bm({ides:f,sendDaemonCommand:e}),va=o.useCallback(he=>{fe(he.tabKey),i(Me=>{const ke=new URLSearchParams(Me),xe=kd(he);return xe?ke.set("activeTab",xe):ke.delete("activeTab"),ke},{replace:!0})},[i]),wa=o.useCallback(he=>{dt(he.tabKey),va(he)},[va,dt]),Tc=o.useCallback(he=>{bt(he.tabKey)},[bt]);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(Zd,{wsStatus:h,showReconnected:g}),t.jsx(eu,{terminalBackend:Ve,isStandalone:De,machineLabel:Ye,machineKey:Xe}),(!Sc||ya)&&t.jsx(cf,{daemons:kc,targetVersion:Nc,required:ya,upgradingDaemons:Ic,onUpgrade:Ac,onDismiss:()=>Cc(!0)}),t.jsx(ef,{showMobileChatMode:Yt,isMobile:C,activeConv:Le,chatIdes:at,wsStatus:h,isConnected:w,onOpenHistory:he=>{he&&Pe(he),$(!0)},onOpenRemote:Te,onStopCli:vc,activeCliViewMode:wc,onSetActiveCliViewMode:jc,mobileChatConversations:zt,ides:f,actionLogs:re,sendDaemonCommand:e,setLocalUserMessages:Z,setActionLogs:z,isStandalone:De,initialDataLoaded:v,userName:m.userName,requestedMobileTabKey:Ae,onRequestedMobileTabConsumed:Ke,requestedMachineId:u,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:F,isSplitMode:we,numGroups:ne,groupSizes:W,groupedConvs:Ie,clearedTabs:de,focusedGroup:y,setFocusedGroup:x,moveTabToGroup:Ce,splitTabRelative:Je,closeGroup:We,handleResizeStart:Oe,groupActiveTabIds:E,setGroupActiveTabIds:I,groupTabOrders:M,setGroupTabOrders:T,toggleHiddenTab:lt,visibleConversations:Fe,hiddenConversations:tr,requestedDesktopTabKey:te,onRequestedDesktopTabConsumed:Ke,onDesktopActiveTabChange:fe,onHideConversation:Tc,onShowHiddenConversation:wa,onShowAllHiddenConversations:xt,scrollToBottomRequest:D,machineEntries:Ue,onBrowseMachineDirectory:sr,onSaveMachineWorkspace:cc,onLaunchMachineIde:lc,onLaunchMachineProvider:dc,onListMachineSavedSessions:uc,notifications:Rt,notificationUnreadCount:Nt,notificationStateBySessionId:At,onMarkNotificationRead:q,onMarkNotificationUnread:Be,onDeleteNotification:K,onMarkNotificationTargetRead:Re}),t.jsx("style",{children:`
|
|
60
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(of,{historyModalOpen:A,historyTargetConv:ve,ides:f,isHistoryCreatingChat:fc,isHistoryRefreshingHistory:tt?!1:xc,savedHistorySessions:$e,isSavedHistoryLoading:_e,isResumingSavedHistorySessionId:ee,onCloseHistory:()=>$(!1),onNewHistoryChat:bc,onSwitchHistorySession:hc,onRefreshHistory:tt?Jr:gc,onResumeSavedHistorySession:yc,remoteDialogConv:P,remoteDialogIdeEntry:Y,connectionStates:_,actionLogs:re,localUserMessages:le,sendDaemonCommand:e,setLocalUserMessages:Z,setActionLogs:z,isStandalone:De,userName:m.userName,onOpenRemoteHistory:he=>{he&&Pe(he),$(!0)},onRemoteConversationChange:Pe,onCloseRemoteDialog:Ee,cliStopDialogOpen:B,cliStopTargetConv:X,onCancelCliStop:()=>{O(!1),je(null)},onStopCliNow:async()=>{O(!1),await ga("hard",X),je(null)},onSaveCliAndStop:async()=>{O(!1),await ga("save",X),je(null)},toasts:S,onDismissToast:he=>L(Me=>Me.filter(ke=>ke.id!==he)),onClickToast:he=>{if(he.targetKey){const Me=ht(he.targetKey);Me&&(x(V.get(Me.tabKey)??0),wa(Me),ye({tabKey:Me.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function pf({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,v]=o.useState(!1),[N,L]=o.useState(null),[d,b]=o.useState(!1),[S,h]=o.useState(""),w=o.useRef(null),_=o.useCallback(A=>{w.current=A},[]),g=o.useCallback((A,$,B=!1)=>{c(O=>[...O.slice(-100),{timestamp:Date.now(),level:A,message:$}]),setTimeout(()=>{var O;return(O=a.current)==null?void 0:O.scrollIntoView({behavior:"smooth"})},100),B&&it.showToast($,A==="error"||A==="warn"?"warning":"success")},[a]),j=o.useCallback(A=>{const $=A instanceof Error?A.message:String(A||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),k=o.useCallback(async(A,$)=>{var B;if(!e||l)return!1;u(A),g("info",`Launching ${nt(A)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const O={ideType:A,enableCdp:!0};(B=$==null?void 0:$.workspace)!=null&&B.trim()?O.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(O.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",O);return g(X!=null&&X.success?"info":"error",X!=null&&X.success?`${nt(A)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(O){return g("error",`Launch error: ${O.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),y=o.useCallback(async A=>{if(!e)return{success:!1};const{cliType:$,dir:B,workspaceId:O,useDefaultWorkspace:X,useHome:je,argsStr:$e,model:me,resumeSessionId:_e}=A;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const ae=$e?$e.split(/\s+/).filter(Boolean):void 0,ee=(B==null?void 0:B.trim())||(O?"(saved id)":X?"(default workspace)":je?"(home)":"");g("info",`Launching ${$}${ee?` in ${ee}`:""}${me?` (model: ${me})`:""}...`),m($);try{const se={cliType:$,cliArgs:ae,initialModel:me||void 0};B!=null&&B.trim()?se.dir=B.trim():O?se.workspaceId=O:X?se.useDefaultWorkspace=!0:je&&(se.useHome=!0),_e&&(se.resumeSessionId=_e);const ue=await r(e,"launch_cli",se),re=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(g("info",`${$} launched`,!0),(re==null?void 0:re.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(re==null?void 0:re.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:re==null?void 0:re.sessionId}):(g("error",`Failed: ${(ue==null?void 0:ue.error)||(re==null?void 0:re.error)}`,!0),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&L({cliType:$,argsStr:$e,model:me}),{success:!1,sessionId:re==null?void 0:re.sessionId})}catch(se){return j(se)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${se.message}`,!0),{success:!1})}finally{m(null)}},[e,g,j,r]),x=o.useCallback(async(A,$,B,O)=>e?A?$.trim()?y({cliType:A,dir:$,argsStr:B,model:O}):(L({cliType:A,argsStr:B,model:O}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,y]),E=o.useCallback(async(A,$,B)=>{if(e&&window.confirm(`Stop ${A}?
|
|
62
|
-
This will terminate the process.`))try{const O=await r(e,"stop_cli",{cliType:A,dir:$,targetSessionId:B});O!=null&&O.success?g("info",`${A} stopped`,!0):g("error",`Stop failed: ${(O==null?void 0:O.error)||"Unknown error"}`,!0)}catch(O){g("error",`Stop failed: ${O.message}`,!0)}},[e,g,r]),I=o.useCallback(async A=>{try{await r(A.daemonId,"restart_ide",{ideType:A.type}),g("info",`${nt(A.type)} restart initiated`,!0)}catch($){g("error",`Restart failed: ${$.message}`,!0)}},[g,r]),M=o.useCallback(async A=>{if(window.confirm(`Stop ${nt(A.type)}?
|
|
63
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(A.daemonId,"stop_ide",{ideType:A.type,killProcess:!0});$!=null&&$.success?g("info",`${nt(A.type)} stopped`,!0):g("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){g("error",`Stop failed: ${$.message}`,!0)}},[g,r]),T=o.useCallback(async()=>{if(e)try{const A=await r(e,"detect_ides",{});g("info",`Found ${((A==null?void 0:A.result)||[]).length} IDE(s)`,!0)}catch(A){g("error",`Detection failed: ${A.message}`,!0)}},[e,g,r]),W=o.useCallback(async A=>{if(!e||!A.trim())return!1;v(!0);try{const $=await r(e,"workspace_add",{path:A.trim()});return $!=null&&$.success?(g("info",`Workspace added: ${A.trim()}`),!0):(g("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return g("error",$.message),!1}finally{v(!1)}},[e,g,r]),R=o.useCallback(async A=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){v(!0);try{const $=await r(e,"workspace_remove",{id:A});$!=null&&$.success?g("info","Workspace removed",!0):g("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){g("error",$.message,!0)}finally{v(!1)}}},[e,g,r]),C=o.useCallback(async A=>{var $;if(e){v(!0);try{const B=await r(e,"workspace_set_default",A===null?{clear:!0}:{id:A});if(B!=null&&B.success){g("info",A?"Default workspace updated":"Default workspace cleared",!0);const O=typeof B.defaultWorkspacePath=="string"?B.defaultWorkspacePath:"";O&&(($=w.current)==null||$.call(w,O))}else g("error",(B==null?void 0:B.error)||"workspace_set_default failed",!0)}catch(B){g("error",B.message,!0)}finally{v(!1)}}},[e,g,r]),H=o.useCallback(async A=>{var B;if(!e||!A.trim())return;const $=A.trim();v(!0);try{const O=await r(e,"workspace_set_default",{path:$});O!=null&&O.success?(g("info","Default workspace set from history"),(B=w.current)==null||B.call(w,$)):g("error",(O==null?void 0:O.error)||"Could not set default (path missing on disk?)")}catch(O){g("error",O.message)}finally{v(!1)}},[e,g,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:S}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:S})}catch(A){g("warn",`Live nickname updated, but account sync failed: ${A.message}`)}g("info",`Nickname set to "${S||"(cleared)"}"`),b(!1)}catch(A){g("error",`Failed: ${A.message}`)}},[e,S,s,g,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:N,setLaunchPick:L,editingNickname:d,setEditingNickname:b,nicknameInput:S,setNicknameInput:h,addLog:g,handleLaunchIde:k,runLaunchCliCore:y,handleLaunchCli:x,handleStopCli:E,handleRestartIde:I,handleStopIde:M,handleDetectIdes:T,handleWorkspaceAdd:W,handleWorkspaceRemove:R,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:H,handleSaveNickname:G,setOnDefaultWorkspaceChanged:_}}function ff({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var I;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,v]=o.useState(!1),[N,L]=o.useState(""),[d,b]=o.useState([]),[S,h]=o.useState(!1),[w,_]=o.useState(""),g=o.useCallback(async M=>{h(!0),_("");try{const T=await Yr(c,e,M);L(T.path),b(T.directories)}catch(T){_(T instanceof Error?T.message:"Could not load folder")}finally{h(!1)}},[e,c]),j=o.useCallback(()=>{v(!0);const M=[...r.map(W=>W.workspace),...n.map(W=>W.workspace),...a.map(W=>W.workspace)],T=qr(s.platform,Gr(M,s.defaultWorkspacePath,(s.workspaces||[]).map(W=>W.path)));g(T)},[a,n,r,g,s.defaultWorkspacePath,s.platform,s.workspaces]),k=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,y=s.availableMem??s.freeMem??s.totalMem,x=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/s.totalMem*100))):0,E=((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(or,{icon:t.jsx(Oo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Bl(s.uptime):"Waiting…"}),t.jsx(or,{icon:t.jsx(It,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(or,{icon:t.jsx(Or,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(or,{icon:t.jsx(al,{size:16}),label:"ACPs",value:`${a.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(Pa,{value:k?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Pa,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:k?`${rn(s.totalMem-y)} / ${rn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${rn(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(Ns,{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:M=>void m(M.target.value===""?null:M.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(M=>t.jsx("option",{value:M.id,children:M.label||M.path},M.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:j,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(M=>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:[M.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Fr(M.path,M.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(M.id),children:"Remove"})]},M.id))})]}),f&&t.jsx(Xr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:N,directories:d,busy:S,error:w,confirmLabel:"Add workspace",onClose:()=>v(!1),onNavigate:M=>{g(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&v(!1)})()}})]})}function xf(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 hf(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function wn(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 jo(e){if(!e||typeof e!="object")return null;if(wn(e))return e;const s=e,r=s.result;return wn(r)?r:wn(s.sourceConfig)?s.sourceConfig:null}function bf(e){const s=e.trim();return s||null}const ko=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],gf=[{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 yf({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[m,f]=o.useState(""),[v,N]=o.useState([]),[L,d]=o.useState(""),b=o.useRef(null),S=o.useRef(null),h=y=>{p(x=>x.includes(y)?x.filter(E=>E!==y):[...x,y])},w=()=>p([...ko]),_=()=>p([]);o.useEffect(()=>{var y;(y=b.current)==null||y.scrollIntoView({behavior:"smooth"})},[v]),o.useEffect(()=>()=>{S.current&&clearInterval(S.current)},[]);const g=o.useCallback(()=>{S.current&&clearInterval(S.current),S.current=setInterval(async()=>{try{const y=await r(e,"provider_auto_fix_status",{providerType:s.type});(y==null?void 0:y.running)===!1&&a==="running"&&(i("done"),N(x=>[...x,`
|
|
64
|
-
✅ Auto-fix completed!`]),S.current&&clearInterval(S.current))}catch{}},3e3)},[e,s.type,r,a]),j=async()=>{if(u.length!==0){i("running"),N(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const y=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});y!=null&&y.success&&(y!=null&&y.started||y!=null&&y.running)?(N(x=>[...x,"✅ Agent started. Monitoring progress..."]),g()):(i("error"),d((y==null?void 0:y.error)||"Failed to start auto-fix"))}catch(y){i("error"),d((y==null?void 0:y.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),N(y=>[...y,`
|
|
65
|
-
⚠️ Auto-fix cancelled.`]),i("done"),S.current&&clearInterval(S.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:y=>y.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:[a==="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:gf.map(y=>t.jsxs("button",{onClick:()=>l(y.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===y.value?y.color+"66":"var(--border-subtle)",background:c===y.value?y.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===y.value?y.color:"var(--text-primary)"},children:y.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:y.desc})]},y.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:w,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:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ko.map(y=>t.jsxs("button",{onClick:()=>h(y),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(y)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(y)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(y)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(y)?"☑ ":"☐ ",y]},y))})]}),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:m,onChange:y=>f(y.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="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:[v.map((y,x)=>t.jsx("div",{className:y.startsWith("✅")?"text-green-400":"",style:y.startsWith("❌")||y.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:y},x)),a==="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:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:j,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),N([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function vf({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const i=s.filter(j=>j.category==="ide"),[c,l]=o.useState(((g=i[0])==null?void 0:g.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[v,N]=o.useState(!1),[L,d]=o.useState(""),[b,S]=o.useState(!1),h=j=>{const k=j.toLowerCase().replace(/[^a-z0-9-]/g,"");p(k),(!m||m===w(u))&&f(w(k))},w=j=>j.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),_=async()=>{if(!(!u||!m||!c)){N(!0),d("");try{const j=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});j!=null&&j.success||j!=null&&j.created?(S(!0),a==null||a(u)):d((j==null?void 0:j.error)||"Failed to create provider")}catch(j){d((j==null?void 0:j.message)||"Connection failed")}N(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:j=>j.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:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm: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:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," 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(j=>t.jsxs("button",{onClick:()=>l(j.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===j.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===j.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:j.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===j.type?"#a78bfa":"var(--text-secondary)"},children:j.displayName})]},j.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:u,onChange:j=>h(j.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/",u||"...","/"]})]})]}),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:m,onChange:j=>f(j.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-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",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:_,disabled:!u||!m||v,className:"machine-btn",style:{background:u&&m?"rgba(34,197,94,0.12)":void 0,borderColor:u&&m?"rgba(34,197,94,0.3)":void 0,color:u&&m?"#86efac":void 0,opacity:!u||!m||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function wf({machineId:e,providers:s,sendDaemonCommand:r}){var I;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,v]=o.useState(null),[N,L]=o.useState(!1),[d,b]=o.useState(null),[S,h]=o.useState("normal"),[w,_]=o.useState(""),[g,j]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),T=jo(M);T&&(b(T),h(T.sourceMode),_(T.explicitProviderDir||""))}catch{}},[e,r]),y=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),T=xf(M);if(T){const W=hf(T,s);W.sort((R,C)=>R.category.localeCompare(C.category)||R.displayName.localeCompare(C.displayName)),a(W)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&y(),d||k()},[]);const x=async(M,T,W)=>{u(`${M}.${T}`),a(R=>R.map(C=>C.type===M?{...C,values:{...C.values,[T]:W}}:C));try{const R=await r(e,"set_provider_setting",{providerType:M,key:T,value:W});R!=null&&R.success||y()}catch{y()}u(null)},E=async()=>{j(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:S,providerDir:bf(w)}),T=jo(M);T?(b(T),h(T.sourceMode),_(T.explicitProviderDir||"")):await k(),await y()}catch{await k()}j(!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(M=>t.jsx("button",{onClick:()=>m(M),className:`machine-btn text-[10px] px-2 py-0.5 ${p===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),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:y,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:k,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:S,onChange:M=>h(M.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:w,onChange:M=>_(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"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…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(C=>C.category===p),T=new Map;for(const C of M)for(const H of C.schema){if(H.type!=="boolean")continue;const G=T.get(H.key),A=!!(C.values[H.key]??H.default);G?(G.onCount+=A?1:0,G.total+=1):T.set(H.key,{label:H.label||H.key,onCount:A?1:0,total:1})}const W=[...T.entries()].filter(([,C])=>C.total===M.length);if(W.length===0)return null;const R=async(C,H)=>{for(const G of M)await x(G.type,C,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 ",p.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:W.map(([C,H])=>{const G=H.onCount===H.total,A=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 R(C,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void R(C,!1),disabled:A,className:`machine-btn text-[9px] px-1.5 py-px ${A?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),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(M=>p==="all"||M.category===p).map(M=>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:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>v(s.find(T=>T.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.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:M.schema.map(T=>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:[T.label||T.key,l===`${M.type}.${T.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),t.jsx("div",{className:"shrink-0",children:T.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,T.key,!(M.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[T.key]??T.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:M.values[T.key]??T.default?21:3}})}):T.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:W=>{const R=parseInt(W.target.value)||0;T.min!==void 0&&R<T.min||T.max!==void 0&&R>T.max||x(M.type,T.key,R)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?t.jsx("select",{value:String(M.values[T.key]??T.default??""),onChange:W=>x(M.type,T.key,W.target.value),className:"machine-input text-[11px]",children:T.options.map(W=>t.jsx("option",{value:W,children:W},W))}):t.jsx("input",{type:"text",value:String(M.values[T.key]??T.default??""),onBlur:W=>x(M.type,T.key,W.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},M.type))}),f&&t.jsx(yf,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>v(null)}),N&&t.jsx(vf,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>L(!1),onCreated:()=>{L(!1),y()}})]})}const jf=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function kf({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Nf(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function No(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 Sf({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[u,p]=o.useState(0),[m,f]=o.useState(0),[v,N]=o.useState(!0),[L,d]=o.useState("debug"),[b,S]=o.useState("all"),h=o.useRef(null),w=o.useRef(!1),_=Nf(a,b);return o.useEffect(()=>{if(!e||!v)return;const g=async()=>{try{const[k,y]=await Promise.all([s(e,"get_logs",{count:200,minLevel:L,since:u}),s(e,"get_debug_trace",kf({count:120,since:m,category:b}))]),x=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(M=>[...M,...x.logs.map(W=>({timestamp:W.ts,level:W.level,message:`[${W.category}] ${W.message}`}))].slice(-300));const I=Math.max(...x.logs.map(M=>M.ts));p(I)}const E=(y==null?void 0:y.result)||y;if(y!=null&&y.success&&Array.isArray(E==null?void 0:E.trace)){i(E.trace.slice(-120));const I=E.trace.reduce((M,T)=>Math.max(M,Number(T.ts||0)),m);I>m&&f(I)}}catch{}l(cs.list({limit:120}))};g();const j=setInterval(g,3e3);return()=>clearInterval(j)},[e,v,u,m,L,b,s]),o.useEffect(()=>{if(v&&(r.length>0||a.length>0||c.length>0)){const g=w.current?"smooth":"instant";setTimeout(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:g}),w.current=!0},50)}},[r.length,a.length,c.length,v]),o.useEffect(()=>{i([]),f(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(g=>t.jsx("button",{onClick:()=>{d(g),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${L===g?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.toUpperCase()},g))]}),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=",_.length," web=",c.length]}),t.jsx("button",{onClick:()=>N(!v),className:`machine-btn ${v?"text-green-500 border-green-500/30":""}`,children:v?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),cs.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((g,j)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:g.level==="error"?"#ef4444":g.level==="warn"?"var(--status-warning)":g.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(g.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:g.level==="error"?"ERR":g.level==="warn"?"WRN":g.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:g.message})]},`log-${j}`))]}),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:jf.map(g=>t.jsx("button",{onClick:()=>S(g.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===g.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.label},g.value))})]}),_.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."}),_.map(g=>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(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.level.toUpperCase()}),t.jsxs("span",{children:[g.category,".",g.stage]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:No(g.payload)})]},g.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(g=>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(g.ts).toLocaleTimeString()}),t.jsx("span",{children:g.kind}),g.topic&&t.jsxs("span",{children:["topic=",g.topic]}),g.interactionId&&t.jsxs("span",{children:["ix=",g.interactionId]})]}),t.jsx("div",{children:No(g.payload)})]},g.id))]})]}),t.jsx("div",{ref:h})]})}function jn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function kn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function So(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 a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Cf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function If(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 Af(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Tf({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=Li(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,v=p.applyDiagnostics,N=o.useMemo(()=>zp({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),L=o.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const I=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),M=jn(I);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");v(M.diagnostics||M.result||null),a("")}catch(I){const M=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[v,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(I,M)=>{const T=`${I}:${M.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
66
|
-
This will terminate the hosted runtime.`))){c(T);try{const W=await r(e,I,{sessionId:M.sessionId}),R=jn(W);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const C=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${C}: ${M.displayName}`,"success"),await d()}catch(W){const R=W instanceof Error?W.message:"Session host action failed";it.showToast(R,"warning"),a(R)}finally{c(W=>W===T?null:W)}}},[e,d,r]),S=o.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 M=await r(e,"session_host_prune_duplicate_sessions",{}),T=jn(M);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const W=T.result||{},R=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,C=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;it.showToast(`Pruned ${R} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(M){const T=M instanceof Error?M.message:"Duplicate prune failed";it.showToast(T,"warning"),a(T)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((I,M)=>(M.lastActivityAt||0)-(I.lastActivityAt||0)),[m==null?void 0:m.sessions]),w=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:ac(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=w.liveRuntimes,g=w.recoverySnapshots,j=w.inactiveRecords,k=o.useMemo(()=>Af(_),[_]),y=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[m==null?void 0:m.recentLogs]),E=(I,M)=>{var B;const T=i===`session_host_resume_session:${I.sessionId}`,W=i===`session_host_restart_session:${I.sessionId}`,R=i===`session_host_stop_session:${I.sessionId}`,C=ba(I.meta),H=L.get(I.sessionId),G=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,A=M==="recovery"?"Recover":"Resume",$=oc(M);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 ${If(I.lifecycle)}`,children:I.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),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:((B=I.writeOwner)==null?void 0:B.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Cf(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(Vn,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",So(I.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="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:T?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",I)},children:W?"Restarting…":"Restart"}),M==="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:R?"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(Ot,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:iu()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{S()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${N.toneClass}`,children:N.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(_s,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&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(ds,{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})]})]})}),m&&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:m.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:g.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:m.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:So(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:kn(m.hostStartedAt)})]})]}),x&&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(ds,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[kn(x.timestamp),x.sessionId?` · ${x.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(Or,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ks("live")}),_.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:_.map(I=>E(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(Ot,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ks("recovery")}),g.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:g.map(I=>E(I,"recovery"))})]}),j.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:ks("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:j.map(I=>E(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"}),y.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:y.map(I=>{var T;const M=h.find(W=>W.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:(M==null?void 0:M.displayName)||((T=L.get(I.sessionId))==null?void 0:T.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:kn(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:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Mf({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",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:()=>{a(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:()=>{a(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:()=>{a(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:()=>a(null),children:"Cancel"})]})]})})}function Nn({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 Sn({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 Lf({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=Fs(e,"0.8.66");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(Nn,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(Sn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const v=$n(f);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(f),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:ct(f)}),v>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ur(v)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ps(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(Oo,{size:13}),children:"Recent Launches"}),t.jsx(Sn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:v,updatedLabel:N}=zi(f);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(f),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:f.label}),N&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:v})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Nn,{icon:t.jsx(ds,{size:13}),children:"Daemon Update"}),t.jsx(Sn,{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:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),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:a,children:[t.jsx(_s,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function _f(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Rf(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Pf={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 Df(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 Cn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Ls(),{handleLaunchIde:f,handleStopCli:v,handleRestartIde:N,handleStopIde:L,handleDetectIdes:d,launchingIde:b,launchingAgentType:S,addLog:h}=c,[w,_]=o.useState(null),g=o.useCallback(P=>{P&&m(_f(P))},[m]),j=Pf[e],k=e==="ide",y=e==="acp",x=o.useMemo(()=>n.filter(P=>P.category===e&&(e==="ide"||P.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map(P=>[P.type,P.displayName||P.type])),[x]),[I,M]=o.useState(""),[T,W]=o.useState(""),[R,C]=o.useState([]),[H,G]=o.useState(""),[A,$]=o.useState(""),[B,O]=o.useState([]),[X,je]=o.useState(!1),[$e,me]=o.useState(""),[_e,ae]=o.useState(!1),[ee,se]=o.useState(()=>gt()),[ue,re]=o.useState(null),[z,le]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[Z,ie]=o.useState(p||""),[Q,de]=o.useState([]),[oe,ge]=o.useState(!1),[fe,D]=o.useState(""),[ye,be]=o.useState([]),[Ne,J]=o.useState(!1),[Se,Ue]=o.useState(""),De=o.useRef(null),[Ve,Ye]=o.useState(null),Xe=o.useRef("__home__"),[pt,Ge]=o.useState("__home__"),[bt,lt]=o.useState(!1),dt=o.useRef(0),xt=Q.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")),at=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!z&&le(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){le("__custom__"),ie(p);return}u&&(le(u),ie(""))},[u,p]),o.useEffect(()=>{k||I&&(x.some(P=>P.type===I)||(M(""),$("")))},[x,k,I]);const pe=(()=>{if(z==="__custom__")return Z.trim();if(!z)return"";const P=(s.workspaces||[]).find(Y=>Y.id===z);return(P==null?void 0:P.path)||""})(),Fe=o.useCallback(P=>{const Y=at.current[P];Y&&(clearTimeout(Y),delete at.current[P]),de(ce=>ce.includes(P)?ce.filter(Pe=>Pe!==P):ce)},[]),Qe=o.useRef(new Set),et=o.useCallback(async P=>{if(l){J(!0),Ue("");try{const Y=await Yr(l,r,P);D(Y.path),ie(Y.path),be(Y.directories)}catch(Y){Ue(Y instanceof Error?Y.message:"Could not load folder")}finally{J(!1)}}},[r,l]),ht=o.useCallback(()=>{if(!l)return;le("__custom__"),ge(!0);const P=a.map(ce=>ce.workspace),Y=qr(s.platform,Gr(Z.trim(),pe,p,P,s.defaultWorkspacePath,(s.workspaces||[]).map(ce=>ce.path)));et(Y)},[Z,p,et,s.defaultWorkspacePath,s.platform,s.workspaces,a,pe,l]),yt=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return;const ce=(s.workspaces||[]).find(Pe=>yr(Pe.path)===yr(Y));if(ce){le(ce.id),ie("");return}le("__custom__"),ie(Y)},[s.workspaces]),Rt=o.useCallback(P=>{const Y=String(P.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const ce=(s.workspaces||[]).find(Pe=>yr(Pe.path)===yr(Y));return ce?{workspaceId:ce.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),Nt=o.useCallback(async P=>{if(!l||!P||e!=="cli"){O([]),je(!1),me("");return}const Y=dt.current+1;dt.current=Y,je(!0),me("");try{const ce=await l(r,"list_saved_sessions",{providerType:P,kind:"cli",limit:30});if(dt.current!==Y)return;const Pe=(ce==null?void 0:ce.result)??ce;O(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(ce){if(dt.current!==Y)return;O([]),me(ce instanceof Error?ce.message:"Could not load saved sessions")}finally{dt.current===Y&&je(!1)}},[e,r,l]),At=o.useMemo(()=>{if(e!=="cli"||!I)return null;const P=E.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:P,agentType:I,status:"idle",title:P,messages:[],ideType:I,workspaceName:pe,displayPrimary:P,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,E,pe,A,I]),q=o.useCallback(P=>{if(e==="ide"||!P){C([]);return}C(rc(r,P))},[e,r]);o.useEffect(()=>{if($(""),q(I),e!=="cli"||!I){O([]),me(""),je(!1);return}Nt(I)},[e,q,Nt,I]);const Be=o.useMemo(()=>B.find(P=>P.providerSessionId===A)||null,[B,A]);o.useEffect(()=>{if(!A)return;const P=B.find(Y=>Y.providerSessionId===A);P!=null&&P.canResume||$("")},[B,A]);const Re=o.useCallback((P,Y)=>{De.current=Y,Xe.current=P.selectedWorkspaceKey||"__home__",Ge(P.selectedWorkspaceKey||"__home__"),Ye(P)},[]),K=o.useCallback(()=>{De.current&&(lt(!0),De.current().finally(()=>{De.current=null,lt(!1),Ye(null)}))},[]),U=o.useCallback(P=>{if(!P)return;de(ce=>ce.includes(P)?ce:[...ce,P]);const Y=at.current[P];Y&&clearTimeout(Y),at.current[P]=setTimeout(()=>{de(ce=>ce.includes(P)?ce.filter(Pe=>Pe!==P):ce),delete at.current[P]},2e4)},[]);o.useEffect(()=>{for(const Y of a)jt(Y.status)!=="stopped"&&(Q.includes(Y.type)&&!Qe.current.has(Y.type)&&(Qe.current.add(Y.type),h("info",`${E.get(Y.type)||Y.type} launched`,!0)),Fe(Y.type));const P=new Set(a.filter(Y=>jt(Y.status)!=="stopped").map(Y=>Y.type));Qe.current.forEach(Y=>{!Q.includes(Y)&&!P.has(Y)&&Qe.current.delete(Y)})},[h,Fe,a,Q,E]),o.useEffect(()=>()=>{Object.values(at.current).forEach(clearTimeout),at.current={}},[]);const[F,V]=o.useState({}),[ne,we]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),ce=(Y==null?void 0:Y.result)||Y;ce!=null&&ce.success&&(ce!=null&&ce.ideExtensions)&&V(ce.ideExtensions)}catch{}})()},[k,r,l]);const Ie=P=>k?nt(P.type):e==="cli"?P.cliName:P.acpName,Ce=k?s.detectedIdes||[]:[],We=o.useCallback(async P=>{const Y=(P==null?void 0:P.type)||I,ce=(P==null?void 0:P.workspacePath)??pe;if(k){await f(Y,ce?{workspace:ce}:void 0)&&U(Y);return}const Pe=await c.runLaunchCliCore({cliType:Y,dir:P!=null&&P.workspaceId?void 0:ce||void 0,workspaceId:(P==null?void 0:P.workspaceId)||void 0,useHome:(P==null?void 0:P.useHome)||!(P!=null&&P.workspaceId)&&!ce,argsStr:(P==null?void 0:P.argsStr)??(T||void 0),model:(P==null?void 0:P.model)??(y&&H||void 0),resumeSessionId:(P==null?void 0:P.resumeSessionId)||!y&&e==="cli"&&Y===I&&A||void 0});if(Pe.success||Pe.pending){const Te=(P==null?void 0:P.argsStr)??T;!k&&(Te!=null&&Te.trim())&&(nc(r,Y,Te),q(Y)),U(Y),Pe.success&&Pe.sessionId&&g(Pe.sessionId)}},[c,f,y,k,T,H,q,U,r,g,pe,A,I]),Oe=fi(k?"ide":y?"acp":"cli",!k&&!y&&!!A),Je=xi(k?"ide":y?"acp":"cli",!k&&!y&&!!A),Le=()=>{var Te;const P=k?nt(I):E.get(I)||I,Y=!k&&!y&&!!A,{options:ce,selectedKey:Pe}=is({machine:s,currentWorkspaceId:z&&z!=="__custom__"?z:null,currentWorkspacePath:pe});Re({title:Y?aa(P):ss("start-fresh",P),description:Y?oa():rs("start-fresh"),confirmLabel:Oe,busyLabel:Je,workspaceOptions:ce,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:j.label},{label:"Provider",value:P},...!k&&e==="cli"&&A?[{label:"Resume",value:((Te=B.find(Ee=>Ee.providerSessionId===A))==null?void 0:Te.title)||A}]:[],...!k&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...y&&H.trim()?[{label:"Model",value:H.trim()}]:[]]},async()=>{const Ee=ce.find(ve=>ve.key===Xe.current);Ee!=null&&Ee.workspaceId?(le(Ee.workspaceId),ie("")):Ee!=null&&Ee.workspacePath?(le("__custom__"),ie(Ee.workspacePath)):(le(""),ie("")),await We({workspaceId:(Ee==null?void 0:Ee.workspaceId)??null,workspacePath:(Ee==null?void 0:Ee.workspacePath)??"",useHome:!(Ee!=null&&Ee.workspaceId)&&!(Ee!=null&&Ee.workspacePath)})})},te=P=>{k?L(P):v(P.type,P.workspace,P.id)},Ae=o.useCallback(async(P,Y,ce=!1)=>{if(P.mode===Y){ce&&P.sessionId&&g(P.sessionId);return}if(!l||!P.sessionId){ce&&P.sessionId&&g(P.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:P.sessionId,cliType:P.type,mode:Y}),ce&&g(P.sessionId)}catch(Pe){Df(Pe)?console.warn("Skipped CLI view mode switch:",Pe instanceof Error?Pe.message:String(Pe)):console.error("Failed to switch CLI view mode:",Pe)}},[r,g,l]),Ke=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:P=>{const Y=P.target.value;if(le(Y),Y==="__custom__"&&l){ht();return}Y!=="__custom__"&&ie("")},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(P=>t.jsxs("option",{value:P.id,children:[P.id===s.defaultWorkspaceId?"⭐ ":"",Fr(P.path,P.label)]},P.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:ht,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:Z,onChange:P=>ie(P.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:z==="__custom__"?pe?t.jsx("span",{className:"font-mono truncate block",title:pe,children:pe}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":pe?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:pe,children:pe})]}):"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 ${j.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 ",j.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(P=>{const Y=a.find(ve=>(ve.type||"").toLowerCase()===(P.type||"").toLowerCase()&&jt(ve.status)!=="stopped"),ce=P.running||!!Y,Pe=!!Y&&Y.cdpConnected,Te=Q.includes(P.type||P.id||""),Ee=I===(P.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&Y){const ve=Y.sessionId;ve?m(`/dashboard?activeTab=${encodeURIComponent(ve)}`,{state:{openRemoteForTabKey:ve}}):m("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Te||M(ve=>ve===(P.type||"")?"":P.type||"")},disabled:!!b||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Pe?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==P.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(P.type)}),ce&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Pe?"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:P.name||nt(P.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":Te?"text-orange-400":Ee?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":Te?"Starting...":Ee?"Configure":"Select"})]})]},P.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(el,{size:14})," Scan System"]})]}):x.length>0?x.map(P=>{const Y=I===P.type,ce=Q.includes(P.type),Te=!!a.find(Ee=>Ee.type===P.type&&jt(Ee.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Ee=>Ee===P.type?"":P.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"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:P.icon}),Te&&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:P.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ce?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:ce?"Starting...":Y?"Configure":"Select"})]})]},P.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&&(k?Ce.find(P=>P.type===I):x.find(P=>P.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:k?nt(I):E.get(I)||I})]}),Ke,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!y&&e==="cli"&&t.jsx(ic,{busy:!!S||!!b||Q.includes(I),savedSessionsLoading:X,savedSessionsError:$e,selectedSession:Be,onRefresh:()=>void Nt(I),onOpenHistory:()=>{I&&(ae(!0),Nt(I))},onClearSelection:()=>$("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&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:P=>G(P.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),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:T,onChange:P=>W(P.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(P=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(P),title:P,children:P},P))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Le,disabled:!!S||!!b||Q.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:S===I||b===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+Q.filter(P=>!a.some(Y=>Y.type===P&&jt(Y.status)!=="stopped")).length,")"]}),a.length===0&&xt.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 ",j.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[xt.map(P=>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(P)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?nt(P):E.get(P)||P}),t.jsx("div",{className:"text-[11px] text-text-muted",children:S===P?"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:${P}`)),a.map(P=>{const Y=k?P:null,ce=!k&&!y?P:null,Pe=jt(P.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(P.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(P),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:P.workspace||"—"}),(ce==null?void 0:ce.mode)&&t.jsx("span",{className:ce.mode==="chat"?"text-violet-400":"text-text-secondary",children:ce.mode==="chat"?"Chat view":"Terminal view"})]}),ce&&(ce.runtimeKey||ce.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ce.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 ",ce.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 Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${ce.runtimeKey}`),_(ce.runtimeKey||null),window.setTimeout(()=>{_(Ee=>Ee===ce.runtimeKey?null:Ee)},1200)},children:w===ce.runtimeKey?"Copied":"Copy"})]}),ce.runtimeWriteOwner&&t.jsx("span",{style:{color:ce.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ce.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Rf(ce.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 ${Pe==="stopped"?"bg-red-500/[0.08] text-red-500":Pe==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Pe}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Te=P.sessionId;if(Te){m(`/dashboard?activeTab=${encodeURIComponent(Te)}`,{state:{openRemoteForTabKey:Te}});return}m("/dashboard",{state:{openRemoteForTabKey:P.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(It,{size:13})}),t.jsx("button",{onClick:()=>{const Te=P.workspace||"",{options:Ee,selectedKey:ve}=is({machine:s,currentWorkspacePath:Te});Re({title:ss("restart-ide",nt(P.type)),description:rs("restart-ide"),confirmLabel:Ts("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Ee,selectedWorkspaceKey:ve,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:nt(P.type)}]},async()=>{const tt=Ee.find(zt=>zt.key===Xe.current),ot=(tt==null?void 0:tt.workspacePath)??"";if(ot&&ot!==Te){await We({type:P.type,workspacePath:ot});return}await N(P)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(_s,{size:14})})]}),y&&t.jsx("button",{onClick:()=>{const Te=P.sessionId;Te&&g(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!P.sessionId,children:t.jsx(Ht,{size:14})}),ce&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[ce.mode&&t.jsx(sa,{mode:ce.mode,onChange:Te=>void Ae(ce,Te,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Te=P.sessionId;Te&&g(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!P.sessionId,children:ce.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(It,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const Te=P.workspace||"",Ee=k?nt(P.type):Ie(P),{options:ve,selectedKey:tt}=is({machine:s,currentWorkspacePath:Te});Re({title:ss("restart-stopped",Ee),description:rs("restart-stopped"),confirmLabel:Ts("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:ve,selectedWorkspaceKey:tt,details:[{label:"Mode",value:j.label},{label:"Provider",value:Ee}]},async()=>{const ot=ve.find(zt=>zt.key===Xe.current);await We({type:P.type,workspaceId:(ot==null?void 0:ot.workspaceId)??null,workspacePath:(ot==null?void 0:ot.workspacePath)??"",useHome:!(ot!=null&&ot.workspaceId)&&!(ot!=null&&ot.workspacePath)})})},disabled:Q.includes(P.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:Q.includes(P.type)?"⏳":t.jsx(qn,{size:14})}):t.jsx("button",{onClick:()=>te(P),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(kt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Te=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${qo(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",jt(Te.status)]},Te.id))}),Y&&(F[Y.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:(F[Y.type]||[]).map(Te=>t.jsxs("button",{disabled:ne===`${Y.type}.${Te.type}`,onClick:async()=>{const Ee=`${Y.type}.${Te.type}`;we(Ee);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Te.type,enabled:!Te.enabled}),V(ve=>({...ve,[Y.type]:(ve[Y.type]||[]).map(tt=>tt.type===Te.type?{...tt,enabled:!tt.enabled}:tt)}))}catch(ve){console.error("Extension toggle failed:",ve)}finally{we(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 ${Te.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 ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,t.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},P.id)})]}),oe&&l&&t.jsx(Xr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:fe,directories:ye,busy:Ne,error:Se,confirmLabel:"Use this folder",onClose:()=>ge(!1),onNavigate:P=>{et(P)},onConfirm:P=>{ie(P),le("__custom__"),ge(!1)}}),Ve&&t.jsx(xa,{title:Ve.title,description:Ve.description,details:Ve.details,workspaceOptions:Ve.workspaceOptions,selectedWorkspaceKey:pt,onWorkspaceChange:P=>{Xe.current=P,Ge(P)},confirmLabel:Ve.confirmLabel,busyLabel:Ve.busyLabel,busy:bt,onConfirm:K,onCancel:()=>{De.current=null,Ye(null)}}),_e&&At&&t.jsx(ia,{activeConv:At,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:B,isSavedSessionsLoading:X,isResumingSavedSessionId:ue,savedHistoryFilters:ee,onSavedHistoryFiltersChange:se,onClose:()=>ae(!1),onNewChat:()=>{$(""),ae(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Nt(I)},onResumeSavedSession:P=>{if(!P.canResume||ue)return;const Y=Rt(P);$(P.providerSessionId),yt(P),re(P.providerSessionId),ae(!1),We({type:P.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:P.providerSessionId}).finally(()=>{re(ce=>ce===P.providerSessionId?null:ce)})}})]})}const Co=[{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 Ef({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[v,N]=o.useState(u);o.useEffect(()=>{N(u)},[u]);const L=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.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:Co.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 ${v===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>N(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===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=Co.find(b=>b.id===v))==null?void 0:d.helper})]}),v==="ide"&&t.jsx(Cn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),v==="cli"&&t.jsx(Cn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),v==="acp"&&t.jsx(Cn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function $f({onNicknameSynced:e}={}){var z,le,Z,ie,Q,de,oe,ge,fe;const{id:s}=Ec(),r=Ls(),n=zn(),{sendCommand:a}=_t(),i=er(),c=ii(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(D=>D.id===s&&D.type==="adhdev-daemon"),m=l.some(D=>D.type==="adhdev-daemon"),[f,v]=o.useState("workspace"),[N,L]=o.useState("ide"),d=o.useRef(null),[b,S]=o.useState(null),h=o.useRef("__home__"),[w,_]=o.useState("__home__"),[g,j]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Ju(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const y=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=pf({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>it.onToast(ye=>{c.setToasts(Ne=>{if(Ne.some(Ue=>Ue.message===ye.message&&ye.timestamp-Ue.timestamp<3e3))return Ne;const Se={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...Ne.slice(-4),Se]});const be=ye.duration||5e3;setTimeout(()=>c.setToasts(Ne=>Ne.filter(J=>J.id!==ye.id)),be)}),[c]);const E=(p==null?void 0:p.availableProviders)||[],I={};for(const D of E)I[D.type]=D.icon;const M=D=>I[D]||"",T=p?{id:p.id,hostname:Yo(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((le=p.machine)==null?void 0:le.arch)||"",cpus:((Z=p.machine)==null?void 0:Z.cpus)||0,totalMem:((ie=p.machine)==null?void 0:ie.totalMem)||0,freeMem:(Q=p.machine)==null?void 0:Q.freeMem,availableMem:(de=p.machine)==null?void 0:de.availableMem,loadavg:(oe=p.machine)==null?void 0:oe.loadavg,uptime:(ge=p.machine)==null?void 0:ge.uptime,release:((fe=p.machine)==null?void 0:fe.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,W=l.filter(D=>D.daemonId===s&&D.type!=="adhdev-daemon").filter(D=>!Xs(D)&&!ws(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Fl(D.aiAgents||(D.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:s})),R=l.filter(D=>D.daemonId===s&&Xs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:s})),C=l.filter(D=>D.daemonId===s&&ws(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:s})),H=p?Ct(p,{fallbackId:s}):"",G="workspace",A=n.state,$=A==null?void 0:A.initialMachineTab,B=A==null?void 0:A.initialWorkspaceCategory,O=A==null?void 0:A.initialWorkspaceId,X=A==null?void 0:A.initialWorkspacePath,je=$==="ides"||$==="clis"||$==="acps"?"workspace":$||G,$e=$==="ides"?"ide":$==="clis"?"cli":$==="acps"?"acp":B,me=[...W.map(D=>{var ye,be,Ne,J,Se;return{id:`ide:${D.type}:${D.workspace||""}`,label:((ye=D.activeChat)==null?void 0:ye.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(J=(Ne=(be=D.activeChat)==null?void 0:be.messages)==null?void 0:Ne.at)==null?void 0:J.call(Ne,-1))==null?void 0:Se.timestamp)||0}}),...R.map(D=>{var ye,be,Ne,J,Se;return{id:`cli:${D.type}:${D.workspace||""}`,label:((ye=D.activeChat)==null?void 0:ye.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(J=(Ne=(be=D.activeChat)==null?void 0:be.messages)==null?void 0:Ne.at)==null?void 0:J.call(Ne,-1))==null?void 0:Se.timestamp)||0}}),...C.map(D=>{var ye,be,Ne,J,Se;return{id:`acp:${D.type}:${D.workspace||""}`,label:((ye=D.activeChat)==null?void 0:ye.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:us(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Se=(J=(Ne=(be=D.activeChat)==null?void 0:be.messages)==null?void 0:Ne.at)==null?void 0:J.call(Ne,-1))==null?void 0:Se.timestamp)||0}})].sort((D,ye)=>(ye.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),_e=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:us(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):me,ae=o.useMemo(()=>{var ye;const D=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return l.filter(be=>be.daemonId===s&&be.type!=="adhdev-daemon").flatMap(be=>ca(be,{},{connectionStates:s&&D?{[s]:D}:void 0,defaultConnectionState:D})).filter(be=>!(be.transport==="pty"&&be.mode==="terminal")).sort((be,Ne)=>$n(Ne)-$n(be))},[l,c.connectionStates,s]),ee=o.useCallback(D=>{const ye=D.sessionId||D.tabKey;ye&&r(`/dashboard?activeTab=${encodeURIComponent(ye)}`)},[r]),se=o.useCallback(()=>{d.current&&(j(!0),d.current().finally(()=>{d.current=null,j(!1),S(null)}))},[]),ue=o.useCallback(D=>{if(!T)return;const{options:ye,selectedKey:be}=is({machine:T,currentWorkspacePath:D.workspace}),Ne=async()=>{L(D.kind),v("workspace")};d.current=async()=>{const J=ye.find(De=>De.key===h.current),Se=(J==null?void 0:J.workspacePath)??null,Ue=(J==null?void 0:J.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await x.handleLaunchIde(D.providerType,Se?{workspace:Se}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await x.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:Se||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&Qo(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Ne()},h.current=be,_(be),S({title:D.kind==="ide"?ss("restart-ide",D.label):D.providerSessionId?aa(D.label):ss("start-fresh",D.label),description:D.kind==="ide"?rs("restart-ide"):D.providerSessionId?oa():rs("start-fresh"),confirmLabel:D.kind==="ide"?Ts("restart-ide"):D.providerSessionId?Pr(!0):Ts("start-fresh"),busyLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?ra(!0):Ms("start-fresh"),workspaceOptions:ye,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{v(je)},[G,je,s]),o.useEffect(()=>{$e&&L($e)},[$e,s]),!T)return u?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:y,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:W.length+R.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ot,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Wr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(tl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jc,{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:y,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:D=>x.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&x.handleSaveNickname(),D.key==="Escape"&&x.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:x.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:()=>x.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:()=>{x.setEditingNickname(!0),x.setNicknameInput(T.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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.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(D=>t.jsxs("button",{onClick:()=>v(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.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:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Lf,{machineEntry:p,providers:E,recentLaunches:_e,currentConversations:ae,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:ee}),t.jsx(Ef,{machine:T,machineId:s,providers:E,ideSessions:W,cliSessions:R,acpSessions:C,actions:x,getIcon:M,initialCategory:N,initialWorkspaceId:O,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(wf,{machineId:s,providers:E,sendDaemonCommand:a}),f==="overview"&&t.jsx(ff,{machineId:s,machine:T,ideSessions:W,cliSessions:R,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Tf,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(Sf,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(Mf,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx(xa,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:D=>{h.current=D,_(D)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:g,onConfirm:se,onCancel:()=>{d.current=null,S(null)}}),t.jsx(hi,{toasts:c.toasts||[],onDismiss:D=>c.setToasts(ye=>ye.filter(be=>be.id!==D)),onClickToast:D=>{D.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(D.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 Bf{constructor(){ft(this,"adapters",new Map);ft(this,"states",new Map);ft(this,"runtimeListeners",new Map);ft(this,"screenshotCallbacks",new Map);ft(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,a){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,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}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 a=this.runtimeListeners.get(s);a&&(a.delete(r),a.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 a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Kt=new Bf;function Kf(){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=Kf(),Io=3e3,Wf=3e4;let $t=null,Of=0;const Kr=new Map;let Zt=null,Gs=null;function Ao(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Os(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Hf(e){return e==="connected"?"connected":e}async function Ir(e,s,r){const n=yu(e,r||{}),a=$t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Of}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Kr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Kr.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function On(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 Uf{constructor(s){ft(this,"daemonId");ft(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 Ir(this.daemonId,s,r)}async sendInput(s,r){return Ir(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Zt&&(clearInterval(Zt),Zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ir(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Zt=setInterval(r,2e3)}stopScreenshots(s){Zt&&(clearInterval(Zt),Zt=null)}}let Mt=null;function zf(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new Uf(e)),Mt}function Ff({children:e}){const s=o.useRef(Tr()),r=Tr();s.current=r;const{setUserName:n}=ls(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),Gs==null||Gs(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Io),v=o.useRef(!0),N=o.useRef(!1),L=o.useRef("initial_connect");return o.useEffect(()=>{v.current=!0,N.current=!1;function d(){var h,w;if(!v.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${vr}...`),Os("connect_attempt",{url:vr,reason:L.current,delayMs:f.current});let S;try{S=new WebSocket(vr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=S,S.onopen=()=>{if(!v.current){S.close();return}u("connected"),f.current=Io,Os("open",{url:vr,reason:L.current}),Gt.resubscribeAll({sendData:On}),console.log("[Standalone WS] Connected")},$t=S,S.onmessage=_=>{var g,j;try{const k=JSON.parse(_.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const y=Kr.get(k.requestId);y&&(Kr.delete(k.requestId),k.type==="error"?y.reject(new Error(((g=k.data)==null?void 0:g.message)||"Command failed")):y.resolve(k.data));return}if(k.type==="session_output"){const y=k.sessionId||k.cliId||k.cliType;y&&Kt.emitSessionOutput(y,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="topic_update"){const y=k.update;y&&Gt.publish(y);return}if(k.type==="status"||k.type==="initial_state"){const y=k.data;if(!y)return;const{injectEntries:x,markLoaded:E,getIdes:I}=s.current,M=y.instanceId||"standalone",T=I().find(C=>C.id===M),W=zf(M);Kt.register(M,W),Kt.setState(M,"connected"),u("connected",M),Kt.emitStatus(M,y);const R=Rr(y,{daemonId:M,existingDaemon:T,existingEntries:I()});Ao("ws_status",{type:k.type,daemonId:M,sessions:(y.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(y.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ao("entries",{daemonId:M,entries:R.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),R.length>0&&x(R,{authoritativeDaemonIds:[M]}),E(),c.current!==M&&((j=i.current)==null||j.call(i),c.current=M,i.current=Gt.subscribe({sendData:On},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const H=s.current.getIdes(),G=H.find($=>$.id===M),A=Rr(C.status,{daemonId:M,existingDaemon:G,existingEntries:H,timestamp:C.timestamp});A.length>0&&s.current.injectEntries(A),C.userName&&a.current&&a.current(C.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},S.onclose=_=>{v.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Kt.setState(Mt.daemonId,"disconnected"),u("disconnected"),p.current=null,L.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Os("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},S.onerror=_=>{N.current||!v.current||(L.current="error",Os("error",{message:_ instanceof Event?"event":String(_),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!v.current)return;clearTimeout(m.current);const S=f.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),Os("schedule_reconnect",{reason:L.current,delayMs:S}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Wf),d()},S)}return d(),()=>{var S;v.current=!1,N.current=!0,(S=i.current)==null||S.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,$t=null),Mt&&(Mt.stopScreenshots(),Kt.unregister(Mt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Vf({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Hf(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(zc,{connectionOverrides:i,children:t.jsx(Ff,{children:e})})}const Gf=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Eo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ot,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Wr,{}),label:"Settings"}];function qf({children:e}){const s=Ls(),r=zn(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" 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:()=>a(!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:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!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:()=>a(!1),children:t.jsx(kt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Gf.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.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($o,{})}),!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(Bo,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.66"]}),t.jsx(_u,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,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 Yf=[{icon:t.jsx(Ot,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ko,{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(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx($o,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Xf=[{icon:t.jsx(nl,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Eo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Hr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Qc,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Vn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Zc,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Qf=[{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 Jf(){return t.jsxs(ji,{icon:t.jsx(Bo,{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.66"]}),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:Yf.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:yi.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:wi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:vi.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:Xf.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:Qf.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(ki,{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(fl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Zf(){const{ides:e}=ls(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=_t(),{userName:a}=ls(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const v=f.target.value.trim();s!=null&&s.id&&v!==a&&n(s.id,"set_user_name",{userName:v}).catch(console.error)},[u,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(ji,{icon:t.jsx(Wr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Cu,{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.66"]}),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(f=>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 ${f.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:f.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),t.jsx(Dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Eu,{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(Wu,{})]}),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(qu,{})]}),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(Xu,{})]})]})}),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(Ru,{}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(pl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:u,onChange:m})]})}),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(Xc,{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:f=>c(f.target.value),onBlur:l,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}Lu();Vu();const ex=Po({baseUrl:""});function To(){const{ides:e,initialLoaded:s}=ls();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(Tn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Tn,{to:"/dashboard",replace:!0})}function tx(){const e=o.useMemo(()=>({sendCommand:Ir,sendData:On}),[]);return t.jsx($c,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Gc,{client:ex,children:t.jsx(Vf,{children:t.jsx(Yc,{value:e,children:t.jsx(qf,{children:t.jsxs(Bc,{children:[t.jsx(Qt,{path:"/dashboard",element:t.jsx(mf,{})}),t.jsx(Qt,{path:"/machine",element:t.jsx(To,{})}),t.jsx(Qt,{path:"/machines/:id",element:t.jsx($f,{})}),t.jsx(Qt,{path:"/machines",element:t.jsx(To,{})}),t.jsx(Qt,{path:"/about",element:t.jsx(Jf,{})}),t.jsx(Qt,{path:"/settings",element:t.jsx(Zf,{})}),t.jsx(Qt,{path:"*",element:t.jsx(Tn,{to:"/dashboard",replace:!0})})]})})})})})})}Gd({connectionManager:Kt});Kc(document.getElementById("root")).render(t.jsx(tx,{}));
|