@adhdev/daemon-standalone 0.8.74 → 0.8.75
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,7 +1,7 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var al=Object.defineProperty;var ol=(e,s,r)=>s in e?al(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var qe=(e,s,r)=>ol(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ea,a as ta,b as Vo,c as Go,u as Bs,R as nt,d as rr,t as il,e as cl,D as ll,f as Bn,g as Wn,h as sa,i as dl,k as ul,B as ml,l as pl,m as ss,N as On,n as fl}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 hl(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 Ts=hl();function Oa(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}}function xl(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function bl(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 Xs(e,s){const r=xl(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??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)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:bl(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),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Ha(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?Xs(n,a):n})}const qo=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}),Yo=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ua(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 mn(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 Br(e){return Array.isArray(e)?e.map(Br):!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,Br(r)]))}function gl(e,s){try{return JSON.stringify(Br(e))===JSON.stringify(Br(s))}catch{return!1}}function fr(e,s,r){return gl(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function yl(e,s,r){var u,p,m,f,y,k,T;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 g=i.get(d.id);if(!g){i.set(d.id,{...d,_lastUpdate:n});continue}const v=Ua(d),h=Ua(g);if(v>h){const C=(u=d.chats)!=null&&u.length?d.chats:g.chats,P=Ha(g.childSessions,d.childSessions),b=mn(g,d,{...g,...d,chats:C,childSessions:P,_lastUpdate:n});i.set(d.id,fr(g,b,n))}else if(v<h){const C={};if(d.status&&d.status!==g.status&&(C.status=d.status),d.cdpConnected!==void 0&&(C.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=g.chats)!=null&&m.length)&&(C.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==g.machineNickname&&(C.machineNickname=d.machineNickname),d.version!==void 0&&(C.version=d.version),d.serverVersion!==void 0&&(C.serverVersion=d.serverVersion),d.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const P=mn(g,d,{...g,...C,_lastUpdate:g._lastUpdate});i.set(d.id,fr(g,P,n))}else fr(g,{...g,_lastUpdate:g._lastUpdate},n)}else{const C=d.timestamp||n,P=g._lastUpdate||g.timestamp||0;if(C>=P){const b=(f=d.chats)!=null&&f.length?d.chats:g.chats,I=Ha(g.childSessions,d.childSessions),j=mn(g,d,{...g,...d,chats:b,childSessions:I,_lastUpdate:n});i.set(d.id,fr(g,j,n))}else(y=d.chats)!=null&&y.length&&!((k=g.chats)!=null&&k.length)&&i.set(d.id,{...g,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const g=d.daemonId||((T=d.id)==null?void 0:T.split(":")[0]);g&&l.add(g)}for(const[d,g]of i){const v=g.daemonId||d.split(":")[0];if(!l.has(v))continue;if(a.has(v)&&!c.has(d)){i.delete(d);continue}const h=n-(g._lastUpdate||g.timestamp||0);(g.transport==="pty"&&!c.has(d)&&h>1e4||g.transport==="acp"&&!c.has(d)&&h>1e4||g.transport==="cdp-page"&&!c.has(d)&&h>3e4)&&i.delete(d)}for(const[d,g]of i)n-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&i.delete(d);return Array.from(i.values())}function vl(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 wl({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((v,h)=>{n(C=>{let P=!1;const b=C.map(I=>I.id!==v||I.chats===h?I:(P=!0,{...I,chats:h}));return P?b:C})},[]),y=o.useCallback((v,h)=>{n(C=>{const P=C.length===0?v:yl(v,C,h),b=!vl(C,P);return b&&Ts.record({kind:"dashboard.entries_applied",payload:{incoming:Oa(v),next:Oa(P)}}),b?P:C})},[]),k=o.useCallback(()=>i(!0),[]),T=o.useMemo(()=>({injectEntries:y,markLoaded:k,getIdes:()=>m.current}),[y,k]),d=s,g=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(Yo.Provider,{value:T,children:t.jsx(qo.Provider,{value:g,children:e})})}function hs(){return o.useContext(qo)}function Wr(){return o.useContext(Yo)}function Xo(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),y=new AbortController,k=setTimeout(()=>y.abort(),15e3);try{const T=await fetch(f,{...u,headers:p,signal:y.signal});if(T.status===401)throw n==null||n(),new Error("Unauthorized");if(!T.ok){const d=await T.json().catch(()=>({error:T.statusText}));throw new Error(d.error||`API Error: ${T.status}`)}return T.json()}finally{clearTimeout(k)}}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 jl=Xo({baseUrl:"http://localhost:3847"}),kl=o.createContext(jl);function Sl({client:e,children:s}){return t.jsx(kl.Provider,{value:e,children:s})}const Nl={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Qo=o.createContext(Nl);function Cl({value:e,children:s}){return t.jsx(Qo.Provider,{value:e,children:s})}function Lt(){return o.useContext(Qo)}function Il(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 Al(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Jo(e){return e?Il([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Al(e.content)]):""}const Be={size:18};function Zo({size:e=Be.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 ra({size:e=Be.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 zt({size:e=Be.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 na({size:e=Be.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 Ml({size:e=Be.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 Tl({size:e=Be.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 ei({size:e=Be.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 Ll({size:e=Be.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 Qr({size:e=Be.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 ti({size:e=Be.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 _l({size:e=Be.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 Vt({size:e=Be.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 Tt({size:e=Be.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 aa({size:e=Be.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 Rl({size:e=Be.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 Ls({size:e=Be.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 Ws({size:e=Be.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 xs({size:e=Be.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 nr({size:e=Be.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 si({size:e=Be.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 ri({size:e=Be.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 ni({size:e=Be.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 Pl({size:e=Be.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 Jr({size:e=Be.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 Dl({size:e=Be.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 oa({size:e=Be.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 $l({size:e=Be.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 Nt({size:e=Be.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 El({size:e=Be.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 Kl({size:e=Be.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 Bl({size:e=Be.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 Wl({size:e=Be.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 Zr({size:e=Be.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 Ol({size:e=Be.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 Hl({size:e=Be.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 Ul({size:e=Be.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 Fl({size:e=Be.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 zl({size:e=Be.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 Vl({size:e=Be.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 Gl({size:e=Be.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 ql({size:e=Be.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 Yl({size:e=Be.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 Xl({size:e=Be.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 Ql({size:e=Be.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 Jl({size:e=Be.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 Fa(e){return!!e&&typeof e=="object"&&"text"in e}function ia(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:Fa(i)?String(i.text||""):"").join(r):Fa(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function _s(e){return ia(e,{normalizeWhitespace:!0})}const pn=new Map;function za(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Zl(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Jo(s)}`}function Va(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function ai(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ed(e,s,r){return Number(e.receivedAt||r[Ns(e,s)]||0)||0}function oi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function td(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function hr(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 fn(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 Ga(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):oi(e)?t.jsx(ea,{remarkPlugins:[ta,Vo,Go],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function xr({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:Ga(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=fn(r);return a?t.jsx("img",{src:a,alt:hr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=fn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=fn(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:hr(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||hr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=hr(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}),Ga(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 Ns(e,s){const r=e,n=ia(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 sd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ea,{remarkPlugins:[ta],children:s.text}),t.jsx("span",{className:"action-time",children:ai(s.timestamp)})]})},(e,s)=>e.log===s.log),rd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,w;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=td(s.content)?s.content:null,
|
|
4
|
-
`});if(m==="thought"){const x=typeof((I=s.meta)==null?void 0:I.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(Bl,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:k})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),y&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(xr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",$=typeof((w=s.meta)==null?void 0:w.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:$})]}),y&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(xr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:k})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:y&&f?t.jsx(xr,{parts:f,renderAsPreformatted:!1}):k.slice(0,100)});const T=s.meta,g=(typeof(T==null?void 0:T.renderMode)=="string"?T.renderMode.trim():"")==="preformatted",v=k,h=!1,C=v,P=g,b=!P&&oi(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(v||y||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${v||y?"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:ai(r)})]}),(v||y)&&t.jsx("div",{className:"chat-markdown",children:y&&f?t.jsx(xr,{parts:f,renderAsPreformatted:P}):P?t.jsx("pre",{className:"chat-preformatted",children:C}):b?t.jsx(ea,{remarkPlugins:[ta,Vo,Go],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),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),nd=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:y,hiddenLiveCount:k=0,loadError:T,scrollToBottomRequestNonce:d},g){const v=o.useRef(null),h=o.useRef(null),C=o.useRef(null),P=o.useRef(0),b=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(null),$=o.useRef(!1),[N,L]=o.useState(new Set),M=o.useRef(!1),B=o.useRef(!1),_=()=>{const te=v.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},S=o.useCallback((te="auto")=>{const ue=v.current;ue&&ue.scrollTo({top:ue.scrollHeight,behavior:te})},[]),O=o.useCallback(()=>{var pe;const te=v.current,ue=(pe=window.getSelection)==null?void 0:pe.call(window);if(!te||!ue||ue.rangeCount===0||ue.isCollapsed){$.current=!1;return}const Ne=ue.anchorNode,le=ue.focusNode;$.current=!!(Ne&&le&&te.contains(Ne)&&te.contains(le))},[]),G=Zl(s),A=o.useCallback(()=>{const te=v.current;!te||!l||pn.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight),messageFingerprint:G})},[l,G]),K=o.useCallback((te="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,S(te)})},[S]);o.useEffect(()=>{const te=!I.current,ue=b.current!==l;if(b.current=l,te||ue){if(I.current=!0,M.current=!1,w.current=!0,!$.current){const le=l?pn.get(l):null;le&&za(le,G)?requestAnimationFrame(()=>{const pe=v.current;pe&&(Va(pe,le),B.current=!0)}):K("auto")}P.current=s.length;return}s.length>P.current?!M.current&&!$.current&&K("auto"):_()&&!M.current&&!$.current&&K("auto"),P.current=s.length},[G,l,c,s.length,K]),o.useEffect(()=>{d&&(M.current=!1,w.current=!0,B.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{w.current=!1,x.current=null},180),$.current||K("auto"))},[K,d]),o.useEffect(()=>()=>{A(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[A]),o.useEffect(()=>{const te=h.current;if(!te)return;const ue=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{w.current=!1,x.current=null},180)},Ne=new ResizeObserver(()=>{w.current&&($.current||(K("auto"),ue()))});return Ne.observe(te),()=>{Ne.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[K,l]),o.useImperativeHandle(g,()=>({scrollToBottom:(te="smooth")=>{S(te)}}),[S]),o.useEffect(()=>{const te=v.current;if(!te)return;let ue;const Ne=()=>{clearTimeout(ue),ue=setTimeout(()=>{M.current=!_(),A()},50)};return te.addEventListener("scroll",Ne,{passive:!0}),()=>{te.removeEventListener("scroll",Ne),clearTimeout(ue)}},[A]),o.useEffect(()=>(document.addEventListener("selectionchange",O),()=>document.removeEventListener("selectionchange",O)),[O]);const V=o.useRef(0),U=o.useRef(!1);o.useEffect(()=>{const te=v.current;if(!te||!U.current||V.current===0)return;const ue=te.scrollHeight-V.current;ue>0&&(te.scrollTop=ue),A(),V.current=0,U.current=!1},[s.length,A]),o.useEffect(()=>{if(B.current||!l)return;const te=pn.get(l),ue=v.current;if(!(!te||!ue)){if(!za(te,G)){S("auto"),B.current=!0;return}Va(ue,te),B.current=!0}},[l,G,s.length,S]);const ce=()=>{const te=v.current;te&&(V.current=te.scrollHeight),U.current=!0,m==null||m()},Y=o.useMemo(()=>{const te=s.map((pe,ae)=>({type:"message",data:pe,index:ae,ts:ed(pe,ae,u)}));if(!r||r.length===0)return te;const ue=[...r].sort((pe,ae)=>pe.timestamp-ae.timestamp).map((pe,ae)=>({type:"action",data:pe,index:ae,ts:pe.timestamp})),Ne=[];let le=0;for(const pe of te){for(;le<ue.length&&pe.ts>0&&ue[le].ts<pe.ts;)Ne.push(ue[le++]);Ne.push(pe)}for(;le<ue.length;)Ne.push(ue[le++]);return Ne},[s,r,u]),oe=k>0||!!y,Q=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:T?`↻ ${T}`:"↑ Load older messages";return t.jsx("div",{ref:v,"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..."}),oe&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${T&&k===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:Q})}),Y.length===0&&!oe&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Y.map(te=>{if(te.type==="action"){const ve=te.data;return t.jsx(sd,{log:ve},`action-${te.index}`)}const ue=te.data,Ne=te.index,le=Ns(ue,Ne),pe=ue.receivedAt||u[le],ae=`${l}-${le}`,z=N.has(ae);return t.jsx(rd,{message:ue,receivedAt:pe,agentName:n,userName:a,isCliMode:i,isTextExpanded:z,onToggleTextExpanded:()=>L(ve=>{const ee=new Set(ve);return z?ee.delete(ae):ee.add(ae),ee})},`msg-${le}`)}),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:C})]})})}),ad=o.memo(nd,(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),od="modulepreload",id=function(e){return"/"+e},qa={},cd=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=id(u),u in qa)return;qa[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":od,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((y,k)=>{f.addEventListener("load",y),f.addEventListener("error",()=>k(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 Ya=!1;const ii=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),y=()=>{const k=i.current;if(k){p.current&&(k.clear(),p.current=!1);for(const T of u.current)k.write(T);u.current=[],m.current&&(k.fit(),m.current=!1),f.current&&(k.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:k=>{i.current?i.current.write(k):u.current.push(k)},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:(k,T)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(k,T)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const k=requestAnimationFrame(()=>{y()});return()=>cancelAnimationFrame(k)},[c]),o.useEffect(()=>{let k=!1;return cd(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(T=>{Ya||(Ya=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||l(()=>T.GhosttyTerminalView)}).catch(T=>{console.error("[CliTerminal] failed to load terminal renderer",T)}),()=>{k=!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"}})});ii.displayName="CliTerminal";function br({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 Xa({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 ld({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,y,k;u>p?(m=a.width,f=a.width/u,y=0,k=(a.height-f)/2):(f=a.height,m=a.height*u,y=(a.width-m)/2,k=0);const T=a.left-i.left+y+m*e.nx,d=a.top-i.top+k+f*e.ny,g=Math.max(8,Math.min(i.width-8,T)),v=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:g-8,top:v-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 dd({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:y,onZoomOut:k,onZoomReset:T,onZoomIn:d,transportType:g,screenshotUsage:v,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},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(C=>!C),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),"%"]}),g==="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"}),g==="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"}),v&&v.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),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:C=>C.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?y:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),k()},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:C=>{C.stopPropagation(),T()},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:C=>{C.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 ud({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 md(){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 Qa(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 cr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!md())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,Qa(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,Qa(s[c])]))}),r.current=s})}function pd({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:y,onAction:k,setLastActionStatus:T,spawnRippleFromNormalized:d,clampPan:g,isMobile:v,mobileFillZoom:h}){const[C,P]=o.useState(null),b=o.useRef(null),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(null),$=o.useRef(0),N=o.useRef(null),L=o.useRef(1),M=o.useRef({x:0,y:0}),B=o.useRef(!1),_=o.useRef(n),S=o.useRef(k),O=30,G=550,A=18,K=60,V=400,U=12,ce=()=>{if(b.current)return;const Q={nx:.5,ny:.5};b.current=Q,P(Q)};return o.useEffect(()=>{_.current=n,n==="mouse"&&ce()},[n]),o.useEffect(()=>{S.current=k},[k]),o.useEffect(()=>{const Q=e.current;if(!Q)return;const te=z=>{if(!r.current)return null;const ve=r.current.getBoundingClientRect();return!ve.width||!ve.height?null:{nx:Math.max(0,Math.min(1,(z.clientX-ve.left)/ve.width)),ny:Math.max(0,Math.min(1,(z.clientY-ve.top)/ve.height))}},ue=(z,ve)=>{if(!r.current)return{dnx:0,dny:0};const ee=r.current,we=ee.getBoundingClientRect(),re=ee.naturalWidth||we.width,ie=ee.naturalHeight||we.height,ne=re/ie,je=we.width/we.height;let xe,E;return ne>je?(xe=we.width,E=we.width/ne):(E=we.height,xe=we.height*ne),{dnx:z/xe,dny:ve/E}},Ne=(z,ve,ee)=>{if(ee<=1.05)return;const we=-(z-.5)*100,re=-(ve-.5)*100,ie=g(we,re,ee);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-u.current)>.1)&&(p(ie.x),m(ie.y),l.current=ie.x,u.current=ie.y)},le=z=>{const ve=s.current;if(ve&&z.target instanceof Node&&ve.contains(z.target))z.preventDefault();else return;if(z.touches.length===1){const ee=z.touches[0];I.current={x:ee.clientX,y:ee.clientY,time:Date.now()},j.current={x:ee.clientX,y:ee.clientY},B.current||(w.current=!1),x.current=setTimeout(()=>{if(!w.current&&!B.current)if(w.current=!0,_.current==="mouse"){const we=b.current||{nx:.5,ny:.5};T("Right Click"),d(we.nx,we.ny,"right"),S.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=te(ee);we&&(T("Right Click"),d(we.nx,we.ny,"right"),S.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(z.touches.length===2){x.current&&clearTimeout(x.current),w.current=!0,B.current=!0;const ee=z.touches[1].clientX-z.touches[0].clientX,we=z.touches[1].clientY-z.touches[0].clientY;N.current=Math.sqrt(ee*ee+we*we),L.current=c.current,M.current={x:(z.touches[0].clientX+z.touches[1].clientX)/2,y:(z.touches[0].clientY+z.touches[1].clientY)/2}}},pe=z=>{const ve=s.current;if(ve&&z.target instanceof Node&&ve.contains(z.target)&&z.preventDefault(),z.touches.length===1&&j.current){const ee=z.touches[0],we=ee.clientX-j.current.x,re=ee.clientY-j.current.y;if(!w.current&&I.current){const ie=ee.clientX-I.current.x,ne=ee.clientY-I.current.y;Math.sqrt(ie*ie+ne*ne)>8&&(w.current=!0,x.current&&clearTimeout(x.current))}if(w.current)if(_.current==="mouse"){const ie=ue(we,re),ne=b.current||{nx:.5,ny:.5},je=Math.max(0,Math.min(1,ne.nx+ie.dnx)),xe=Math.max(0,Math.min(1,ne.ny+ie.dny));b.current={nx:je,ny:xe},P({nx:je,ny:xe}),T(`Cursor: ${Math.round(je*100)}%, ${Math.round(xe*100)}%`),Ne(je,xe,c.current);const E=Date.now();E-y.current>=30&&(y.current=E,S.current("input_mouseMoved",{nx:je,ny:xe}).catch(()=>{}))}else if(c.current>1){const ie=s.current;if(ie){const ne=ie.clientWidth,je=ie.clientHeight,xe=l.current+we/ne*100,E=u.current+re/je*100,ke=g(xe,E,c.current);p(ke.x),m(ke.y),l.current=ke.x,u.current=ke.y}}else{const ie=te(ee);if(ie){const ne=Date.now();ne-y.current>=40&&(y.current=ne,T("Scroll"),S.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-re*2.5)}).catch(()=>{}))}}j.current={x:ee.clientX,y:ee.clientY};return}if(z.touches.length===2&&N.current!==null){const ee=z.touches[1].clientX-z.touches[0].clientX,we=z.touches[1].clientY-z.touches[0].clientY,ie=Math.sqrt(ee*ee+we*we)/N.current,ne=(z.touches[0].clientX+z.touches[1].clientX)/2,je=(z.touches[0].clientY+z.touches[1].clientY)/2,xe=ne-M.current.x,E=je-M.current.y,ke=Math.abs(ie-1)>.03;if(_.current==="mouse"){if(ke){const ge=Math.max(i,Math.min(5,L.current*ie));f(ge),c.current=ge}else if(Math.abs(xe)>2||Math.abs(E)>2){const ge=b.current||{nx:.5,ny:.5},Ce=Date.now();Ce-y.current>=30&&(y.current=Ce,T("Scroll"),S.current("input_wheel",{nx:ge.nx,ny:ge.ny,deltaX:Math.round(-xe*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const ge=Math.max(i,Math.min(5,L.current*ie));f(ge),c.current=ge;const Ce=s.current;if(Ce&&ge>1){const J=Ce.clientWidth,Me=Ce.clientHeight,He=l.current+xe/J*100,$e=u.current+E/Me*100,Ze=g(He,$e,ge);p(Ze.x),m(Ze.y),l.current=Ze.x,u.current=Ze.y}}M.current={x:ne,y:je}}},ae=z=>{var ve;if(x.current&&clearTimeout(x.current),N.current=null,z.touches.length===1&&B.current){const ee=z.touches[0];I.current={x:ee.clientX,y:ee.clientY,time:Date.now()},j.current={x:ee.clientX,y:ee.clientY},w.current=!0;return}if(z.touches.length===0){if(B.current){B.current=!1,w.current=!1;return}if(z.changedTouches.length===1){const ee=z.changedTouches[0],we=Date.now(),re=we-(((ve=I.current)==null?void 0:ve.time)||0),ie=I.current?ee.clientX-I.current.x:0,ne=I.current?ee.clientY-I.current.y:0,je=Math.sqrt(ie*ie+ne*ne);if(_.current==="mouse"){if(re<O||re>G||je>A){w.current=!1;return}const xe=b.current||te(ee);xe&&(T(`Click: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),d(xe.nx,xe.ny,"left"),S.current("input_click",{...xe}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(re<K||re>V||je>U){w.current=!1;return}const xe=te(ee);if(!xe)return;we-$.current<300?(T("Double tap"),d(xe.nx,xe.ny,"double"),S.current("input_click",{...xe,clickCount:2}).catch(()=>{}),$.current=0):(T(`Tap: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),d(xe.nx,xe.ny,"left"),S.current("input_click",{...xe}).catch(()=>{}),$.current=we)}}w.current=!1}};return Q.addEventListener("touchstart",le,{passive:!1}),Q.addEventListener("touchmove",pe,{passive:!1}),Q.addEventListener("touchend",ae,{passive:!1}),()=>{Q.removeEventListener("touchstart",le),Q.removeEventListener("touchmove",pe),Q.removeEventListener("touchend",ae),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,y,T,d,g]),{cursorPos:C,cursorPosRef:b,handleToggleInputMode:()=>{a(Q=>{const te=Q==="touch"?"mouse":"touch";return te==="mouse"&&ce(),te})},handleZoomReset:()=>{const Q=v?h:1;f(Q),c.current=Q,p(0),m(0),l.current=0,u.current=0}}}function ci({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,y]=o.useState(""),[,k]=o.useState(!1),[T,d]=o.useState([]),g=o.useRef(0),[v,h]=o.useState(!1),[C,P]=o.useState(!1),b=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(b?"mouse":"touch"),[w,x]=o.useState(1),$=o.useRef(!1),[N,L]=o.useState(1),[M,B]=o.useState(0),[_,S]=o.useState(0);cr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:N,panX:M,panY:_,isMenuOpen:v,isImeOpen:C});const O=o.useRef(0),G=o.useRef(N),A=o.useRef(M),K=o.useRef(_);o.useEffect(()=>{G.current=N},[N]),o.useEffect(()=>{A.current=M},[M]),o.useEffect(()=>{K.current=_},[_]),o.useEffect(()=>{var re;(re=c.current)==null||re.focus()},[]);const V=r==="connected",U=n,ce=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!b||$.current||!U)return;const re=u.current,ie=l.current;if(!re||!ie)return;const ne=()=>{const je=ie.clientWidth,xe=ie.clientHeight,E=re.naturalWidth,ke=re.naturalHeight;if(!E||!ke||!je||!xe)return;const ge=Math.min(je/E,xe/ke),J=Math.max(je/E,xe/ke)/ge;J>1.01&&(x(J),L(J),G.current=J),$.current=!0};re.complete&&re.naturalWidth?ne():re.addEventListener("load",ne,{once:!0})},[U,b]);const oe=.5;o.useEffect(()=>{N<=oe&&(B(0),S(0))},[N,oe]);const Q=(re,ie,ne)=>{if(ne<=oe)return{x:0,y:0};const je=(ne-1)/(2*ne)*100,xe=(ne-1)/(2*ne)*100;return{x:Math.max(-je,Math.min(je,re)),y:Math.max(-xe,Math.min(xe,ie))}},te=(re,ie)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(re-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(ie-ne.top)/ne.height))}},ue=(re,ie,ne)=>{const je=l.current;if(!je)return;const xe=je.getBoundingClientRect(),E=++g.current;d(ke=>[...ke,{id:E,x:re-xe.left,y:ie-xe.top,type:ne}]),setTimeout(()=>d(ke=>ke.filter(ge=>ge.id!==E)),600)},Ne=(re,ie,ne)=>{const je=u.current,xe=l.current;if(!je||!xe)return;const E=je.getBoundingClientRect(),ke=xe.getBoundingClientRect(),ge=je.naturalWidth||E.width,Ce=je.naturalHeight||E.height,J=ge/Ce,Me=E.width/E.height;let He,$e,Ze,Ge;J>Me?(He=E.width,$e=E.width/J,Ze=0,Ge=(E.height-$e)/2):($e=E.height,He=E.height*J,Ze=(E.width-He)/2,Ge=0);const Ye=E.left-ke.left+Ze+He*re,ot=E.top-ke.top+Ge+$e*ie,et=++g.current;d(mt=>[...mt,{id:et,x:Ye,y:ot,type:ne}]),setTimeout(()=>d(mt=>mt.filter(Ve=>Ve.id!==et)),600)},le=async re=>{var ne;const ie=te(re.clientX,re.clientY);if(ie){m(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),ue(re.clientX,re.clientY,"left"),(ne=c.current)==null||ne.focus();try{const je=await e("input_click",{nx:ie.nx,ny:ie.ny});je!=null&&je.success||s(`❌ Click failed: ${je==null?void 0:je.error}`)}catch(je){s(`❌ Click error: ${je.message||je}`)}}},pe=async(re,ie,ne,je=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:re,code:ie,text:ne?re:void 0,unmodifiedText:ne?re:void 0,modifiers:je})}catch(xe){s(`❌ Key error: ${xe.message||xe}`)}},ae=async re=>{if(re.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(re.key)&&re.preventDefault();let ne=0;re.altKey&&(ne|=1),re.ctrlKey&&(ne|=2),re.metaKey&&(ne|=4),re.shiftKey&&(ne|=8),m(`Key: ${re.key}`),await pe(re.key,re.code,re.key.length===1,ne)},z=async re=>{if(re.key==="Enter"){if(re.nativeEvent.isComposing)return;if(f){const ie=f;y(""),m(`IME Sent: ${ie}`);try{const ne=await e("input_type",{text:ie});ne!=null&&ne.success||s(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ IME error: ${ne.message}`)}}else m("Key: Enter"),await pe("Enter","Enter",!1)}};o.useEffect(()=>{const re=c.current;if(!re)return;const ie=ne=>{var je;if((je=u.current)!=null&&je.contains(ne.target)){ne.preventDefault();const xe=Date.now();if(xe-O.current<40)return;O.current=xe;const E=te(ne.clientX,ne.clientY);if(!E)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return re.addEventListener("wheel",ie,{passive:!1}),()=>re.removeEventListener("wheel",ie)},[e]);const{cursorPos:ve,handleToggleInputMode:ee,handleZoomReset:we}=pd({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:oe,zoomRef:G,panXRef:A,panYRef:K,setPanX:B,setPanY:S,setZoom:L,lastWheelTimeRef:O,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:Ne,clampPan:Q,isMobile:b,mobileFillZoom:w});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ae,onContextMenu:re=>re.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[U?t.jsx("img",{ref:u,src:U,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${N}) translate(${M}%, ${_}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:le,onContextMenu:re=>re.preventDefault(),onDragStart:re=>re.preventDefault()}):t.jsx(ud,{waitingLabel:ce,waitingHint:Y,transportType:i}),I==="mouse"&&U&&t.jsx(ld,{cursorPos:ve,viewportRef:l,imgRef:u}),T.map(re=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[re.type];return t.jsxs("div",{style:{position:"absolute",left:re.x,top:re.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},re.id)})]}),t.jsx(dd,{inputMode:I,onToggleInputMode:ee,isImeOpen:C,setIsImeOpen:P,isMenuOpen:v,setIsMenuOpen:h,imeText:f,setImeText:y,handleImeSubmit:z,isConnActive:V,zoom:N,isMobile:b,mobileFillZoom:w,onZoomOut:()=>L(re=>Math.max(.5,re-.25)),onZoomReset:we,onZoomIn:()=>L(re=>Math.min(5,re+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
|
|
2
|
+
var al=Object.defineProperty;var ol=(e,s,r)=>s in e?al(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var qe=(e,s,r)=>ol(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ea,a as ta,b as Vo,c as Go,u as Bs,R as nt,d as rr,t as il,e as cl,D as ll,f as Bn,g as Wn,h as sa,i as dl,k as ul,B as ml,l as pl,m as ss,N as On,n as fl}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 hl(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 Ts=hl();function Oa(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}}function xl(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function bl(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 Xs(e,s){const r=xl(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??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)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:bl(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),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Ha(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?Xs(n,a):n})}const qo=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}),Yo=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ua(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 mn(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 Br(e){return Array.isArray(e)?e.map(Br):!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,Br(r)]))}function gl(e,s){try{return JSON.stringify(Br(e))===JSON.stringify(Br(s))}catch{return!1}}function fr(e,s,r){return gl(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function yl(e,s,r){var u,p,m,f,b,k,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 y=i.get(d.id);if(!y){i.set(d.id,{...d,_lastUpdate:n});continue}const v=Ua(d),h=Ua(y);if(v>h){const C=(u=d.chats)!=null&&u.length?d.chats:y.chats,P=Ha(y.childSessions,d.childSessions),g=mn(y,d,{...y,...d,chats:C,childSessions:P,_lastUpdate:n});i.set(d.id,fr(y,g,n))}else if(v<h){const C={};if(d.status&&d.status!==y.status&&(C.status=d.status),d.cdpConnected!==void 0&&(C.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=y.chats)!=null&&m.length)&&(C.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==y.machineNickname&&(C.machineNickname=d.machineNickname),d.version!==void 0&&(C.version=d.version),d.serverVersion!==void 0&&(C.serverVersion=d.serverVersion),d.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const P=mn(y,d,{...y,...C,_lastUpdate:y._lastUpdate});i.set(d.id,fr(y,P,n))}else fr(y,{...y,_lastUpdate:y._lastUpdate},n)}else{const C=d.timestamp||n,P=y._lastUpdate||y.timestamp||0;if(C>=P){const g=(f=d.chats)!=null&&f.length?d.chats:y.chats,I=Ha(y.childSessions,d.childSessions),j=mn(y,d,{...y,...d,chats:g,childSessions:I,_lastUpdate:n});i.set(d.id,fr(y,j,n))}else(b=d.chats)!=null&&b.length&&!((k=y.chats)!=null&&k.length)&&i.set(d.id,{...y,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const y=d.daemonId||((L=d.id)==null?void 0:L.split(":")[0]);y&&l.add(y)}for(const[d,y]of i){const v=y.daemonId||d.split(":")[0];if(!l.has(v))continue;if(a.has(v)&&!c.has(d)){i.delete(d);continue}const h=n-(y._lastUpdate||y.timestamp||0);(y.transport==="pty"&&!c.has(d)&&h>1e4||y.transport==="acp"&&!c.has(d)&&h>1e4||y.transport==="cdp-page"&&!c.has(d)&&h>3e4)&&i.delete(d)}for(const[d,y]of i)n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&i.delete(d);return Array.from(i.values())}function vl(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 wl({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((v,h)=>{n(C=>{let P=!1;const g=C.map(I=>I.id!==v||I.chats===h?I:(P=!0,{...I,chats:h}));return P?g:C})},[]),b=o.useCallback((v,h)=>{n(C=>{const P=C.length===0?v:yl(v,C,h),g=!vl(C,P);return g&&Ts.record({kind:"dashboard.entries_applied",payload:{incoming:Oa(v),next:Oa(P)}}),g?P:C})},[]),k=o.useCallback(()=>i(!0),[]),L=o.useMemo(()=>({injectEntries:b,markLoaded:k,getIdes:()=>m.current}),[b,k]),d=s,y=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(Yo.Provider,{value:L,children:t.jsx(qo.Provider,{value:y,children:e})})}function hs(){return o.useContext(qo)}function Wr(){return o.useContext(Yo)}function Xo(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),b=new AbortController,k=setTimeout(()=>b.abort(),15e3);try{const L=await fetch(f,{...u,headers:p,signal:b.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(k)}}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 jl=Xo({baseUrl:"http://localhost:3847"}),kl=o.createContext(jl);function Sl({client:e,children:s}){return t.jsx(kl.Provider,{value:e,children:s})}const Nl={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Qo=o.createContext(Nl);function Cl({value:e,children:s}){return t.jsx(Qo.Provider,{value:e,children:s})}function Lt(){return o.useContext(Qo)}function Il(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 Al(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Jo(e){return e?Il([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Al(e.content)]):""}const Be={size:18};function Zo({size:e=Be.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 ra({size:e=Be.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 zt({size:e=Be.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 na({size:e=Be.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 Ml({size:e=Be.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 Tl({size:e=Be.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 ei({size:e=Be.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 Ll({size:e=Be.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 Qr({size:e=Be.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 ti({size:e=Be.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 _l({size:e=Be.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 Vt({size:e=Be.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 Tt({size:e=Be.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 aa({size:e=Be.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 Rl({size:e=Be.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 Ls({size:e=Be.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 Ws({size:e=Be.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 xs({size:e=Be.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 nr({size:e=Be.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 si({size:e=Be.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 ri({size:e=Be.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 ni({size:e=Be.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 Pl({size:e=Be.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 Jr({size:e=Be.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 Dl({size:e=Be.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 oa({size:e=Be.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 $l({size:e=Be.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 Nt({size:e=Be.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 El({size:e=Be.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 Kl({size:e=Be.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 Bl({size:e=Be.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 Wl({size:e=Be.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 Zr({size:e=Be.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 Ol({size:e=Be.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 Hl({size:e=Be.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 Ul({size:e=Be.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 Fl({size:e=Be.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 zl({size:e=Be.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 Vl({size:e=Be.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 Gl({size:e=Be.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 ql({size:e=Be.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 Yl({size:e=Be.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 Xl({size:e=Be.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 Ql({size:e=Be.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 Jl({size:e=Be.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 Fa(e){return!!e&&typeof e=="object"&&"text"in e}function ia(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:Fa(i)?String(i.text||""):"").join(r):Fa(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function _s(e){return ia(e,{normalizeWhitespace:!0})}const pn=new Map;function za(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Zl(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Jo(s)}`}function Va(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function ai(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ed(e,s,r){return Number(e.receivedAt||r[Ns(e,s)]||0)||0}function oi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function td(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function hr(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 fn(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 Ga(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):oi(e)?t.jsx(ea,{remarkPlugins:[ta,Vo,Go],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function xr({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:Ga(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=fn(r);return a?t.jsx("img",{src:a,alt:hr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=fn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=fn(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:hr(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||hr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=hr(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}),Ga(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 Ns(e,s){const r=e,n=ia(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 sd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ea,{remarkPlugins:[ta],children:s.text}),t.jsx("span",{className:"action-time",children:ai(s.timestamp)})]})},(e,s)=>e.log===s.log),rd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,w;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=td(s.content)?s.content:null,b=!!(f!=null&&f.some(x=>x.type!=="text")),k=ia(s.content,{joiner:`
|
|
4
|
+
`});if(m==="thought"){const x=typeof((I=s.meta)==null?void 0:I.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(Bl,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:k})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),b&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(xr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",$=typeof((w=s.meta)==null?void 0:w.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:$})]}),b&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(xr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:k})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:b&&f?t.jsx(xr,{parts:f,renderAsPreformatted:!1}):k.slice(0,100)});const L=s.meta,y=(typeof(L==null?void 0:L.renderMode)=="string"?L.renderMode.trim():"")==="preformatted",v=k,h=!1,C=v,P=y,g=!P&&oi(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(v||b||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${v||b?"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:ai(r)})]}),(v||b)&&t.jsx("div",{className:"chat-markdown",children:b&&f?t.jsx(xr,{parts:f,renderAsPreformatted:P}):P?t.jsx("pre",{className:"chat-preformatted",children:C}):g?t.jsx(ea,{remarkPlugins:[ta,Vo,Go],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),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),nd=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:b,hiddenLiveCount:k=0,loadError:L,scrollToBottomRequestNonce:d},y){const v=o.useRef(null),h=o.useRef(null),C=o.useRef(null),P=o.useRef(0),g=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(null),$=o.useRef(!1),[N,T]=o.useState(new Set),M=o.useRef(!1),B=o.useRef(!1),_=()=>{const te=v.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},S=o.useCallback((te="auto")=>{const ue=v.current;ue&&ue.scrollTo({top:ue.scrollHeight,behavior:te})},[]),O=o.useCallback(()=>{var pe;const te=v.current,ue=(pe=window.getSelection)==null?void 0:pe.call(window);if(!te||!ue||ue.rangeCount===0||ue.isCollapsed){$.current=!1;return}const Ne=ue.anchorNode,le=ue.focusNode;$.current=!!(Ne&&le&&te.contains(Ne)&&te.contains(le))},[]),G=Zl(s),A=o.useCallback(()=>{const te=v.current;!te||!l||pn.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight),messageFingerprint:G})},[l,G]),K=o.useCallback((te="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,S(te)})},[S]);o.useEffect(()=>{const te=!I.current,ue=g.current!==l;if(g.current=l,te||ue){if(I.current=!0,M.current=!1,w.current=!0,!$.current){const le=l?pn.get(l):null;le&&za(le,G)?requestAnimationFrame(()=>{const pe=v.current;pe&&(Va(pe,le),B.current=!0)}):K("auto")}P.current=s.length;return}s.length>P.current?!M.current&&!$.current&&K("auto"):_()&&!M.current&&!$.current&&K("auto"),P.current=s.length},[G,l,c,s.length,K]),o.useEffect(()=>{d&&(M.current=!1,w.current=!0,B.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{w.current=!1,x.current=null},180),$.current||K("auto"))},[K,d]),o.useEffect(()=>()=>{A(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[A]),o.useEffect(()=>{const te=h.current;if(!te)return;const ue=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{w.current=!1,x.current=null},180)},Ne=new ResizeObserver(()=>{w.current&&($.current||(K("auto"),ue()))});return Ne.observe(te),()=>{Ne.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[K,l]),o.useImperativeHandle(y,()=>({scrollToBottom:(te="smooth")=>{S(te)}}),[S]),o.useEffect(()=>{const te=v.current;if(!te)return;let ue;const Ne=()=>{clearTimeout(ue),ue=setTimeout(()=>{M.current=!_(),A()},50)};return te.addEventListener("scroll",Ne,{passive:!0}),()=>{te.removeEventListener("scroll",Ne),clearTimeout(ue)}},[A]),o.useEffect(()=>(document.addEventListener("selectionchange",O),()=>document.removeEventListener("selectionchange",O)),[O]);const V=o.useRef(0),U=o.useRef(!1);o.useEffect(()=>{const te=v.current;if(!te||!U.current||V.current===0)return;const ue=te.scrollHeight-V.current;ue>0&&(te.scrollTop=ue),A(),V.current=0,U.current=!1},[s.length,A]),o.useEffect(()=>{if(B.current||!l)return;const te=pn.get(l),ue=v.current;if(!(!te||!ue)){if(!za(te,G)){S("auto"),B.current=!0;return}Va(ue,te),B.current=!0}},[l,G,s.length,S]);const ce=()=>{const te=v.current;te&&(V.current=te.scrollHeight),U.current=!0,m==null||m()},Y=o.useMemo(()=>{const te=s.map((pe,ae)=>({type:"message",data:pe,index:ae,ts:ed(pe,ae,u)}));if(!r||r.length===0)return te;const ue=[...r].sort((pe,ae)=>pe.timestamp-ae.timestamp).map((pe,ae)=>({type:"action",data:pe,index:ae,ts:pe.timestamp})),Ne=[];let le=0;for(const pe of te){for(;le<ue.length&&pe.ts>0&&ue[le].ts<pe.ts;)Ne.push(ue[le++]);Ne.push(pe)}for(;le<ue.length;)Ne.push(ue[le++]);return Ne},[s,r,u]),oe=k>0||!!b,Q=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:L?`↻ ${L}`:"↑ Load older messages";return t.jsx("div",{ref:v,"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..."}),oe&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${L&&k===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:Q})}),Y.length===0&&!oe&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Y.map(te=>{if(te.type==="action"){const ve=te.data;return t.jsx(sd,{log:ve},`action-${te.index}`)}const ue=te.data,Ne=te.index,le=Ns(ue,Ne),pe=ue.receivedAt||u[le],ae=`${l}-${le}`,z=N.has(ae);return t.jsx(rd,{message:ue,receivedAt:pe,agentName:n,userName:a,isCliMode:i,isTextExpanded:z,onToggleTextExpanded:()=>T(ve=>{const ee=new Set(ve);return z?ee.delete(ae):ee.add(ae),ee})},`msg-${le}`)}),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:C})]})})}),ad=o.memo(nd,(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),od="modulepreload",id=function(e){return"/"+e},qa={},cd=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=id(u),u in qa)return;qa[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":od,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((b,k)=>{f.addEventListener("load",b),f.addEventListener("error",()=>k(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 Ya=!1;const ii=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1},n)=>{const a=o.useRef(null),[i,c]=o.useState(null),l=o.useRef([]),u=o.useRef(!1),p=o.useRef(!1),m=o.useRef(!1),f=()=>{const b=a.current;if(b){u.current&&(b.clear(),u.current=!1);for(const k of l.current)b.write(k);l.current=[],p.current&&(b.fit(),p.current=!1),m.current&&(b.bumpResize(),m.current=!1)}};return o.useImperativeHandle(n,()=>({write:b=>{a.current?a.current.write(b):l.current.push(b)},clear:()=>{a.current?a.current.clear():(l.current=[],u.current=!0)},reset:()=>{a.current&&typeof a.current.reset=="function"?a.current.reset():(l.current=[],u.current=!0)},resize:(b,k)=>{a.current&&typeof a.current.resize=="function"&&a.current.resize(b,k)},fit:()=>{a.current?a.current.fit():p.current=!0},bumpResize:()=>{a.current?a.current.bumpResize():m.current=!0}}),[]),o.useEffect(()=>{if(!i)return;const b=requestAnimationFrame(()=>{f()});return()=>cancelAnimationFrame(b)},[i]),o.useEffect(()=>{let b=!1;return cd(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(k=>{Ya||(Ya=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||c(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{b=!0}},[]),i?t.jsx(i,{ref:a,onInput:e,fontSize:s,readOnly:r,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"}})});ii.displayName="CliTerminal";function br({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 Xa({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 ld({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,b,k;u>p?(m=a.width,f=a.width/u,b=0,k=(a.height-f)/2):(f=a.height,m=a.height*u,b=(a.width-m)/2,k=0);const L=a.left-i.left+b+m*e.nx,d=a.top-i.top+k+f*e.ny,y=Math.max(8,Math.min(i.width-8,L)),v=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:y-8,top:v-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 dd({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:b,onZoomOut:k,onZoomReset:L,onZoomIn:d,transportType:y,screenshotUsage:v,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.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(C=>!C),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:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},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(C=>!C),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),"%"]}),y==="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"}),y==="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"}),v&&v.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),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:C=>C.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?b:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),k()},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:C=>{C.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:C=>{C.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 ud({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 md(){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 Qa(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 cr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!md())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,Qa(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,Qa(s[c])]))}),r.current=s})}function pd({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:b,onAction:k,setLastActionStatus:L,spawnRippleFromNormalized:d,clampPan:y,isMobile:v,mobileFillZoom:h}){const[C,P]=o.useState(null),g=o.useRef(null),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(null),$=o.useRef(0),N=o.useRef(null),T=o.useRef(1),M=o.useRef({x:0,y:0}),B=o.useRef(!1),_=o.useRef(n),S=o.useRef(k),O=30,G=550,A=18,K=60,V=400,U=12,ce=()=>{if(g.current)return;const Q={nx:.5,ny:.5};g.current=Q,P(Q)};return o.useEffect(()=>{_.current=n,n==="mouse"&&ce()},[n]),o.useEffect(()=>{S.current=k},[k]),o.useEffect(()=>{const Q=e.current;if(!Q)return;const te=z=>{if(!r.current)return null;const ve=r.current.getBoundingClientRect();return!ve.width||!ve.height?null:{nx:Math.max(0,Math.min(1,(z.clientX-ve.left)/ve.width)),ny:Math.max(0,Math.min(1,(z.clientY-ve.top)/ve.height))}},ue=(z,ve)=>{if(!r.current)return{dnx:0,dny:0};const ee=r.current,we=ee.getBoundingClientRect(),re=ee.naturalWidth||we.width,ie=ee.naturalHeight||we.height,ne=re/ie,je=we.width/we.height;let xe,E;return ne>je?(xe=we.width,E=we.width/ne):(E=we.height,xe=we.height*ne),{dnx:z/xe,dny:ve/E}},Ne=(z,ve,ee)=>{if(ee<=1.05)return;const we=-(z-.5)*100,re=-(ve-.5)*100,ie=y(we,re,ee);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-u.current)>.1)&&(p(ie.x),m(ie.y),l.current=ie.x,u.current=ie.y)},le=z=>{const ve=s.current;if(ve&&z.target instanceof Node&&ve.contains(z.target))z.preventDefault();else return;if(z.touches.length===1){const ee=z.touches[0];I.current={x:ee.clientX,y:ee.clientY,time:Date.now()},j.current={x:ee.clientX,y:ee.clientY},B.current||(w.current=!1),x.current=setTimeout(()=>{if(!w.current&&!B.current)if(w.current=!0,_.current==="mouse"){const we=g.current||{nx:.5,ny:.5};L("Right Click"),d(we.nx,we.ny,"right"),S.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=te(ee);we&&(L("Right Click"),d(we.nx,we.ny,"right"),S.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(z.touches.length===2){x.current&&clearTimeout(x.current),w.current=!0,B.current=!0;const ee=z.touches[1].clientX-z.touches[0].clientX,we=z.touches[1].clientY-z.touches[0].clientY;N.current=Math.sqrt(ee*ee+we*we),T.current=c.current,M.current={x:(z.touches[0].clientX+z.touches[1].clientX)/2,y:(z.touches[0].clientY+z.touches[1].clientY)/2}}},pe=z=>{const ve=s.current;if(ve&&z.target instanceof Node&&ve.contains(z.target)&&z.preventDefault(),z.touches.length===1&&j.current){const ee=z.touches[0],we=ee.clientX-j.current.x,re=ee.clientY-j.current.y;if(!w.current&&I.current){const ie=ee.clientX-I.current.x,ne=ee.clientY-I.current.y;Math.sqrt(ie*ie+ne*ne)>8&&(w.current=!0,x.current&&clearTimeout(x.current))}if(w.current)if(_.current==="mouse"){const ie=ue(we,re),ne=g.current||{nx:.5,ny:.5},je=Math.max(0,Math.min(1,ne.nx+ie.dnx)),xe=Math.max(0,Math.min(1,ne.ny+ie.dny));g.current={nx:je,ny:xe},P({nx:je,ny:xe}),L(`Cursor: ${Math.round(je*100)}%, ${Math.round(xe*100)}%`),Ne(je,xe,c.current);const E=Date.now();E-b.current>=30&&(b.current=E,S.current("input_mouseMoved",{nx:je,ny:xe}).catch(()=>{}))}else if(c.current>1){const ie=s.current;if(ie){const ne=ie.clientWidth,je=ie.clientHeight,xe=l.current+we/ne*100,E=u.current+re/je*100,ke=y(xe,E,c.current);p(ke.x),m(ke.y),l.current=ke.x,u.current=ke.y}}else{const ie=te(ee);if(ie){const ne=Date.now();ne-b.current>=40&&(b.current=ne,L("Scroll"),S.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-re*2.5)}).catch(()=>{}))}}j.current={x:ee.clientX,y:ee.clientY};return}if(z.touches.length===2&&N.current!==null){const ee=z.touches[1].clientX-z.touches[0].clientX,we=z.touches[1].clientY-z.touches[0].clientY,ie=Math.sqrt(ee*ee+we*we)/N.current,ne=(z.touches[0].clientX+z.touches[1].clientX)/2,je=(z.touches[0].clientY+z.touches[1].clientY)/2,xe=ne-M.current.x,E=je-M.current.y,ke=Math.abs(ie-1)>.03;if(_.current==="mouse"){if(ke){const ge=Math.max(i,Math.min(5,T.current*ie));f(ge),c.current=ge}else if(Math.abs(xe)>2||Math.abs(E)>2){const ge=g.current||{nx:.5,ny:.5},Ce=Date.now();Ce-b.current>=30&&(b.current=Ce,L("Scroll"),S.current("input_wheel",{nx:ge.nx,ny:ge.ny,deltaX:Math.round(-xe*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const ge=Math.max(i,Math.min(5,T.current*ie));f(ge),c.current=ge;const Ce=s.current;if(Ce&&ge>1){const J=Ce.clientWidth,Me=Ce.clientHeight,He=l.current+xe/J*100,$e=u.current+E/Me*100,Ze=y(He,$e,ge);p(Ze.x),m(Ze.y),l.current=Ze.x,u.current=Ze.y}}M.current={x:ne,y:je}}},ae=z=>{var ve;if(x.current&&clearTimeout(x.current),N.current=null,z.touches.length===1&&B.current){const ee=z.touches[0];I.current={x:ee.clientX,y:ee.clientY,time:Date.now()},j.current={x:ee.clientX,y:ee.clientY},w.current=!0;return}if(z.touches.length===0){if(B.current){B.current=!1,w.current=!1;return}if(z.changedTouches.length===1){const ee=z.changedTouches[0],we=Date.now(),re=we-(((ve=I.current)==null?void 0:ve.time)||0),ie=I.current?ee.clientX-I.current.x:0,ne=I.current?ee.clientY-I.current.y:0,je=Math.sqrt(ie*ie+ne*ne);if(_.current==="mouse"){if(re<O||re>G||je>A){w.current=!1;return}const xe=g.current||te(ee);xe&&(L(`Click: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),d(xe.nx,xe.ny,"left"),S.current("input_click",{...xe}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(re<K||re>V||je>U){w.current=!1;return}const xe=te(ee);if(!xe)return;we-$.current<300?(L("Double tap"),d(xe.nx,xe.ny,"double"),S.current("input_click",{...xe,clickCount:2}).catch(()=>{}),$.current=0):(L(`Tap: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),d(xe.nx,xe.ny,"left"),S.current("input_click",{...xe}).catch(()=>{}),$.current=we)}}w.current=!1}};return Q.addEventListener("touchstart",le,{passive:!1}),Q.addEventListener("touchmove",pe,{passive:!1}),Q.addEventListener("touchend",ae,{passive:!1}),()=>{Q.removeEventListener("touchstart",le),Q.removeEventListener("touchmove",pe),Q.removeEventListener("touchend",ae),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,b,L,d,y]),{cursorPos:C,cursorPosRef:g,handleToggleInputMode:()=>{a(Q=>{const te=Q==="touch"?"mouse":"touch";return te==="mouse"&&ce(),te})},handleZoomReset:()=>{const Q=v?h:1;f(Q),c.current=Q,p(0),m(0),l.current=0,u.current=0}}}function ci({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,b]=o.useState(""),[,k]=o.useState(!1),[L,d]=o.useState([]),y=o.useRef(0),[v,h]=o.useState(!1),[C,P]=o.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(g?"mouse":"touch"),[w,x]=o.useState(1),$=o.useRef(!1),[N,T]=o.useState(1),[M,B]=o.useState(0),[_,S]=o.useState(0);cr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:N,panX:M,panY:_,isMenuOpen:v,isImeOpen:C});const O=o.useRef(0),G=o.useRef(N),A=o.useRef(M),K=o.useRef(_);o.useEffect(()=>{G.current=N},[N]),o.useEffect(()=>{A.current=M},[M]),o.useEffect(()=>{K.current=_},[_]),o.useEffect(()=>{var re;(re=c.current)==null||re.focus()},[]);const V=r==="connected",U=n,ce=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!g||$.current||!U)return;const re=u.current,ie=l.current;if(!re||!ie)return;const ne=()=>{const je=ie.clientWidth,xe=ie.clientHeight,E=re.naturalWidth,ke=re.naturalHeight;if(!E||!ke||!je||!xe)return;const ge=Math.min(je/E,xe/ke),J=Math.max(je/E,xe/ke)/ge;J>1.01&&(x(J),T(J),G.current=J),$.current=!0};re.complete&&re.naturalWidth?ne():re.addEventListener("load",ne,{once:!0})},[U,g]);const oe=.5;o.useEffect(()=>{N<=oe&&(B(0),S(0))},[N,oe]);const Q=(re,ie,ne)=>{if(ne<=oe)return{x:0,y:0};const je=(ne-1)/(2*ne)*100,xe=(ne-1)/(2*ne)*100;return{x:Math.max(-je,Math.min(je,re)),y:Math.max(-xe,Math.min(xe,ie))}},te=(re,ie)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(re-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(ie-ne.top)/ne.height))}},ue=(re,ie,ne)=>{const je=l.current;if(!je)return;const xe=je.getBoundingClientRect(),E=++y.current;d(ke=>[...ke,{id:E,x:re-xe.left,y:ie-xe.top,type:ne}]),setTimeout(()=>d(ke=>ke.filter(ge=>ge.id!==E)),600)},Ne=(re,ie,ne)=>{const je=u.current,xe=l.current;if(!je||!xe)return;const E=je.getBoundingClientRect(),ke=xe.getBoundingClientRect(),ge=je.naturalWidth||E.width,Ce=je.naturalHeight||E.height,J=ge/Ce,Me=E.width/E.height;let He,$e,Ze,Ge;J>Me?(He=E.width,$e=E.width/J,Ze=0,Ge=(E.height-$e)/2):($e=E.height,He=E.height*J,Ze=(E.width-He)/2,Ge=0);const Ye=E.left-ke.left+Ze+He*re,ot=E.top-ke.top+Ge+$e*ie,et=++y.current;d(mt=>[...mt,{id:et,x:Ye,y:ot,type:ne}]),setTimeout(()=>d(mt=>mt.filter(Ve=>Ve.id!==et)),600)},le=async re=>{var ne;const ie=te(re.clientX,re.clientY);if(ie){m(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),ue(re.clientX,re.clientY,"left"),(ne=c.current)==null||ne.focus();try{const je=await e("input_click",{nx:ie.nx,ny:ie.ny});je!=null&&je.success||s(`❌ Click failed: ${je==null?void 0:je.error}`)}catch(je){s(`❌ Click error: ${je.message||je}`)}}},pe=async(re,ie,ne,je=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:re,code:ie,text:ne?re:void 0,unmodifiedText:ne?re:void 0,modifiers:je})}catch(xe){s(`❌ Key error: ${xe.message||xe}`)}},ae=async re=>{if(re.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(re.key)&&re.preventDefault();let ne=0;re.altKey&&(ne|=1),re.ctrlKey&&(ne|=2),re.metaKey&&(ne|=4),re.shiftKey&&(ne|=8),m(`Key: ${re.key}`),await pe(re.key,re.code,re.key.length===1,ne)},z=async re=>{if(re.key==="Enter"){if(re.nativeEvent.isComposing)return;if(f){const ie=f;b(""),m(`IME Sent: ${ie}`);try{const ne=await e("input_type",{text:ie});ne!=null&&ne.success||s(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ IME error: ${ne.message}`)}}else m("Key: Enter"),await pe("Enter","Enter",!1)}};o.useEffect(()=>{const re=c.current;if(!re)return;const ie=ne=>{var je;if((je=u.current)!=null&&je.contains(ne.target)){ne.preventDefault();const xe=Date.now();if(xe-O.current<40)return;O.current=xe;const E=te(ne.clientX,ne.clientY);if(!E)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return re.addEventListener("wheel",ie,{passive:!1}),()=>re.removeEventListener("wheel",ie)},[e]);const{cursorPos:ve,handleToggleInputMode:ee,handleZoomReset:we}=pd({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:oe,zoomRef:G,panXRef:A,panYRef:K,setPanX:B,setPanY:S,setZoom:T,lastWheelTimeRef:O,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:Ne,clampPan:Q,isMobile:g,mobileFillZoom:w});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ae,onContextMenu:re=>re.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[U?t.jsx("img",{ref:u,src:U,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${N}) translate(${M}%, ${_}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:le,onContextMenu:re=>re.preventDefault(),onDragStart:re=>re.preventDefault()}):t.jsx(ud,{waitingLabel:ce,waitingHint:Y,transportType:i}),I==="mouse"&&U&&t.jsx(ld,{cursorPos:ve,viewportRef:l,imgRef:u}),L.map(re=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[re.type];return t.jsxs("div",{style:{position:"absolute",left:re.x,top:re.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},re.id)})]}),t.jsx(dd,{inputMode:I,onToggleInputMode:ee,isImeOpen:C,setIsImeOpen:P,isMenuOpen:v,setIsMenuOpen:h,imeText:f,setImeText:b,handleImeSubmit:z,isConnActive:V,zoom:N,isMobile:g,mobileFillZoom:w,onZoomOut:()=>T(re=>Math.max(.5,re-.25)),onZoomReset:we,onZoomIn:()=>T(re=>Math.min(5,re+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
|
|
5
5
|
@keyframes slideUp {
|
|
6
6
|
from { opacity: 0; transform: translateY(6px); }
|
|
7
7
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -24,12 +24,12 @@ var al=Object.defineProperty;var ol=(e,s,r)=>s in e?al(e,s,{enumerable:!0,config
|
|
|
24
24
|
50% { transform: translateY(-7px); }
|
|
25
25
|
100% { transform: translateY(0px); }
|
|
26
26
|
}
|
|
27
|
-
`})]})}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,s){const r=kt(s);return r?`${e}:${r}`:void 0}function Xt(e,s,r){const n=Ft(s,r),a=kt(r);n&&e.push(n),a&&e.push(a)}function Cs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function li(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function ca(e){return Cs([kt(e.providerSessionId),kt(e.sessionId)])}function os(e){const s=[];return Xt(s,"provider",e.providerSessionId),Xt(s,"session",e.sessionId),Xt(s,"tab",e.tabKey),Xt(s,"route",e.routeId),Cs(s)}function fd(e){const s=[];return kt(e.providerSessionId)?(Xt(s,"provider",e.providerSessionId),Cs(s)):kt(e.sessionId)?(Xt(s,"session",e.sessionId),Cs(s)):kt(e.tabKey)?(Xt(s,"tab",e.tabKey),Cs(s)):kt(e.routeId)?(Xt(s,"route",e.routeId),Cs(s)):[]}function di(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function lr(e){return ca(e)[0]}function ui(e){const s=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),i=[Ft("provider",s),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(u=>typeof u=="string"),c=os({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=di({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:li({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:lr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Or(e,s){const r=ui(e);return fd(s).some(n=>r.lookupKeys.includes(n))}function en(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 mi=e=>en(e);function hd(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Os(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 tn(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...hd(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 Hr(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 la(e,s,r){const n=Hr(e,s),a=Os(e),i=os(e).map(T=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(T)}).find(T=>!!T),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,k=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:k,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":k?"task_complete":"idle"}}function xd(e,s,r){return la(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function pi({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Os(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(xs,{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),y=r===l,k=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:k,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"} ${k&&!y?"opacity-40":"opacity-100"} ${k?"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:y?"⏳ ...":c(l)},u)})})]})]})}var bd=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function gd(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if(gd(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":bd.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 fi(e){return jt(e)==="generating"}function at(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function yd(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 hn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function sn(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 vd(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 wd(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function jd(e){return vd(e.trim().replace(/\.local$/i,""))}function kd(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function hi(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&&!wd(c));if(r&&r!=="Unknown")return jd(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Mt(e,s={}){return kd(e)||hi(e,s)}function xi(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 bi(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 bs(e,s){return xi(e).join(" · ")}function ar(e){return e.transport==="pty"}function Is(e){return e.transport==="acp"}function Sd(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:at(e)}function Ja(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Nd(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Cd(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 Id(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 Ad(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&&Id(s.receivedAt)||0}function Md(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Hn(e){return Math.max(Md(e),Ad(e.activeChat))}function Td(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 da(e,s){return Td(Hn(e),Hn(s),Mt(e,{fallbackId:e.id}),Mt(s,{fallbackId:s.id}),e.id,s.id)}const gi="adhdev_notification_prefs",Za={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ld(){try{const e=localStorage.getItem(gi);if(e){const s=JSON.parse(e);return{...Za,...s}}}catch{}return{...Za}}function _d(e){try{localStorage.setItem(gi,JSON.stringify(e))}catch{}}let Ut=Ld(),_r=[];function Rd(){_r.forEach(e=>e())}function Pd(e){Ut={...Ut,...e},_d(Ut),Rd()}function Dd(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return _r.push(r),()=>{_r=_r.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Pd(r)},[]);return[{...Ut},s]}function Js(e){if(!Ut.globalEnabled)return!1;switch(e){case"disconnect":return Ut.disconnectAlert;case"completion":return Ut.completionAlert;case"approval":return Ut.approvalAlert;case"browser":return Ut.browserNotifications;default:return!0}}const $d={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ed(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function yi(){return"Notification"in window&&Notification.permission==="granted"}let rs=null;async function Kd(){if(rs!==null)return rs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return rs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(rs=!!await e.pushManager.getSubscription(),rs):(rs=!1,!1)}catch{return rs=!1,!1}}function Un(e,s,r){if(yi())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 Bd(e,s={}){const r={...$d,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Kd().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Un(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!yi())&&Js("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&&Js("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const y=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,y.slice(0,120),`approval-${u.id}`)}r.onComplete&&Js("completion")&&fi(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 Wd=/^(run|approve|accept|yes|allow|always)/,Od=/^(run|approve|accept|yes|allow|always|proceed|save)/,Hd=/^(reject|deny|delete|remove|abort|cancel|no)/;function ua(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ud(e){const s=ua(e).toLowerCase();return Wd.test(s)?"primary":Hd.test(s)?"danger":"default"}function Fd(e){return Od.test(ua(e).toLowerCase())?"approve":"reject"}function zd(e){return e.map((s,r)=>({label:ua(s),variant:Ud(s),action:Fd(s),button:s,buttonIndex:r}))}function Vd(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 Gd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function qd(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 Yd{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const 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
|
|
27
|
+
`})]})}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ft(e,s){const r=kt(s);return r?`${e}:${r}`:void 0}function Xt(e,s,r){const n=Ft(s,r),a=kt(r);n&&e.push(n),a&&e.push(a)}function Cs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function li(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function ca(e){return Cs([kt(e.providerSessionId),kt(e.sessionId)])}function os(e){const s=[];return Xt(s,"provider",e.providerSessionId),Xt(s,"session",e.sessionId),Xt(s,"tab",e.tabKey),Xt(s,"route",e.routeId),Cs(s)}function fd(e){const s=[];return kt(e.providerSessionId)?(Xt(s,"provider",e.providerSessionId),Cs(s)):kt(e.sessionId)?(Xt(s,"session",e.sessionId),Cs(s)):kt(e.tabKey)?(Xt(s,"tab",e.tabKey),Cs(s)):kt(e.routeId)?(Xt(s,"route",e.routeId),Cs(s)):[]}function di(e){return Ft("provider",e.providerSessionId)||Ft("session",e.sessionId)||Ft("tab",e.tabKey)||Ft("route",e.routeId)||"unknown:"}function lr(e){return ca(e)[0]}function ui(e){const s=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),i=[Ft("provider",s),Ft("session",r),Ft("tab",n),Ft("route",a)].filter(u=>typeof u=="string"),c=os({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=di({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:li({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:lr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Or(e,s){const r=ui(e);return fd(s).some(n=>r.lookupKeys.includes(n))}function en(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 mi=e=>en(e);function hd(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Os(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 tn(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...hd(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 Hr(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 la(e,s,r){const n=Hr(e,s),a=Os(e),i=os(e).map(L=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(L)}).find(L=>!!L),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,k=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:k,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":k?"task_complete":"idle"}}function xd(e,s,r){return la(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function pi({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Os(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(xs,{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),b=r===l,k=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:k,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"} ${k&&!b?"opacity-40":"opacity-100"} ${k?"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:b?"⏳ ...":c(l)},u)})})]})]})}var bd=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function gd(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if(gd(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":bd.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 fi(e){return jt(e)==="generating"}function at(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function yd(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 hn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function sn(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 vd(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 wd(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function jd(e){return vd(e.trim().replace(/\.local$/i,""))}function kd(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function hi(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&&!wd(c));if(r&&r!=="Unknown")return jd(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Mt(e,s={}){return kd(e)||hi(e,s)}function xi(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 bi(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 bs(e,s){return xi(e).join(" · ")}function ar(e){return e.transport==="pty"}function Is(e){return e.transport==="acp"}function Sd(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:at(e)}function Ja(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Nd(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Cd(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 Id(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 Ad(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&&Id(s.receivedAt)||0}function Md(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Hn(e){return Math.max(Md(e),Ad(e.activeChat))}function Td(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 da(e,s){return Td(Hn(e),Hn(s),Mt(e,{fallbackId:e.id}),Mt(s,{fallbackId:s.id}),e.id,s.id)}const gi="adhdev_notification_prefs",Za={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ld(){try{const e=localStorage.getItem(gi);if(e){const s=JSON.parse(e);return{...Za,...s}}}catch{}return{...Za}}function _d(e){try{localStorage.setItem(gi,JSON.stringify(e))}catch{}}let Ut=Ld(),_r=[];function Rd(){_r.forEach(e=>e())}function Pd(e){Ut={...Ut,...e},_d(Ut),Rd()}function Dd(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return _r.push(r),()=>{_r=_r.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Pd(r)},[]);return[{...Ut},s]}function Js(e){if(!Ut.globalEnabled)return!1;switch(e){case"disconnect":return Ut.disconnectAlert;case"completion":return Ut.completionAlert;case"approval":return Ut.approvalAlert;case"browser":return Ut.browserNotifications;default:return!0}}const $d={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ed(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function yi(){return"Notification"in window&&Notification.permission==="granted"}let rs=null;async function Kd(){if(rs!==null)return rs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return rs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(rs=!!await e.pushManager.getSubscription(),rs):(rs=!1,!1)}catch{return rs=!1,!1}}function Un(e,s,r){if(yi())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 Bd(e,s={}){const r={...$d,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Kd().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Un(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!yi())&&Js("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&&Js("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const b=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,b.slice(0,120),`approval-${u.id}`)}r.onComplete&&Js("completion")&&fi(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 Wd=/^(run|approve|accept|yes|allow|always)/,Od=/^(run|approve|accept|yes|allow|always|proceed|save)/,Hd=/^(reject|deny|delete|remove|abort|cancel|no)/;function ua(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Ud(e){const s=ua(e).toLowerCase();return Wd.test(s)?"primary":Hd.test(s)?"danger":"default"}function Fd(e){return Od.test(ua(e).toLowerCase())?"approve":"reject"}function zd(e){return e.map((s,r)=>({label:ua(s),variant:Ud(s),action:Fd(s),button:s,buttonIndex:r}))}function Vd(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 Gd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function qd(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 Yd{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const 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=at(p);const f=this.resolveOwningDaemon(s);if(f){const y=Mt(f,{fallbackId:f.id});y&&(m=!p||p==="adhdev-daemon"?y:`${y}/${m}`)}let b="",k="info";if(s.event==="agent:generating_completed"){const y=s.duration?` (${s.duration}s)`:"";b=`✅ ${m} agent task completed${y}`,k="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(b=`⚡ ${m} approval needed`,k="warning",n&&!((L=s.modalButtons)!=null&&L.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Vd(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const y=this.resolveActionRouteTarget(s);if(!y)return;const v=this.resolveActionFn,h=zd(s.modalButtons).map(g=>({label:g.label,variant:g.variant,onClick:()=>{v(y,"resolve_action",{action:g.action,button:g.button,buttonIndex:g.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),C=Gd(m,s.modalMessage,b),P=Date.now();this.emitToast({id:P,message:C,type:k,timestamp:P,targetKey:n||y,actions:h,duration:15e3}),b=""}}else if(s.event==="monitor:long_generating"){const y=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";b=`⚠️ ${m} agent is taking a long time${y}`,k="warning",Js("browser")&&!document.hasFocus()&&Un(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${y.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const y=s.requesterName||"A team member",v=s.requestId,h=s.orgId;if(b=`👁️ ${y} wants to view your session`,k="warning",v&&h&&this.viewRequestRespondFn){const C=Date.now(),P=qd(h,v,this.viewRequestRespondFn,(g,I)=>console.error(`[EventManager] ${g} view request failed:`,I));this.emitToast({id:C,message:b,type:k,timestamp:C,actions:P,duration:3e4}),b=""}Js("browser")&&!document.hasFocus()&&Un("👁️ View Request",`${y} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(b="✅ View request approved",k="success"):s.event==="team:view_request_rejected"&&(b=`❌ ${s.targetName||"Team member"} declined your view request`,k="warning");if(b){const y=Date.now();this.emitToast({id:y,message:b,type:k,timestamp:y,targetKey:n||s.daemonId,duration:5e3})}}}const lt=new Yd,eo=new Map;function Rs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vi(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Xd(e){return!Rs(e)||!Rs(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function gr(e){return!Rs(e)||!Rs(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Fs(e){if(!(!Rs(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function yr(e){return Rs(e)&&e.success===!1}function Qd(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";lt.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";lt.showToast(n.notification.body,a)}}}function Jd(e,s){return e&&vi(e.currentValue)?e.currentValue:s}function Rr(e,s){return e.options||s[e.id]||[]}function xn(e,s){return{value:s}}function Zd(e,s,r){var a;return r?((a=Rr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const eu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function tu({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Lt(),u=`${e}:${s||n}`,p=eu[n]||"#94a3b8",[m,f]=o.useState({}),b=o.useRef(0),k={};for(const _ of i||[])_.defaultValue!==void 0&&(k[_.id]=_.defaultValue);const L={...k,...c||{},...Date.now()<b.current?m:{}};o.useEffect(()=>{c&&Date.now()>b.current&&f({})},[c]);const[d,y]=o.useState(eo.get(u)||{}),[v,h]=o.useState(null),[C,P]=o.useState(null),g=o.useCallback(async(_,S={})=>{const O={...S,...s&&{targetSessionId:s}};return await l(e,_,O)},[e,s,l]),I=o.useCallback(async(_,S={})=>{const O=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await g("invoke_provider_script",{...O,scriptName:_,...S})},[g,n,r,s]),j=o.useCallback((_,S,O)=>{const G=Jd(O,S);f(A=>({...A,[_.id]:G})),Qd(O==null?void 0:O.effects)},[]),w=o.useCallback((_,S)=>{f(O=>{const G={...O};return S===void 0?delete G[_.id]:G[_.id]=S,G}),b.current=0},[]);if(!i||i.length===0)return null;const x=i.filter(_=>_.placement==="bar"&&_.hidden!==!0).sort((_,S)=>(_.order??50)-(S.order??50));if(x.length===0)return null;const $=async _=>{if(v===_.id){h(null);return}if(Rr(_,d).length>0){h(_.id);return}if(_.dynamic&&_.listScript){P(_.id);try{const O=await I(_.listScript,{}),G=Xd(O);if(!G){const K=Fs(O);K&<.showToast(K,"warning");return}const A=G.options;if(y(K=>{const V={...K,[_.id]:A};return eo.set(u,V),V}),vi(G.currentValue)){const K=G.currentValue;f(V=>({...V,[_.id]:K}))}h(_.id)}catch(O){const G=O instanceof Error?O.message:`Could not load ${_.label}`;lt.showToast(G,"warning")}finally{P(null)}}},N=async(_,S)=>{h(null);const O=(c==null?void 0:c[_.id])??k[_.id];f(G=>({...G,[_.id]:S})),b.current=Date.now()+5e3;try{if(!_.setScript)return;const G=await I(_.setScript,xn(_,S)),A=gr(G);if(A&&!A.ok||yr(G))throw new Error((A==null?void 0:A.error)||Fs(G)||`Could not update ${_.label}`);j(_,S,A)}catch(G){w(_,O);const A=G instanceof Error?G.message:`Could not update ${_.label}`;lt.showToast(A,"warning")}},T=async _=>{const S=Rr(_,d).map(U=>U.value);if(S.length===0)return;const O=String(L[_.id]||""),A=(S.indexOf(O)+1)%S.length,K=S[A];if(typeof K!="string")return;const V=(c==null?void 0:c[_.id])??k[_.id];f(U=>({...U,[_.id]:K})),b.current=Date.now()+5e3;try{if(!_.setScript)return;const U=await I(_.setScript,xn(_,K)),ce=gr(U);if(ce&&!ce.ok||yr(U))throw new Error((ce==null?void 0:ce.error)||Fs(U)||`Could not update ${_.label}`);j(_,K,ce)}catch(U){w(_,V);const ce=U instanceof Error?U.message:`Could not update ${_.label}`;lt.showToast(ce,"warning")}},M=async _=>{const O=!L[_.id],G=(c==null?void 0:c[_.id])??k[_.id];f(A=>({...A,[_.id]:O})),b.current=Date.now()+5e3;try{if(!_.setScript)return;const A=await I(_.setScript,xn(_,O)),K=gr(A);if(K&&!K.ok||yr(A))throw new Error((K==null?void 0:K.error)||Fs(A)||`Could not update ${_.label}`);j(_,O,K)}catch(A){w(_,G);const K=A instanceof Error?A.message:`Could not update ${_.label}`;lt.showToast(K,"warning")}},B=async _=>{if(!_.invokeScript)return;if(_.confirmMessage){const O=[_.confirmTitle,_.confirmMessage,_.confirmLabel].filter(A=>typeof A=="string"&&A.trim().length>0);if(!window.confirm(O.join(`
|
|
29
29
|
|
|
30
|
-
`)))return}const S=(c==null?void 0:c[_.id])??k[_.id];try{const O=await I(_.invokeScript),G=gr(O);if(G&&!G.ok||yr(O))throw new Error((G==null?void 0:G.error)||Fs(O)||`Could not run ${_.label}`);G&&j(_,S??!0,G)}catch(O){w(_,S);const G=O instanceof Error?O.message:`Could not run ${_.label}`;lt.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(_=>{const S=String(T[_.id]||""),O=Zd(_,d,S),G=v===_.id,A=C===_.id,K=Rr(_,d);switch(_.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:G?`${p}55`:"transparent",border:"1px solid",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),A?"...":O||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&K.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:_.label.toUpperCase()}),K.map(V=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:V.value===S?`${p}18`:"transparent",color:V.value===S?p:"var(--text-secondary)",fontWeight:V.value===S?600:400,borderLeft:V.value===S?`2px solid ${p}`:"2px solid transparent"},title:V.description||V.label,onMouseEnter:U=>{U.currentTarget.style.background=`${p}12`},onMouseLeave:U=>{U.currentTarget.style.background=V.value===S?`${p}18`:"transparent"},onClick:()=>N(_,V.value),children:V.label},V.value))]})]})]},_.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>L(_),title:`Click to cycle: ${K.map(V=>V.label).join(" → ")}`,children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),O||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},_.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:S?`${p}44`:"transparent",background:S?`${p}14`:"var(--surface-tertiary)",color:S?p:"var(--text-muted)"},onClick:()=>M(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.label]},_.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>B(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.resultDisplay==="inline"&&S?`${_.label}: ${S}`:_.label]},_.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:S?"var(--text-primary)":"var(--text-muted)"},children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),S?`${_.label}: ${S}`:_.label]},_.id);default:return null}})]})}function wi({hasDraft:e,isBusy:s=!1}){return!e||s}const su=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0}){const u=o.useRef(null),[p,m]=o.useState("");o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var y;l&&((y=u.current)==null||y.focus())},[s,l]);const f=async()=>{const y=p.trim();if(!y||a)return;await c(y)!==!1&&m("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2.5 items-center",title:l?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:i||`Send message to ${r}...`,value:p,onChange:y=>m(y.target.value),onPaste:y=>{const k=y.clipboardData.getData("text");k&&m(T=>T+k),y.preventDefault()},onKeyDown:y=>{if(y.key==="Enter"){if(y.nativeEvent.isComposing){y.preventDefault();return}y.preventDefault(),f()}},onBlur:y=>{if(window.innerWidth<768){const k=y.relatedTarget;if((k==null?void 0:k.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{f()},disabled:wi({hasDraft:!!p.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!a?{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:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Ps=(e,s)=>tt(e)?e.mode||"terminal":"chat",ji=(e,s)=>tt(e)&&Ps(e)==="terminal",Je=e=>e.transport==="acp";function Qt(e){return e.streamSource!=="agent-stream"}function es(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function ki(e){return e.machineName||""}function dr(e){return es(e)}function $t(e){return e.agentType||""}function Ur(e){return e.hostIdeType||""}function ma(e){return e.displayPrimary||e.agentName||"Agent"}function Si(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function ru(e){return e.lastMessagePreview||e.displaySecondary||""}function Ni(e){return[e.displaySecondary,ki(e)].filter(Boolean)}function Ds(e){return e.agentName||at($t(e))}function nu(e){var s,r;if(!Qt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Ur(e)||$t(e))}function Ci(e){return Qt(e)?e.sessionId:e.nativeSessionId}function to(e){return Qt(e)?"native":e.tabKey}function au(e){return e.sessionId}function ou(e,s){if(s)return Qt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function iu(e,s){const r=$t(e),n=Qt(e),a=tt(e)||Je(e),i=n?a?Ds(e)||(s==null?void 0:s.cliName)||at(Ur(e)||r):s!=null&&s.type?at(s.type):at(Ur(e)||r):Ds(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Je(e),isCliTerminal:ji(e),providerType:r,displayLabel:i,targetEntry:ou(e,s)}}function cu(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 is(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||cu(s==null?void 0:s.receivedAt)||0}function Fn(e,s=0){return is(e)||e.lastUpdated||s||0}function Ii(e){return is(e)||e.lastUpdated||0}function Ai(e,s,r=Ii){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 zn(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 lu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!zn(e)&&!e.title.trim()}function du(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(zn(r))-Number(zn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Ai(s,r)})[0]||null}function Kt(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=du(a);return n?i&&lu(n)?i:n:i||r[0]||null}function Jt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function pa(e){return lr(e)||e.tabKey||e.routeId||null}function Mi(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Kt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?pa(a):null}function Ti({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Bs(),c=es(e),l=ki(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=Ds(e),y=nu(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),T=o.useCallback(()=>{if(r){r();return}const d=pa(e);d&&i(Jt(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:T,title:y,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:y})]}):t.jsxs("span",{className:"conversation-meta-chip",title:y,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:y})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(nr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(nr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}))]})}function bn(e,s){return`${e}:${s}`}function uu(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function vr(e,s){uu()&&console.debug(`[subscription-manager] ${e}`,s)}class mu{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=bn(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),vr("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 y;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};vr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=s.sendData)==null||y.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=bn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ts.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),Ts.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=bn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;vr("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);vr("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 Zt=new mu;function pu(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 fu(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 Fr(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}=fu(u),f=pu(i,n),y=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=p.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),T=p.filter(g=>g.kind==="agent"&&g.transport==="pty"),d=p.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...y&&{machine:y,platform:y.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:k.some(g=>!!g.cdpConnected)});for(const g of k){const v=f.get(g.id),h=Xs(g,v),C=(m.get(g.id)||[]).map(P=>Xs(P,f.get(P.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:g.id,workspace:h.workspace,terminals:0,childSessions:C,agents:C.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.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 g of T){const v=f.get(g.id),h=Xs(g,v);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.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:g.id,cliName:h.providerName||h.providerType,mode:h.mode||(v==null?void 0:v.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 g of d){const v=f.get(g.id),h=Xs(g,v);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(v==null?void 0:v.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:g.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 gn=new Map,yn=new Map,vn=new Set,Zs=new Map,hu=1200;function xu(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 so(e,s){const r=Zs.get(e);!r||r.size===0||(Zs.delete(e),r.forEach(n=>n(s)))}function bu(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 ur(){const{sendCommand:e,sendData:s}=Lt(),{injectEntries:r,getIdes:n}=Wr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=yn.get(a)||0;if(!(i!=null&&i.force)&&vn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=gn.get(a);if(u)return u;const p=(async()=>{if(s&&!vn.has(a)&&(vn.add(a),Zt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const g=n(),v=g.find(C=>C.id===a),h=Fr(d.status,{daemonId:a,existingDaemon:v,existingEntries:g,timestamp:d.timestamp});h.length>0&&r(h),yn.set(a,Date.now()),so(a,!0)}),!(i!=null&&i.force)&&await bu(a,hu)))return;const m=await e(a,"get_status_metadata"),f=xu(m);if(!f)return;const y=n(),k=y.find(d=>d.id===a),T=Fr(f,{daemonId:a,existingDaemon:k,existingEntries:y,timestamp:f.timestamp||Date.now()});T.length>0&&r(T,{authoritativeDaemonIds:[a]}),yn.set(a,Date.now()),so(a,!0)})().finally(()=>{gn.delete(a)});return gn.set(a,p),p},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function fa(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=_s(e.content),i=_s(s.content);if(!a||!i||!(a===i||or(a,i)||or(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function ro(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function $s(e){return _s(e==null?void 0:e.content)}function or(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function gu(e,s){const r=$s(e),n=$s(s);return!r||!n||r===n?null:or(r,n)?e:or(n,r)?s:null}function yu(e,s){const r=gu(e,s);if(r)return r;const n=ro(e),a=ro(s);return a!==n?a>n?s:e:$s(s).length>=$s(e).length?s:e}function cs(e){const s=[];for(const r of e){const n=s.findIndex(a=>fa(a,r));if(n>=0){s.splice(n,1,yu(s[n],r));continue}s.push(r)}return s}function vu(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:cs([...r,...n])}function no(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function ao(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=>fa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function wu(e,s){return e.filter(r=>{const n=$s(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Gt(r);return!s.some(c=>{if(fa(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=$s(c);if(!or(u,n)&&u!==n)return!1;const p=Gt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}function As(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Je(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:s}function ir(e){return e?dr(e):""}function zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ha(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function ju(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const ku=60,Su=200;function Nu(e={}){return e.isCliLike?Su:ku}const mr=60,oo=new Map;function Li(e,s){return`${e}::${s}`}function Vn(e=mr){return{liveMessages:[],cursor:Ri([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function _i(e){return Jo(e)}function Ri(e,s=mr){return{knownMessageCount:e.length,lastMessageSignature:_i(e[e.length-1]),tailLimit:s}}function wr(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 Cu(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return cs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return cs([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return cs([...e.slice(0,a),...r])}return r}default:return r}}class Iu{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);this.manager=s.manager||Zt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Vn(Math.max(0,s.tailLimit??mr))}updateOptions(s){s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId)}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=cs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Ri(n,this.snapshot.cursor.tailLimit);wr(this.snapshot.liveMessages)===wr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Cu(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:_i(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};wr(this.snapshot.liveMessages)===wr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function Pi(e){const s=Li(e.daemonId,e.sessionId),r=oo.get(s);if(r)return r.updateOptions(e),r;const n=new Iu(e);return oo.set(s,n),n}function Au(e,s){return{...e,loadHistoryPage:s}}function Mu(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Tu(e){const s=new Set,r=[];for(const n of e){const a=dr(n),i=n.sessionId||"";if(!a||!i)continue;const c=Li(a,i);if(s.has(c))continue;s.add(c);const l=lr(n);r.push({daemonId:a,sessionId:i,historySessionId:l||i,subscriptionKey:`daemon:${a}:session:${i}`})}return r.sort(Mu),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function Lu(e,s){const{sendData:r,sendCommand:n}=Lt(),a=(s==null?void 0:s.enabled)!==!1,i=dr(e),c=e.sessionId||"",l=lr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??mr),m=o.useMemo(()=>!a||!i||!c?null:Pi({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,y]=o.useState(()=>(m==null?void 0:m.getSnapshot())||Vn(p));o.useEffect(()=>{if(!m){y(Vn(p));return}m.hydrateLiveMessages(e.messages),m.retain(),y(m.getSnapshot());const T=m.subscribe(d=>{y(d)});return()=>{T(),m.release()}},[e.messages,m,p]);const k=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const T=e.agentType,d=await n(i,"chat_history",{agentType:T,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),g=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(g.messages)?g.messages:[],hasMore:g.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>Au(f,k),[k,f])}function _u(e,s){const{sendData:r}=Lt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,mr),i=o.useMemo(()=>Tu(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>Pi({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}function Ru(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Pu(e){return Ru(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Du=60;function Gn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ce,Y;const y=o.useRef(new Map),k=ur();cr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const T=nt.useMemo(()=>Os(e),[e.status,e.connectionState]),d=o.useMemo(()=>iu(e,s),[e,s]),g=Nu({isCliLike:d.isCli||d.isAcp}),v=Lu(e,{enabled:!!e.sessionId}),[h,C]=o.useState(g),P=e.tabKey,b=v.historyMessages,I=v.hasMoreHistory,j=v.historyError,w=vu(v.liveMessages,e.messages);o.useEffect(()=>{C(g)},[g,P]);const x=Math.max(0,w.length-h),$=ma(e),N=dr(e),L=Pu(e),M=ha(e),B=a||M,_=!!M,[S,O]=o.useState(!1);o.useEffect(()=>{const oe=d.targetEntry;N&&(!oe||oe.providerControls===void 0||oe.controlValues===void 0)&&k(N,{minFreshMs:3e4}).catch(()=>{})},[N,d.isAcp,(ce=d.targetEntry)==null?void 0:ce.providerControls,(Y=d.targetEntry)==null?void 0:Y.controlValues,k]);const G=o.useCallback(async()=>{if(!S){if(w.length>h){C(oe=>Math.min(w.length,oe+Du));return}O(!0);try{await v.loadHistoryPage()}finally{O(!1)}}},[v,S,w.length,h]),{allMessages:A,receivedAtMap:K}=o.useMemo(()=>{const oe=x>0?w.slice(-h):w;if(b.length===0){const Ne=no(cs(oe)),le={};return Ne.forEach((pe,ae)=>{const z=`${e.tabKey}:${Ns(pe,ae)}`;let ve=Gt(pe)||y.current.get(z)||0;ve||(ve=Date.now(),y.current.set(z,ve)),le[Ns(pe,ae)]=ve}),{allMessages:Ne,receivedAtMap:le}}const Q=wu(b,oe),te=no(cs([...Q,...oe])),ue={};return te.forEach((Ne,le)=>{const pe=`${e.tabKey}:${Ns(Ne,le)}`;let ae=Gt(Ne)||y.current.get(pe)||0;ae||(ae=Date.now(),y.current.set(pe,ae)),ue[Ns(Ne,le)]=ae}),{allMessages:te,receivedAtMap:ue}},[e.tabKey,x,b,w,h]),V=o.useMemo(()=>l.filter(oe=>oe.routeId===e.tabKey).sort((oe,Q)=>oe.timestamp-Q.timestamp),[l,e.tabKey]),U=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((T.isGenerating||e.status==="streaming")&&O(!1),e.status==="not_monitored"&&L)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(nr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{size:14})," Open ",$," 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"&&L)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(si,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{size:14})," Open ",$," 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"&&!S)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,L,i,c,S,w.length,$,T.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(Ti,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(ad,{messages:A,actionLogs:V,agentName:Ds(e)||$||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:T.isGenerating,contextKey:e.tabKey,receivedAtMap:K,onLoadMore:G,isLoadingMore:S,hasMoreHistory:I,hiddenLiveCount:x,loadError:j??void 0,emptyState:U,scrollToBottomRequestNonce:m}),f&&!d.isCliTerminal&&(()=>{var oe,Q;return t.jsx(tu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(oe=d.targetEntry)==null?void 0:oe.providerControls,controlValues:(Q=d.targetEntry)==null?void 0:Q.controlValues})})(),!d.isCliTerminal&&t.jsx(su,{contextKey:e.tabKey,panelLabel:$,isSending:n,isBusy:_,statusMessage:B,onSend:r,isActive:f})]})}let Di=hs;function $i(){return Di()}class $u{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let Ei=new $u;class Eu{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 ut=new Eu;function Ku(e){e.dashboardWS&&(Ei=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Di=e.useDaemonsHook)}function dt(e){return ma(e)}function gs(e){return Ni(e).join(" · ")}function Ki(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=_s(s==null?void 0:s.content);return r||(e.title?e.title:gs(e)||"No messages yet")}function Bi(e,s){const{isReconnecting:r,isConnecting:n}=Os(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Bu(e,s){const r=["Chat",...Ni(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ls(e){return Bi(e)||gs(e)}function Wu(e){return`${dt(e)} · ${Ki(e)}`}function Ou(e){const s=Ur(e),r=s?at(s):Ds(e);return`${dt(e)} — ${r||"Agent"}`}function Hu(e){return Ds(e)||"CLI"}function Wi(e){return Si(e)}function Oi(e){return e?`Remote · ${dt(e)||e.workspaceName||"Session"}`:"Remote"}function Uu({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var ce;const{ides:l}=hs(),u=o.useRef(null),{sendCommand:p,sendData:m}=Lt(),[f,y]=o.useState(""),[k,T]=o.useState(!1),[d,g]=o.useState(1),v=o.useRef(!1),h=o.useRef(0),C=o.useRef(!1),P=o.useRef(""),b=o.useRef(null),I=o.useRef(!1),j=o.useRef(null),w=e.tabKey,x=e.sessionId||"",$=e.daemonId||((ce=e.routeId)==null?void 0:ce.split(":")[0])||e.routeId||"",N=l.find(Y=>Y.id===$&&Y.type==="adhdev-daemon"),L=(N==null?void 0:N.terminalSizingMode)==="fit"?"fit":"measured",M=ha(e),B=i||M,_=.6,S=1.15,O=()=>{if(typeof window>"u")return 1;const Y=window.innerWidth||0;return Y<=360?.68:Y<=390?.74:Y<=430?.82:Y<=480?.9:1},G=()=>{var Y,oe;h.current=0,C.current=!1,P.current="",b.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),T(!1),(oe=(Y=r.current)==null?void 0:Y.reset)==null||oe.call(Y)},A=()=>{var Y,oe;h.current=0,C.current=!1,P.current="",b.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),T(!0),(oe=(Y=r.current)==null?void 0:Y.reset)==null||oe.call(Y)},K=()=>{var oe;if(j.current=null,!c)return;const Y=P.current;Y&&(P.current="",(oe=r.current)==null||oe.write(Y))},V=Y=>{Y&&(P.current+=Y,c&&j.current===null&&(j.current=requestAnimationFrame(K)))},U=(Y,oe=0,Q,te)=>{var ue,Ne,le,pe,ae;oe>0&&h.current>=oe||oe===0&&C.current||(h.current=oe,T(!0),typeof Q=="number"&&typeof te=="number"&&Q>0&&te>0&&((Ne=(ue=r.current)==null?void 0:ue.resize)==null||Ne.call(ue,Q,te)),(pe=(le=r.current)==null?void 0:le.reset)==null||pe.call(le),Y&&((ae=r.current)==null||ae.write(Y)))};return o.useEffect(()=>{G()},[x]),o.useEffect(()=>{var oe;if(!x)return;const Y=((oe=ut.onRuntimeEvent)==null?void 0:oe.call(ut,x,Q=>{if(!(!Q||Q.sessionId!==x)){if(Q.type==="runtime_snapshot"){if(!c){b.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows};return}U(Q.text||"",Q.seq||0,Q.cols,Q.rows);return}if(Q.type==="session_output"){C.current=!0,typeof Q.seq=="number"&&(h.current=Math.max(h.current,Q.seq)),k||T(!0),typeof Q.data=="string"&&V(Q.data);return}if(Q.type==="session_cleared"){if(!c){I.current=!0,P.current="",b.current=null;return}A()}}}))||(()=>{});return()=>{Y()}},[$,x,r,c,k]),o.useEffect(()=>{var oe,Q,te;if(!x)return;$&&((oe=ut.getState)==null?void 0:oe.call(ut,$))==="connected"&&(T(!0),(Q=ut.requestRuntimeSnapshot)==null||Q.call(ut,$,x).catch(()=>{}));const Y=(te=ut.onStateChange)==null?void 0:te.call(ut,(ue,Ne)=>{var le;ue!==$||Ne!=="connected"||(T(!0),(le=ut.requestRuntimeSnapshot)==null||le.call(ut,$,x).catch(()=>{}))});return()=>{Y==null||Y()}},[$,x,r]),o.useEffect(()=>{s&&G()},[s,w,r]),o.useEffect(()=>{y("")},[e.tabKey]),o.useEffect(()=>{const Y=()=>{v.current||g(O())};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),o.useEffect(()=>{var oe;if(!c){(oe=u.current)==null||oe.blur();return}I.current&&(I.current=!1,A());const Y=b.current;Y&&(b.current=null,U(Y.text,Y.seq,Y.cols,Y.rows)),P.current&&j.current===null&&(j.current=requestAnimationFrame(K)),requestAnimationFrame(()=>{var Q;(Q=r.current)==null||Q.bumpResize()})},[c]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const Y=oe=>{var te;const Q=oe.detail;Q!=null&&Q.sessionId&&Q.sessionId!==x||k&&((te=r.current)==null||te.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",Y),()=>{window.removeEventListener("adhdev:fit-cli-terminal",Y)}},[k,x,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:()=>{v.current=!0,g(Y=>Math.max(_,Number((Y-.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:()=>{v.current=!0,g(Y=>Math.min(S,Number((Y+.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/d}%`,height:`${100/d}%`,transform:`scale(${d})`,transformOrigin:"top left"},children:t.jsx(ii,{ref:r,readOnly:!k||!c,sizingMode:L,onInput:Y=>{k&&(m!=null&&m($,{type:"pty_input",sessionId:x,targetSessionId:x,data:Y})||p($,"pty_input",{targetSessionId:x,data:Y}).catch(console.error))}})})}),!k&&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.jsxs("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:u,type:"text",placeholder:B||`Send message to ${dt(e)}...`,value:f,disabled:!k||!c,onChange:Y=>y(Y.target.value),onPaste:Y=>{const oe=Y.clipboardData.getData("text");oe&&y(Q=>Q+oe),Y.preventDefault()},onKeyDown:Y=>{if(Y.key!=="Enter")return;if(Y.nativeEvent.isComposing){Y.preventDefault();return}Y.preventDefault();const oe=f.trim();!k||!oe||M||n(oe).then(Q=>{Q!==!1&&y("")})},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 Y=f.trim();!k||!Y||M||n(Y).then(oe=>{oe!==!1&&y("")})},disabled:!k||!c||wi({hasDraft:!!f.trim(),isBusy:!!M}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!M?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.trim()&&!M?{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:f.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),B&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:B})]})]})}function Fu({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 zu({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 xa({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(Jr,{size:n}):t.jsx(Vt,{size:n})})}function io({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function co({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=en(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 Vu({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:y,onShowAllHidden:k,onResetPanelsToMain:T,inboxOpen:d,onInboxOpenChange:g,hiddenOpen:v,onHiddenOpenChange:h,onOpenNewSession:C,actionShortcuts:P,notifications:b,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:N,p2pStates:L={}}=hs(),M=!!e&&tt(e)&&!Je(e),B=!!e&&Je(e),_=u||(e?ji(e)?"terminal":"chat":null),[S,O]=o.useState(!1),G=o.useRef(null),A=o.useRef(null),K=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",V=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",U=N.filter(z=>z.type==="adhdev-daemon"),ce=Object.values(L),Y=ce.filter(z=>z==="connected").length,oe=ce.filter(z=>z==="connecting"||z==="new"||z==="checking").length,te=r!=="connected"||U.length===0?null:oe>0&&Y===0?"P2P connecting...":Y>0&&s===0?"Waiting for IDE...":null,ue=o.useMemo(()=>b.filter(z=>!z.readAt),[b]),Ne=o.useMemo(()=>b.filter(z=>!!z.readAt),[b]),le=o.useMemo(()=>ue.slice(0,9),[ue]),pe=I;o.useEffect(()=>{if(!d)return;const z=ve=>{var ee;(ee=G.current)!=null&&ee.contains(ve.target)||g(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,g]),o.useEffect(()=>{if(!v)return;const z=ve=>{var ee;(ee=A.current)!=null&&ee.contains(ve.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[v,h]),o.useEffect(()=>{if(!v&&!d)return;const z=ve=>{if(!ve.altKey)return;const ee=ve.code.match(/^Digit([1-9])$/);if(!ee)return;const we=Number(ee[1])-1,re=v?f[we]:void 0,ie=d?le[we]:void 0;if(!(!re&&!ie)){if(ve.preventDefault(),ve.stopPropagation(),re){y==null||y(re),h(!1);return}ie&&(j(ie),g(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,v,d,le,h,g,j,y]);const ae=z=>{if(!z)return;const ve=a.find(ee=>ee.tabKey===z);ve&&(m==null||m(ve))};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(Vt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?dt(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:K,boxShadow:V}})})]}),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:K,boxShadow:V}}),te&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",te]}),C&&t.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx($l,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||B||!Je(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:gs(e)||dt(e),children:dt(e)}),(M||B)&&l&&t.jsxs(t.Fragment,{children:[M&&p&&_&&t.jsx(xa,{mode:_,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:B?"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(Nt,{size:14})})]}),!Je(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(aa,{size:14})}),!M&&!Je(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Tt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${S?" is-drop-target":""}`,ref:A,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),O(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",O(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||O(!1)},onDrop:z=>{const ve=z.dataTransfer.getData("text/tab-key");z.preventDefault(),O(!1),ae(ve)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(ri,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),v&&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(io,{value:P==null?void 0:P.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[T&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:T,children:"Reset panels"}),f.length>0&&k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{k(),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(io,{value:P==null?void 0:P.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:dt(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:()=>{y==null||y(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:dt(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,gs(z)]})]},z.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>g(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Zr,{size:16}),pe>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:pe})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ue.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ue.map(z=>t.jsx(co,{notification:z,shortcutIndex:le.indexOf(z)>=0?le.indexOf(z)+1:void 0,onOpen:()=>j(z),onMarkRead:()=>w(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>$(z.id)},z.id))]}),Ne.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Ne.map(z=>t.jsx(co,{notification:z,onOpen:()=>j(z),onMarkRead:()=>w(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>$(z.id)},z.id))]}),b.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function yt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Gu(e,s){return String(e||"")!==String(s||"")}function qu(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(`
|
|
30
|
+
`)))return}const S=(c==null?void 0:c[_.id])??k[_.id];try{const O=await I(_.invokeScript),G=gr(O);if(G&&!G.ok||yr(O))throw new Error((G==null?void 0:G.error)||Fs(O)||`Could not run ${_.label}`);G&&j(_,S??!0,G)}catch(O){w(_,S);const G=O instanceof Error?O.message:`Could not run ${_.label}`;lt.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(_=>{const S=String(L[_.id]||""),O=Zd(_,d,S),G=v===_.id,A=C===_.id,K=Rr(_,d);switch(_.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:G?`${p}55`:"transparent",border:"1px solid",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),A?"...":O||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&K.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:_.label.toUpperCase()}),K.map(V=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:V.value===S?`${p}18`:"transparent",color:V.value===S?p:"var(--text-secondary)",fontWeight:V.value===S?600:400,borderLeft:V.value===S?`2px solid ${p}`:"2px solid transparent"},title:V.description||V.label,onMouseEnter:U=>{U.currentTarget.style.background=`${p}12`},onMouseLeave:U=>{U.currentTarget.style.background=V.value===S?`${p}18`:"transparent"},onClick:()=>N(_,V.value),children:V.label},V.value))]})]})]},_.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:S?"var(--text-primary)":"var(--text-muted)"},onClick:()=>T(_),title:`Click to cycle: ${K.map(V=>V.label).join(" → ")}`,children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),O||_.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},_.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:S?`${p}44`:"transparent",background:S?`${p}14`:"var(--surface-tertiary)",color:S?p:"var(--text-muted)"},onClick:()=>M(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.label]},_.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>B(_),children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),_.resultDisplay==="inline"&&S?`${_.label}: ${S}`:_.label]},_.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:S?"var(--text-primary)":"var(--text-muted)"},children:[_.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:_.icon}),S?`${_.label}: ${S}`:_.label]},_.id);default:return null}})]})}function wi({hasDraft:e,isBusy:s=!1}){return!e||s}const su=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0}){const u=o.useRef(null),[p,m]=o.useState("");o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var b;l&&((b=u.current)==null||b.focus())},[s,l]);const f=async()=>{const b=p.trim();if(!b||a)return;await c(b)!==!1&&m("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2.5 items-center",title:l?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:i||`Send message to ${r}...`,value:p,onChange:b=>m(b.target.value),onPaste:b=>{const k=b.clipboardData.getData("text");k&&m(L=>L+k),b.preventDefault()},onKeyDown:b=>{if(b.key==="Enter"){if(b.nativeEvent.isComposing){b.preventDefault();return}b.preventDefault(),f()}},onBlur:b=>{if(window.innerWidth<768){const k=b.relatedTarget;if((k==null?void 0:k.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{f()},disabled:wi({hasDraft:!!p.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${p.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:p.trim()&&!a?{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:p.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Ps=(e,s)=>tt(e)?e.mode||"terminal":"chat",ji=(e,s)=>tt(e)&&Ps(e)==="terminal",Je=e=>e.transport==="acp";function Qt(e){return e.streamSource!=="agent-stream"}function es(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function ki(e){return e.machineName||""}function dr(e){return es(e)}function $t(e){return e.agentType||""}function Ur(e){return e.hostIdeType||""}function ma(e){return e.displayPrimary||e.agentName||"Agent"}function Si(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function ru(e){return e.lastMessagePreview||e.displaySecondary||""}function Ni(e){return[e.displaySecondary,ki(e)].filter(Boolean)}function Ds(e){return e.agentName||at($t(e))}function nu(e){var s,r;if(!Qt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Ur(e)||$t(e))}function Ci(e){return Qt(e)?e.sessionId:e.nativeSessionId}function to(e){return Qt(e)?"native":e.tabKey}function au(e){return e.sessionId}function ou(e,s){if(s)return Qt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function iu(e,s){const r=$t(e),n=Qt(e),a=tt(e)||Je(e),i=n?a?Ds(e)||(s==null?void 0:s.cliName)||at(Ur(e)||r):s!=null&&s.type?at(s.type):at(Ur(e)||r):Ds(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Je(e),isCliTerminal:ji(e),providerType:r,displayLabel:i,targetEntry:ou(e,s)}}function cu(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 is(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||cu(s==null?void 0:s.receivedAt)||0}function Fn(e,s=0){return is(e)||e.lastUpdated||s||0}function Ii(e){return is(e)||e.lastUpdated||0}function Ai(e,s,r=Ii){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 zn(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 lu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!zn(e)&&!e.title.trim()}function du(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(zn(r))-Number(zn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Ai(s,r)})[0]||null}function Kt(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=du(a);return n?i&&lu(n)?i:n:i||r[0]||null}function Jt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function pa(e){return lr(e)||e.tabKey||e.routeId||null}function Mi(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Kt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?pa(a):null}function Ti({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Bs(),c=es(e),l=ki(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=Ds(e),b=nu(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),L=o.useCallback(()=>{if(r){r();return}const d=pa(e);d&&i(Jt(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:b,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:b})]}):t.jsxs("span",{className:"conversation-meta-chip",title:b,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:b})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(nr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(nr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(zt,{size:12}),t.jsx("span",{children:l})]}))]})}function bn(e,s){return`${e}:${s}`}function uu(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function vr(e,s){uu()&&console.debug(`[subscription-manager] ${e}`,s)}class mu{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=bn(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),vr("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 b;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};vr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(b=s.sendData)==null||b.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=bn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ts.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),Ts.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=bn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;vr("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);vr("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 Zt=new mu;function pu(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 fu(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 Fr(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}=fu(u),f=pu(i,n),b=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=p.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),L=p.filter(y=>y.kind==="agent"&&y.transport==="pty"),d=p.filter(y=>y.kind==="agent"&&y.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...b&&{machine:b,platform:b.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:k.some(y=>!!y.cdpConnected)});for(const y of k){const v=f.get(y.id),h=Xs(y,v),C=(m.get(y.id)||[]).map(P=>Xs(P,f.get(P.id)));r.push({id:`${n}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:y.id,workspace:h.workspace,terminals:0,childSessions:C,agents:C.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.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 y of L){const v=f.get(y.id),h=Xs(y,v);r.push({id:`${n}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(v==null?void 0:v.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:y.id,cliName:h.providerName||h.providerType,mode:h.mode||(v==null?void 0:v.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 y of d){const v=f.get(y.id),h=Xs(y,v);r.push({id:`${n}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(v==null?void 0:v.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:y.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 gn=new Map,yn=new Map,vn=new Set,Zs=new Map,hu=1200;function xu(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 so(e,s){const r=Zs.get(e);!r||r.size===0||(Zs.delete(e),r.forEach(n=>n(s)))}function bu(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 ur(){const{sendCommand:e,sendData:s}=Lt(),{injectEntries:r,getIdes:n}=Wr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=yn.get(a)||0;if(!(i!=null&&i.force)&&vn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=gn.get(a);if(u)return u;const p=(async()=>{if(s&&!vn.has(a)&&(vn.add(a),Zt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const y=n(),v=y.find(C=>C.id===a),h=Fr(d.status,{daemonId:a,existingDaemon:v,existingEntries:y,timestamp:d.timestamp});h.length>0&&r(h),yn.set(a,Date.now()),so(a,!0)}),!(i!=null&&i.force)&&await bu(a,hu)))return;const m=await e(a,"get_status_metadata"),f=xu(m);if(!f)return;const b=n(),k=b.find(d=>d.id===a),L=Fr(f,{daemonId:a,existingDaemon:k,existingEntries:b,timestamp:f.timestamp||Date.now()});L.length>0&&r(L,{authoritativeDaemonIds:[a]}),yn.set(a,Date.now()),so(a,!0)})().finally(()=>{gn.delete(a)});return gn.set(a,p),p},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function fa(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=_s(e.content),i=_s(s.content);if(!a||!i||!(a===i||or(a,i)||or(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function ro(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function $s(e){return _s(e==null?void 0:e.content)}function or(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function gu(e,s){const r=$s(e),n=$s(s);return!r||!n||r===n?null:or(r,n)?e:or(n,r)?s:null}function yu(e,s){const r=gu(e,s);if(r)return r;const n=ro(e),a=ro(s);return a!==n?a>n?s:e:$s(s).length>=$s(e).length?s:e}function cs(e){const s=[];for(const r of e){const n=s.findIndex(a=>fa(a,r));if(n>=0){s.splice(n,1,yu(s[n],r));continue}s.push(r)}return s}function vu(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:cs([...r,...n])}function no(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function ao(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=>fa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function wu(e,s){return e.filter(r=>{const n=$s(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Gt(r);return!s.some(c=>{if(fa(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=$s(c);if(!or(u,n)&&u!==n)return!1;const p=Gt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}function As(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Je(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:s}function ir(e){return e?dr(e):""}function zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ha(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function ju(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const ku=60,Su=200;function Nu(e={}){return e.isCliLike?Su:ku}const mr=60,oo=new Map;function Li(e,s){return`${e}::${s}`}function Vn(e=mr){return{liveMessages:[],cursor:Ri([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function _i(e){return Jo(e)}function Ri(e,s=mr){return{knownMessageCount:e.length,lastMessageSignature:_i(e[e.length-1]),tailLimit:s}}function wr(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 Cu(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return cs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return cs([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return cs([...e.slice(0,a),...r])}return r}default:return r}}class Iu{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);this.manager=s.manager||Zt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Vn(Math.max(0,s.tailLimit??mr))}updateOptions(s){s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId)}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=cs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Ri(n,this.snapshot.cursor.tailLimit);wr(this.snapshot.liveMessages)===wr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Cu(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:_i(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};wr(this.snapshot.liveMessages)===wr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function Pi(e){const s=Li(e.daemonId,e.sessionId),r=oo.get(s);if(r)return r.updateOptions(e),r;const n=new Iu(e);return oo.set(s,n),n}function Au(e,s){return{...e,loadHistoryPage:s}}function Mu(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Tu(e){const s=new Set,r=[];for(const n of e){const a=dr(n),i=n.sessionId||"";if(!a||!i)continue;const c=Li(a,i);if(s.has(c))continue;s.add(c);const l=lr(n);r.push({daemonId:a,sessionId:i,historySessionId:l||i,subscriptionKey:`daemon:${a}:session:${i}`})}return r.sort(Mu),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function Lu(e,s){const{sendData:r,sendCommand:n}=Lt(),a=(s==null?void 0:s.enabled)!==!1,i=dr(e),c=e.sessionId||"",l=lr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??mr),m=o.useMemo(()=>!a||!i||!c?null:Pi({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,b]=o.useState(()=>(m==null?void 0:m.getSnapshot())||Vn(p));o.useEffect(()=>{if(!m){b(Vn(p));return}m.hydrateLiveMessages(e.messages),m.retain(),b(m.getSnapshot());const L=m.subscribe(d=>{b(d)});return()=>{L(),m.release()}},[e.messages,m,p]);const k=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const L=e.agentType,d=await n(i,"chat_history",{agentType:L,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),y=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(y.messages)?y.messages:[],hasMore:y.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>Au(f,k),[k,f])}function _u(e,s){const{sendData:r}=Lt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,mr),i=o.useMemo(()=>Tu(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>Pi({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}function Ru(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Pu(e){return Ru(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Du=60;function Gn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ce,Y;const b=o.useRef(new Map),k=ur();cr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const L=nt.useMemo(()=>Os(e),[e.status,e.connectionState]),d=o.useMemo(()=>iu(e,s),[e,s]),y=Nu({isCliLike:d.isCli||d.isAcp}),v=Lu(e,{enabled:!!e.sessionId}),[h,C]=o.useState(y),P=e.tabKey,g=v.historyMessages,I=v.hasMoreHistory,j=v.historyError,w=vu(v.liveMessages,e.messages);o.useEffect(()=>{C(y)},[y,P]);const x=Math.max(0,w.length-h),$=ma(e),N=dr(e),T=Pu(e),M=ha(e),B=a||M,_=!!M,[S,O]=o.useState(!1);o.useEffect(()=>{const oe=d.targetEntry;N&&(!oe||oe.providerControls===void 0||oe.controlValues===void 0)&&k(N,{minFreshMs:3e4}).catch(()=>{})},[N,d.isAcp,(ce=d.targetEntry)==null?void 0:ce.providerControls,(Y=d.targetEntry)==null?void 0:Y.controlValues,k]);const G=o.useCallback(async()=>{if(!S){if(w.length>h){C(oe=>Math.min(w.length,oe+Du));return}O(!0);try{await v.loadHistoryPage()}finally{O(!1)}}},[v,S,w.length,h]),{allMessages:A,receivedAtMap:K}=o.useMemo(()=>{const oe=x>0?w.slice(-h):w;if(g.length===0){const Ne=no(cs(oe)),le={};return Ne.forEach((pe,ae)=>{const z=`${e.tabKey}:${Ns(pe,ae)}`;let ve=Gt(pe)||b.current.get(z)||0;ve||(ve=Date.now(),b.current.set(z,ve)),le[Ns(pe,ae)]=ve}),{allMessages:Ne,receivedAtMap:le}}const Q=wu(g,oe),te=no(cs([...Q,...oe])),ue={};return te.forEach((Ne,le)=>{const pe=`${e.tabKey}:${Ns(Ne,le)}`;let ae=Gt(Ne)||b.current.get(pe)||0;ae||(ae=Date.now(),b.current.set(pe,ae)),ue[Ns(Ne,le)]=ae}),{allMessages:te,receivedAtMap:ue}},[e.tabKey,x,g,w,h]),V=o.useMemo(()=>l.filter(oe=>oe.routeId===e.tabKey).sort((oe,Q)=>oe.timestamp-Q.timestamp),[l,e.tabKey]),U=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((L.isGenerating||e.status==="streaming")&&O(!1),e.status==="not_monitored"&&T)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(nr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{size:14})," Open ",$," 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"&&T)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(si,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{size:14})," Open ",$," 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"&&!S)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,T,i,c,S,w.length,$,L.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(Ti,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(ad,{messages:A,actionLogs:V,agentName:Ds(e)||$||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:L.isGenerating,contextKey:e.tabKey,receivedAtMap:K,onLoadMore:G,isLoadingMore:S,hasMoreHistory:I,hiddenLiveCount:x,loadError:j??void 0,emptyState:U,scrollToBottomRequestNonce:m}),f&&!d.isCliTerminal&&(()=>{var oe,Q;return t.jsx(tu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(oe=d.targetEntry)==null?void 0:oe.providerControls,controlValues:(Q=d.targetEntry)==null?void 0:Q.controlValues})})(),!d.isCliTerminal&&t.jsx(su,{contextKey:e.tabKey,panelLabel:$,isSending:n,isBusy:_,statusMessage:B,onSend:r,isActive:f})]})}let Di=hs;function $i(){return Di()}class $u{constructor(){qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let Ei=new $u;class Eu{sendPtyInput(s,r,n){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 ut=new Eu;function Ku(e){e.dashboardWS&&(Ei=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Di=e.useDaemonsHook)}function dt(e){return ma(e)}function gs(e){return Ni(e).join(" · ")}function Ki(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=_s(s==null?void 0:s.content);return r||(e.title?e.title:gs(e)||"No messages yet")}function Bi(e,s){const{isReconnecting:r,isConnecting:n}=Os(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Bu(e,s){const r=["Chat",...Ni(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ls(e){return Bi(e)||gs(e)}function Wu(e){return`${dt(e)} · ${Ki(e)}`}function Ou(e){const s=Ur(e),r=s?at(s):Ds(e);return`${dt(e)} — ${r||"Agent"}`}function Hu(e){return Ds(e)||"CLI"}function Wi(e){return Si(e)}function Oi(e){return e?`Remote · ${dt(e)||e.workspaceName||"Session"}`:"Remote"}function Uu({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var ce;const{ides:l}=hs(),u=o.useRef(null),{sendCommand:p,sendData:m}=Lt(),[f,b]=o.useState(""),[k,L]=o.useState(!1),[d,y]=o.useState(1),v=o.useRef(!1),h=o.useRef(0),C=o.useRef(!1),P=o.useRef(""),g=o.useRef(null),I=o.useRef(!1),j=o.useRef(null),w=e.tabKey,x=e.sessionId||"",$=e.daemonId||((ce=e.routeId)==null?void 0:ce.split(":")[0])||e.routeId||"",N=l.find(Y=>Y.id===$&&Y.type==="adhdev-daemon"),T=(N==null?void 0:N.terminalSizingMode)==="fit"?"fit":"measured",M=ha(e),B=i||M,_=.6,S=1.15,O=()=>{if(typeof window>"u")return 1;const Y=window.innerWidth||0;return Y<=360?.68:Y<=390?.74:Y<=430?.82:Y<=480?.9:1},G=()=>{var Y,oe;h.current=0,C.current=!1,P.current="",g.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),L(!1),(oe=(Y=r.current)==null?void 0:Y.reset)==null||oe.call(Y)},A=()=>{var Y,oe;h.current=0,C.current=!1,P.current="",g.current=null,I.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),L(!0),(oe=(Y=r.current)==null?void 0:Y.reset)==null||oe.call(Y)},K=()=>{var oe;if(j.current=null,!c)return;const Y=P.current;Y&&(P.current="",(oe=r.current)==null||oe.write(Y))},V=Y=>{Y&&(P.current+=Y,c&&j.current===null&&(j.current=requestAnimationFrame(K)))},U=(Y,oe=0,Q,te)=>{var ue,Ne,le,pe,ae;oe>0&&h.current>=oe||oe===0&&C.current||(h.current=oe,L(!0),typeof Q=="number"&&typeof te=="number"&&Q>0&&te>0&&((Ne=(ue=r.current)==null?void 0:ue.resize)==null||Ne.call(ue,Q,te)),(pe=(le=r.current)==null?void 0:le.reset)==null||pe.call(le),Y&&((ae=r.current)==null||ae.write(Y)))};return o.useEffect(()=>{G()},[x]),o.useEffect(()=>{var oe;if(!x)return;const Y=((oe=ut.onRuntimeEvent)==null?void 0:oe.call(ut,x,Q=>{if(!(!Q||Q.sessionId!==x)){if(Q.type==="runtime_snapshot"){if(!c){g.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows};return}U(Q.text||"",Q.seq||0,Q.cols,Q.rows);return}if(Q.type==="session_output"){C.current=!0,typeof Q.seq=="number"&&(h.current=Math.max(h.current,Q.seq)),k||L(!0),typeof Q.data=="string"&&V(Q.data);return}if(Q.type==="session_cleared"){if(!c){I.current=!0,P.current="",g.current=null;return}A()}}}))||(()=>{});return()=>{Y()}},[$,x,r,c,k]),o.useEffect(()=>{var oe,Q,te;if(!x)return;$&&((oe=ut.getState)==null?void 0:oe.call(ut,$))==="connected"&&(L(!0),(Q=ut.requestRuntimeSnapshot)==null||Q.call(ut,$,x).catch(()=>{}));const Y=(te=ut.onStateChange)==null?void 0:te.call(ut,(ue,Ne)=>{var le;ue!==$||Ne!=="connected"||(L(!0),(le=ut.requestRuntimeSnapshot)==null||le.call(ut,$,x).catch(()=>{}))});return()=>{Y==null||Y()}},[$,x,r]),o.useEffect(()=>{s&&G()},[s,w,r]),o.useEffect(()=>{b("")},[e.tabKey]),o.useEffect(()=>{const Y=()=>{v.current||y(O())};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),o.useEffect(()=>{var oe;if(!c){(oe=u.current)==null||oe.blur();return}I.current&&(I.current=!1,A());const Y=g.current;Y&&(g.current=null,U(Y.text,Y.seq,Y.cols,Y.rows)),P.current&&j.current===null&&(j.current=requestAnimationFrame(K)),requestAnimationFrame(()=>{var Q;(Q=r.current)==null||Q.bumpResize()})},[c]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const Y=oe=>{var te;const Q=oe.detail;Q!=null&&Q.sessionId&&Q.sessionId!==x||k&&((te=r.current)==null||te.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",Y),()=>{window.removeEventListener("adhdev:fit-cli-terminal",Y)}},[k,x,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:()=>{v.current=!0,y(Y=>Math.max(_,Number((Y-.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:()=>{v.current=!0,y(Y=>Math.min(S,Number((Y+.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/d}%`,height:`${100/d}%`,transform:`scale(${d})`,transformOrigin:"top left"},children:t.jsx(ii,{ref:r,readOnly:!k||!c,sizingMode:T,onInput:Y=>{k&&(m!=null&&m($,{type:"pty_input",sessionId:x,targetSessionId:x,data:Y})||p($,"pty_input",{targetSessionId:x,data:Y}).catch(console.error))}})})}),!k&&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.jsxs("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:u,type:"text",placeholder:B||`Send message to ${dt(e)}...`,value:f,disabled:!k||!c,onChange:Y=>b(Y.target.value),onPaste:Y=>{const oe=Y.clipboardData.getData("text");oe&&b(Q=>Q+oe),Y.preventDefault()},onKeyDown:Y=>{if(Y.key!=="Enter")return;if(Y.nativeEvent.isComposing){Y.preventDefault();return}Y.preventDefault();const oe=f.trim();!k||!oe||M||n(oe).then(Q=>{Q!==!1&&b("")})},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 Y=f.trim();!k||!Y||M||n(Y).then(oe=>{oe!==!1&&b("")})},disabled:!k||!c||wi({hasDraft:!!f.trim(),isBusy:!!M}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!M?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.trim()&&!M?{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:f.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),B&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:B})]})]})}function Fu({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 zu({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 xa({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(Jr,{size:n}):t.jsx(Vt,{size:n})})}function io({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function co({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=en(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 Vu({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:b,onShowAllHidden:k,onResetPanelsToMain:L,inboxOpen:d,onInboxOpenChange:y,hiddenOpen:v,onHiddenOpenChange:h,onOpenNewSession:C,actionShortcuts:P,notifications:g,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:w,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:N,p2pStates:T={}}=hs(),M=!!e&&tt(e)&&!Je(e),B=!!e&&Je(e),_=u||(e?ji(e)?"terminal":"chat":null),[S,O]=o.useState(!1),G=o.useRef(null),A=o.useRef(null),K=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",V=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",U=N.filter(z=>z.type==="adhdev-daemon"),ce=Object.values(T),Y=ce.filter(z=>z==="connected").length,oe=ce.filter(z=>z==="connecting"||z==="new"||z==="checking").length,te=r!=="connected"||U.length===0?null:oe>0&&Y===0?"P2P connecting...":Y>0&&s===0?"Waiting for IDE...":null,ue=o.useMemo(()=>g.filter(z=>!z.readAt),[g]),Ne=o.useMemo(()=>g.filter(z=>!!z.readAt),[g]),le=o.useMemo(()=>ue.slice(0,9),[ue]),pe=I;o.useEffect(()=>{if(!d)return;const z=ve=>{var ee;(ee=G.current)!=null&&ee.contains(ve.target)||y(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,y]),o.useEffect(()=>{if(!v)return;const z=ve=>{var ee;(ee=A.current)!=null&&ee.contains(ve.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[v,h]),o.useEffect(()=>{if(!v&&!d)return;const z=ve=>{if(!ve.altKey)return;const ee=ve.code.match(/^Digit([1-9])$/);if(!ee)return;const we=Number(ee[1])-1,re=v?f[we]:void 0,ie=d?le[we]:void 0;if(!(!re&&!ie)){if(ve.preventDefault(),ve.stopPropagation(),re){b==null||b(re),h(!1);return}ie&&(j(ie),y(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,v,d,le,h,y,j,b]);const ae=z=>{if(!z)return;const ve=a.find(ee=>ee.tabKey===z);ve&&(m==null||m(ve))};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(Vt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?dt(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:K,boxShadow:V}})})]}),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:K,boxShadow:V}}),te&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",te]}),C&&t.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx($l,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||B||!Je(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:gs(e)||dt(e),children:dt(e)}),(M||B)&&l&&t.jsxs(t.Fragment,{children:[M&&p&&_&&t.jsx(xa,{mode:_,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:B?"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(Nt,{size:14})})]}),!Je(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(aa,{size:14})}),!M&&!Je(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Tt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${S?" is-drop-target":""}`,ref:A,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),O(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",O(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||O(!1)},onDrop:z=>{const ve=z.dataTransfer.getData("text/tab-key");z.preventDefault(),O(!1),ae(ve)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(ri,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),v&&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(io,{value:P==null?void 0:P.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&&k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{k(),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(io,{value:P==null?void 0:P.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:dt(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:()=>{b==null||b(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:dt(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,gs(z)]})]},z.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>y(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Zr,{size:16}),pe>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:pe})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ue.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ue.map(z=>t.jsx(co,{notification:z,shortcutIndex:le.indexOf(z)>=0?le.indexOf(z)+1:void 0,onOpen:()=>j(z),onMarkRead:()=>w(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>$(z.id)},z.id))]}),Ne.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Ne.map(z=>t.jsx(co,{notification:z,onOpen:()=>j(z),onMarkRead:()=>w(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>$(z.id)},z.id))]}),g.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function yt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Gu(e,s){return String(e||"")!==String(s||"")}function qu(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
31
|
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!xi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function Yu(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 Hi(e,s={}){return Yu(qu(e,s),s.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function ba(e){return e?"Resuming saved history…":"Starting fresh…"}function Xu(){return"Start fresh"}function Ui(e,s=!1){return e==="cli"?zr(s):e==="ide"?"Start IDE":"Start ACP session"}function Fi(e,s=!1){return e==="cli"?ba(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Qu(){return"Recover hosted runtime"}function Ju(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Zu(){return"Open saved history"}function em(){return"Saved History"}function ga(){return"Use saved history when you want continuity in the same provider conversation."}function tm(){return"No saved history found yet."}function sm(){return"Refresh saved history"}function rm(){return"Refreshing saved history…"}function ds(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function us(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 Es(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ya(e){return`Resume saved history with ${e}?`}function va(){return"Review or change the target workspace before resuming saved history."}function nm(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 wa({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:y,onResumeSavedSession:k}){var w;const T=s.find(x=>x.id===e.routeId),d=(T==null?void 0:T.chats)||[],g=(w=T==null?void 0:T.activeChat)==null?void 0:w.id,v=tt(e)&&!Je(e),[h,C]=o.useState(()=>yt()),P=l||h,b=x=>{if(u){u(x);return}C(x)},I=o.useMemo(()=>Hi(a,{textQuery:P.textQuery,workspaceQuery:P.workspaceQuery,modelQuery:P.modelQuery,resumableOnly:P.resumableOnly,sortMode:P.sortMode}),[P.modelQuery,P.resumableOnly,P.sortMode,P.textQuery,P.workspaceQuery,a]),j=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:v?em():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ou(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ga()})]}),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(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&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"}),v?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:P.textQuery,onChange:x=>b({...P,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:P.workspaceQuery,onChange:x=>b({...P,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:P.modelQuery,onChange:x=>b({...P,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:P.sortMode,onChange:x=>b({...P,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:P.resumableOnly,onChange:x=>b({...P,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const $=e.providerSessionId===x.providerSessionId,N=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{N||!k||k(x)},disabled:N,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${N?"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 ${$?"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:nm(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",bs(x.summaryMetadata)?` · ${bs(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"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 ${g===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 ${g===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),"..."]}),g===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)),(v&&!i&&I.length===0||!v&&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(Wl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":tm():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:rm()})})]}),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:y,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(Ws,{size:13})," ",v?sm():"Refresh History"]})})})]})]});return typeof document>"u"?j:rr.createPortal(j,document.body)}const lo={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 zi({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=lo[n.type]||lo.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(Nt,{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 am=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function om(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function im(e){return e.sessionId||e.instanceId||e.agentType}function wn(e,s){return e||s}function uo(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 Vi(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Mt(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 ja(e,s,r={}){return cm(e,s,Gi(e,r))}function cm(e,s,r={}){var f,y,k,T,d,g;const n=[],a=r.machineName,i=r.connectionState,c=om(e),l=Sd(e.type,{agentName:e.cliName}),u=tt(e)||Je(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var h,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||at(v.providerType),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((h=v.activeChat)==null?void 0:h.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],m=am(e);if(m){const v=e.sessionId||e.instanceId,h=l,C=(f=e.activeChat)==null?void 0:f.activeModal,P=C&&Array.isArray(C.buttons)&&C.buttons.length>0,b=jt((y=e.activeChat)==null?void 0:y.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||jt((d=(T=e.agents)==null?void 0:T[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const w=(g=e.activeChat)==null?void 0:g.id,x=e.chats;if(w&&Array.isArray(x)&&x.length>0){const _=x.find(S=>S.id===w||S.id&&String(S.id)===String(w));_!=null&&_.title&&String(_.title).trim()&&(j=String(_.title).trim())}const $=(tt(e)||Je(e),e.type),N=(tt(e)||Je(e))&&Ja(j,h,$)?"":j,L=I.messages||[],M=uo(s,[e.id,v]),B=ao(L,M);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:b,title:N,messages:[...L,...B],resume:e.resume,hostIdeType:!tt(e)&&!Je(e)?e.type:void 0,workspaceName:c,displayPrimary:N||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:P?C.buttons:void 0,modalMessage:P?C.message:void 0,streamSource:"native",tabKey:wn(v,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Je(e)))return n;for(const v of p){const h=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=Nd(v),P=im(v),b=`${e.id}:${P}`,I=v.title&&String(v.title).trim()||"",j=Ja(I,v.agentName,v.agentType)?"":I,w=v.messages||[],x=uo(s,[b,v.sessionId,v.instanceId]),$=ao(w,x);(v.transport==="cdp-webview"||v.sessionId||v.providerSessionId||w.length>0||$.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:C,title:j,messages:[...w,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||v.agentName||u,displaySecondary:`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,modalButtons:h?v.activeModal.buttons:void 0,modalMessage:h?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wn(v.sessionId||v.instanceId,b),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,sessionCapabilities:e.sessionCapabilities,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:wn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function lm(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 dm(e,s){const r=lm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const qi=[{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:"🏄"}],Yi=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Xi=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],um=qi,mm=Yi,pm=Xi;function ys(...e){return il(cl(e))}function fm({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ys("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 Qi({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(fm,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ys("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:ys("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 Ji({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ys("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 hm={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"},xm={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function bm({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ys("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",hm[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:xm[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 gm={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"},ym={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function vm({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ys("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",gm[e],r),children:[t.jsx("span",{className:ys("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",ym[e])}),n]})}const qn="adhdev:themechange";function wm(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ks(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ss(e){return e==="system"?wm():e}function Zi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(qn,{detail:{preference:e,theme:s}}))}function jm(){const e=ks(),s=Ss(e);Zi(s),Pr(e,s)}function ka(){const[e,s]=o.useState(ks),[r,n]=o.useState(()=>Ss(ks()));o.useEffect(()=>{Zi(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),Pr("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:ks()),n(f==="dark"||f==="light"?f:Ss(ks()))},l=u=>{if(u.key!=="theme")return;const p=ks(),m=Ss(p);s(p),n(m)};return window.addEventListener(qn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(qn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ss(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Pr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ss(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Pr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const mo={dark:"Dark",light:"Light",system:"System"};function km({collapsed:e}){const{preference:s,cycleTheme:r}=ka(),n=s==="dark"?t.jsx(Hl,{size:16}):s==="light"?t.jsx(Ol,{size:16}):t.jsx(Ul,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${mo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:mo[s]})]})}function as({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 Sm({onPrefChange:e}){const[s,r]=Dd(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zr,{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(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{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(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nr,{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 Vr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Nm(e,s){const r=Vr(e),n=Vr(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 ec(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function er(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Nm(r,s)>=0)return!1;const n=Vr(r),a=Vr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Cm(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function jn(e,s){return e instanceof Error?e.message:s}function Im({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(Ji,{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(Mm,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function po({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 rr.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 Am(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...um,...mm,...pm].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 Mm({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,_;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,y]=o.useState("idle"),[k,T]=o.useState(""),d=e.version||null,g=((B=e.machine)==null?void 0:B.platform)||((_=e.system)==null?void 0:_.platform)||"",v=Mt(e,{fallbackId:e.id}),h=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",C=s.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),P=s.filter(S=>S.daemonId===e.id&&S.transport==="pty"),b=s.filter(S=>S.daemonId===e.id&&S.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const S=Cm(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(c("done"),u(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(c("done"),u(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(S.error||"Upgrade failed"))}catch(S){c("error"),u(jn(S,"Connection lost during upgrade"))}}},w=async()=>{if(m(null),!!n){y("loading");try{await n(e.id),y("done"),T("Machine disconnected.")}catch(S){y("error"),T(jn(S,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){y("loading");try{await a(e.id),y("done"),T("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){y("error"),T(jn(S,"Failed to revoke token"))}}},$="0.8.74",N=ec(e,$),L=er(e,$),M=C.length+P.length+b.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:v}),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] ${N?"":"bg-bg-secondary"}`,style:N?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!N&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&N&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${$}`}`}`}),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(vm,{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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(S=>{const O=Am(S.type),G=S.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:O.icon}),t.jsx("span",{children:O.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..."})]},S.id)}),P.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:S.cliName||"CLI"})]},S.id)),b.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:S.cliName||"ACP"})]},S.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&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:k||l})]}),p==="disconnect"&&t.jsx(po,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
32
|
+
`).includes(a)))}function Yu(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 Hi(e,s={}){return Yu(qu(e,s),s.sortMode||"recent")}function zr(e){return e?"Resume saved history":"Start fresh"}function ba(e){return e?"Resuming saved history…":"Starting fresh…"}function Xu(){return"Start fresh"}function Ui(e,s=!1){return e==="cli"?zr(s):e==="ide"?"Start IDE":"Start ACP session"}function Fi(e,s=!1){return e==="cli"?ba(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Qu(){return"Recover hosted runtime"}function Ju(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Zu(){return"Open saved history"}function em(){return"Saved History"}function ga(){return"Use saved history when you want continuity in the same provider conversation."}function tm(){return"No saved history found yet."}function sm(){return"Refresh saved history"}function rm(){return"Refreshing saved history…"}function ds(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function us(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 Es(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ks(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ya(e){return`Resume saved history with ${e}?`}function va(){return"Review or change the target workspace before resuming saved history."}function nm(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 wa({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:b,onResumeSavedSession:k}){var w;const L=s.find(x=>x.id===e.routeId),d=(L==null?void 0:L.chats)||[],y=(w=L==null?void 0:L.activeChat)==null?void 0:w.id,v=tt(e)&&!Je(e),[h,C]=o.useState(()=>yt()),P=l||h,g=x=>{if(u){u(x);return}C(x)},I=o.useMemo(()=>Hi(a,{textQuery:P.textQuery,workspaceQuery:P.workspaceQuery,modelQuery:P.modelQuery,resumableOnly:P.resumableOnly,sortMode:P.sortMode}),[P.modelQuery,P.resumableOnly,P.sortMode,P.textQuery,P.workspaceQuery,a]),j=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:v?em():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ou(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ga()})]}),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(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&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"}),v?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:P.textQuery,onChange:x=>g({...P,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:P.workspaceQuery,onChange:x=>g({...P,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:P.modelQuery,onChange:x=>g({...P,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:P.sortMode,onChange:x=>g({...P,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:P.resumableOnly,onChange:x=>g({...P,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const $=e.providerSessionId===x.providerSessionId,N=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{N||!k||k(x)},disabled:N,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${N?"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 ${$?"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:nm(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",bs(x.summaryMetadata)?` · ${bs(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"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 ${y===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 ${y===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),"..."]}),y===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)),(v&&!i&&I.length===0||!v&&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(Wl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":tm():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:rm()})})]}),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:b,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(Ws,{size:13})," ",v?sm():"Refresh History"]})})})]})]});return typeof document>"u"?j:rr.createPortal(j,document.body)}const lo={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 zi({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=lo[n.type]||lo.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(Nt,{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 am=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function om(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function im(e){return e.sessionId||e.instanceId||e.agentType}function wn(e,s){return e||s}function uo(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 Vi(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Mt(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 ja(e,s,r={}){return cm(e,s,Gi(e,r))}function cm(e,s,r={}){var f,b,k,L,d,y;const n=[],a=r.machineName,i=r.connectionState,c=om(e),l=Sd(e.type,{agentName:e.cliName}),u=tt(e)||Je(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var h,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||at(v.providerType),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((h=v.activeChat)==null?void 0:h.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],m=am(e);if(m){const v=e.sessionId||e.instanceId,h=l,C=(f=e.activeChat)==null?void 0:f.activeModal,P=C&&Array.isArray(C.buttons)&&C.buttons.length>0,g=jt((b=e.activeChat)==null?void 0:b.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||jt((d=(L=e.agents)==null?void 0:L[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const w=(y=e.activeChat)==null?void 0:y.id,x=e.chats;if(w&&Array.isArray(x)&&x.length>0){const _=x.find(S=>S.id===w||S.id&&String(S.id)===String(w));_!=null&&_.title&&String(_.title).trim()&&(j=String(_.title).trim())}const $=(tt(e)||Je(e),e.type),N=(tt(e)||Je(e))&&Ja(j,h,$)?"":j,T=I.messages||[],M=uo(s,[e.id,v]),B=ao(T,M);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:g,title:N,messages:[...T,...B],resume:e.resume,hostIdeType:!tt(e)&&!Je(e)?e.type:void 0,workspaceName:c,displayPrimary:N||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:P?C.buttons:void 0,modalMessage:P?C.message:void 0,streamSource:"native",tabKey:wn(v,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Je(e)))return n;for(const v of p){const h=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=Nd(v),P=im(v),g=`${e.id}:${P}`,I=v.title&&String(v.title).trim()||"",j=Ja(I,v.agentName,v.agentType)?"":I,w=v.messages||[],x=uo(s,[g,v.sessionId,v.instanceId]),$=ao(w,x);(v.transport==="cdp-webview"||v.sessionId||v.providerSessionId||w.length>0||$.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:C,title:j,messages:[...w,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||v.agentName||u,displaySecondary:`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,modalButtons:h?v.activeModal.buttons:void 0,modalMessage:h?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:wn(v.sessionId||v.instanceId,g),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,sessionCapabilities:e.sessionCapabilities,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:wn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function lm(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 dm(e,s){const r=lm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const qi=[{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:"🏄"}],Yi=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Xi=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],um=qi,mm=Yi,pm=Xi;function ys(...e){return il(cl(e))}function fm({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ys("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 Qi({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(fm,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ys("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:ys("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 Ji({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ys("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 hm={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"},xm={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function bm({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ys("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",hm[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:xm[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 gm={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"},ym={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function vm({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ys("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",gm[e],r),children:[t.jsx("span",{className:ys("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",ym[e])}),n]})}const qn="adhdev:themechange";function wm(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ks(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ss(e){return e==="system"?wm():e}function Zi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(qn,{detail:{preference:e,theme:s}}))}function jm(){const e=ks(),s=Ss(e);Zi(s),Pr(e,s)}function ka(){const[e,s]=o.useState(ks),[r,n]=o.useState(()=>Ss(ks()));o.useEffect(()=>{Zi(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),Pr("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:ks()),n(f==="dark"||f==="light"?f:Ss(ks()))},l=u=>{if(u.key!=="theme")return;const p=ks(),m=Ss(p);s(p),n(m)};return window.addEventListener(qn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(qn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ss(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Pr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ss(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Pr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const mo={dark:"Dark",light:"Light",system:"System"};function km({collapsed:e}){const{preference:s,cycleTheme:r}=ka(),n=s==="dark"?t.jsx(Hl,{size:16}):s==="light"?t.jsx(Ol,{size:16}):t.jsx(Ul,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${mo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:mo[s]})]})}function as({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 Sm({onPrefChange:e}){const[s,r]=Dd(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zr,{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(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{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(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(nr,{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 Vr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Nm(e,s){const r=Vr(e),n=Vr(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 ec(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function er(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Nm(r,s)>=0)return!1;const n=Vr(r),a=Vr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Cm(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function jn(e,s){return e instanceof Error?e.message:s}function Im({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(Ji,{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(Mm,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function po({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 rr.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 Am(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...um,...mm,...pm].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 Mm({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,_;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,b]=o.useState("idle"),[k,L]=o.useState(""),d=e.version||null,y=((B=e.machine)==null?void 0:B.platform)||((_=e.system)==null?void 0:_.platform)||"",v=Mt(e,{fallbackId:e.id}),h=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",C=s.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),P=s.filter(S=>S.daemonId===e.id&&S.transport==="pty"),g=s.filter(S=>S.daemonId===e.id&&S.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const S=Cm(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(c("done"),u(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(c("done"),u(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(S.error||"Upgrade failed"))}catch(S){c("error"),u(jn(S,"Connection lost during upgrade"))}}},w=async()=>{if(m(null),!!n){b("loading");try{await n(e.id),b("done"),L("Machine disconnected.")}catch(S){b("error"),L(jn(S,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){b("loading");try{await a(e.id),b("done"),L("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){b("error"),L(jn(S,"Failed to revoke token"))}}},$="0.8.75",N=ec(e,$),T=er(e,$),M=C.length+P.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:v}),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] ${N?"":"bg-bg-secondary"}`,style:N?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!N&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&N&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${$}`}`}`}),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(vm,{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:[I&&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 ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&M>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(S=>{const O=Am(S.type),G=S.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:O.icon}),t.jsx("span",{children:O.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..."})]},S.id)}),P.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:S.cliName||"CLI"})]},S.id)),g.map(S=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:S.cliName||"ACP"})]},S.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&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:k||l})]}),p==="disconnect"&&t.jsx(po,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
33
33
|
|
|
34
34
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
35
|
|
|
@@ -40,7 +40,7 @@ This will:
|
|
|
40
40
|
• Delete the machine registration
|
|
41
41
|
• Require restarting ADHDev on that machine
|
|
42
42
|
|
|
43
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Tm=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Lm(){const{preference:e,setPreference:s}=ka();return t.jsx("div",{className:"flex gap-2",children:Tm.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 _m(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 Rm(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function kn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function fo(e){const{r:s,g:r,b:n}=Rm(e);return .2126*kn(s)+.7152*kn(r)+.0722*kn(n)}function ho(e,s){const r=fo(e),n=fo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function tc(e){const s=_m(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ho(s,r)>=ho(s,n)?r:n}const Yn={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},Xn={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},Pm=[{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"}}}],sc="adhdev-chat-theme",rc="adhdev-chat-theme-custom";function Dr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(sc)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(rc);if(s){const r=JSON.parse(s);return{...e==="dark"?Yn:Xn,...r[e]}}}catch{}return e==="dark"?Yn:Xn}function jr(e,s){try{localStorage.setItem(rc,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(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 Gr(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 Dm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function tr(e,s){var a;const r=(a=Dm[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",tc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function ms(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",tc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 Sa(){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 $m(e){try{localStorage.setItem(sc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ps()?"dark":"light";ms(Et(s))}else Sa(),tr(e,ps()?"dark":"light")}function Em(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ps()?"dark":"light";ms(Et(s))}else Sa(),tr(e,ps()?"dark":"light")}function ps(){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 Vs({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 Km({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"?jr(p,f):jr(f,p),ms(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(Vs,{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(Vs,{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(Vs,{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(Vs,{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(Vs,{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?Yn:Xn,u=Et(e?"light":"dark");e?jr(c,u):jr(u,c),a(c),ms(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 Bm(){const[e,s]=o.useState(Dr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(ps());const u=new MutationObserver(()=>{const f=ps();n(f);const y=Dr();y==="custom"?ms(Et(f?"dark":"light")):tr(y,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ps();n(f);const y=Dr();y==="custom"?ms(Et(f?"dark":"light")):tr(y,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"?ms(Et(r?"dark":"light")):(Sa(),tr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=u=>{s(u),$m(u)},l=[...Pm,{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(Km,{dark:r,onColorsChange:u=>i(u)})]})}const nc="adhdev_mobileDashboardMode_v1";function ac(){try{return localStorage.getItem(nc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Wm(e){try{localStorage.setItem(nc,e)}catch{}}function Om(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(ac()==="chat")},[]),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vt,{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),Wm(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function Hm(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 Um(e,s){const{sendData:r}=Lt(),{injectEntries:n,getIdes:a}=Wr(),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=>Zt.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(y=>y.id===u),f=Hm(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 Fm=4e3;function oc(e,s){const{sendData:r}=Lt(),[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=Zt.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)},Fm):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 zm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ic(e){const{sendData:s}=Lt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=zm(e);if(!a||!e.sessionId||!s){n({});return}const i=Zt.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}),Ts.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 cc="adhdev_hiddenTabs";function Vm(){try{const e=localStorage.getItem(cc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ws(e){try{localStorage.setItem(cc,JSON.stringify([...e]))}catch{}}function Gm(){const[e,s]=o.useState(Vm),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),ws(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),ws(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),ws(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return ws(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const y=new Set(f);for(const k of m)y.add(k);return ws(y),y})},[]),l=o.useCallback((p,m)=>{s(f=>{const y=new Set(f);for(const k of m)y.delete(k);return ws(y),y})},[]),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 xo(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 qm(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=xo(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>xo(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function lc(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 Ym(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))lc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Xm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ed()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Wi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Bd(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 Qm(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 Sn(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 Jm(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function bo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Jm(_s(r.content)):"";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 Zm(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||""),bo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),bo(r.activeChat)].join(":"))].join("|")}function ep(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 tp(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 sp(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 rp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of os({routeId:n.routeId}))r.set(i,a);for(const i of os({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of os({tabKey:n.tabKey}))r.set(i,n)}return r}function np(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function ap(e){const s=np(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=_s(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function op({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Qm(e),[e]),c=o.useMemo(()=>Vi(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),y=o.useMemo(()=>{const b=new Map,I=[];for(const $ of i){const{connectionState:N="new",machineName:L}=Gi($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),M=tp($,r),B=Zm($),_=m.current.get($.id);if(_&&_.ide===$&&_.sourceSignature===B&&_.connectionState===N&&_.machineName===L&&sp(_.localRefs,M)){b.set($.id,_),I.push(..._.conversations);continue}const S=ja($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),O={ide:$,sourceSignature:B,connectionState:N,machineName:L,localRefs:M,conversations:S};b.set($.id,O),I.push(...S)}m.current=b;const j=new Map,w=$=>{const N=ap($),L=f.current.get($.tabKey);if(L&&L.signature===N)return j.set($.tabKey,L),L.timestamp;const M={signature:N,timestamp:Ii($)||(L==null?void 0:L.timestamp)||0};return j.set($.tabKey,M),M.timestamp},x=[...I].sort(($,N)=>Ai($,N,w));return f.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const b=ep(y,n);return Sn(l.current,b)?l.current:(l.current=b,b)},[y,n]),T=o.useMemo(()=>{const b=new Map,I=Array.from(new Set(k.map(j=>j.routeId)));for(const j of I){const w=Kt(k,j);w&&b.set(j,w)}return b},[k]),d=o.useMemo(()=>{const b=new Map;for(const I of k){const j=T.get(I.routeId),w=I.streamSource==="native"&&j?j:I;for(const x of os({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))b.set(x,w)}return b},[k,T]),g=o.useMemo(()=>rp(k,T),[k,T]),v=o.useCallback(b=>{if(b)return d.get(b)},[d]),h=o.useCallback(b=>{if(b)return g.get(b)},[g]),C=o.useMemo(()=>{const b=k.filter(I=>!a.has(I.tabKey));return Sn(u.current,b)?u.current:(u.current=b,b)},[k,a]),P=o.useMemo(()=>{const b=C.map(I=>I.tabKey);return Sn(p.current,b)?p.current:(p.current=b,b)},[C]);return{chatIdes:i,conversations:k,visibleConversations:C,visibleTabKeys:P,resolveConversationBySessionId:v,resolveConversationByTarget:h}}function ip({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 cp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=lt.onToast(u=>{r(m=>m.some(y=>y.message===u.message&&u.timestamp-y.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=lt.onSystemMessage((u,p)=>{var k,T;const m=a(u),f=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),y=!!(m&&(m.status==="waiting_approval"||(T=m.modalButtons)!=null&&T.length||m.modalMessage));f&&y||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=lt.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(y=>{var k;return!(y.role==="system"&&((k=y._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Ei.on("status_event",c=>{lt.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var g;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 y=Number(u.buttonIndex),k=u.button||((g=m==null?void 0:m.modalButtons)==null?void 0:g[y])||"Approve",T=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T);s(f,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(y)&&{buttonIndex:y},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 lp="adhdev_dashboardLayout_v1",dp="adhdev_dashboardDockview_v1",up="adhdev_dashboardDockviewHiddenRestore_v1",Gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Na(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function dc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function uc(e){return`${lp}:${e}`}function mp(e){const s=uc(e);return Na(s,null)}function pp(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=uc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function mc(e){return`${dp}:${e}`}function fp(e){const s=mc(e);return Na(s,null)}function hp(e,s){try{const r=mc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function pc(e){return`${up}:${e}`}function xp(e){const s=pc(e);return Na(s,{})}function bp(e,s){try{const r=pc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function gp(){return{groupAssignments:[...Gs.groupAssignments],focusedGroup:Gs.focusedGroup,groupActiveTabIds:{...Gs.groupActiveTabIds},groupTabOrders:{...Gs.groupTabOrders},groupSizes:[...Gs.groupSizes]}}function yp(){const[e]=o.useState(()=>dc(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,y]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,T]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const g=mp(e)??gp();r(new Map(g.groupAssignments)),a(g.focusedGroup),c(g.groupActiveTabIds),u(g.groupTabOrders),m(g.groupSizes),T(!0)},[k,e]);return o.useEffect(()=>{k&&pp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const g=window.matchMedia("(max-width: 767px)"),v=h=>y(h.matches);return g.addEventListener("change",v),()=>g.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function vp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function wp({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:y,handleRefreshHistory:k}){const T=o.useRef(!1),d=o.useRef(!1),g=o.useRef(null),v=o.useRef(!1);o.useEffect(()=>{if(!e||T.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const C=n.get(h.tabKey)??0;c(P=>({...P,[C]:h.tabKey})),l(C),T.current=!0,d.current=!0,g.current!=null&&(window.clearTimeout(g.current),g.current=null),u(P=>{const b=new URLSearchParams(P);return b.delete("activeTab"),b},{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(T.current){d.current=!0;return}if(g.current==null)return g.current=window.setTimeout(()=>{g.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{g.current!=null&&(window.clearTimeout(g.current),g.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){v.current=!1;return}if(!m||v.current||f)return;const h=y.find(C=>C.id===m.routeId);h&&(!h.chats||h.chats.length===0||vp(h.chats,m))&&(v.current=!0,k())},[p,m,f,y,k]),o.useEffect(()=>{if(!m)return;let h=null,C=0,P=-1,b=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){C<18&&(C+=1,h=requestAnimationFrame(I));return}let w=0;for(const x of j)x.scrollTop=x.scrollHeight,w+=x.scrollHeight;w===P?b+=1:(b=0,P=w),C+=1,!(b>=2||C>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function jp({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),y=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!tt(v)&&!Je(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const h=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===v?h:Kt(i,v)},[i,u,a]),T=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{y&&(p({routeId:y.routeId,tabKey:to(y)}),f(y),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,y]);const d=o.useCallback(v=>{v&&(p({routeId:v.routeId,tabKey:to(v)}),f(v))},[]),g=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:T,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:g}}function Nn(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=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function go({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(g){console.error("Launch failed",g)}},[e]),y=o.useCallback(async(d,g)=>{try{const v=d||(s==null?void 0:s.daemonId)||"",h=await e(v,"switch_chat",{id:g,sessionId:g,...As(s)}),C=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?zs(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?zs(a,`⚠️ Switch error: ${C}`):zs(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),zs(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=ir(s);await e(d,"new_chat",{...As(s)}),c(g=>({...g,[s.tabKey]:Date.now()})),i(g=>({...g,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),T=o.useCallback(async()=>{var d,g;if(!(!s||p)){m(!0);try{const v=ir(s),h=async()=>e(v,"list_chats",{forceExpand:!0,...As(s)});let C=await h(),P=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);Nn(P,s)&&(await new Promise(b=>setTimeout(b,450)),C=await h(),P=(C==null?void 0:C.chats)||((g=C==null?void 0:C.result)==null?void 0:g.chats)),C!=null&&C.success&&Array.isArray(P)&&(n(s.routeId,P),Nn(P,s)&&!Nn(r,s)&&zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:y,handleNewChat:k,handleRefreshHistory:T}}function kp(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 Sp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function yo(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 kr(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 vo(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 Np(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 Cp(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 wo(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 jo(e){return Array(e).fill(100/e)}function Ip({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(()=>kr(e,p),[e,p]),y=f.assignments,k=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),T=k>1,d=o.useCallback((b,I)=>{s(j=>{const w=new Map(kr(j,p).assignments);return I===0?w.delete(b):w.set(b,I),w}),n(j=>({...j,[I]:b})),r(I)},[s,p,n,r]),g=o.useCallback(b=>{s(I=>{const j=kr(I,p).assignments,w=new Map;for(const[x,$]of j)$!==b&&($>b?w.set(x,$-1):w.set(x,$));return w}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(b,1);const w=j.reduce((x,$)=>x+$,0);return w>0?j.map(x=>x/w*100):[]}),r(0)},[s,p,c,r]),v=o.useCallback((b,I)=>{I.preventDefault();const j=m.current;if(!j)return;const w=I.clientX,x=j.offsetWidth,$=i.length===k?[...i]:jo(k),N=M=>{const _=(M.clientX-w)/x*100,S=[...$];S[b]=Math.max(15,$[b]+_),S[b+1]=Math.max(15,$[b+1]-_),c(S)},L=()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",L)},[i,k,c]),h=o.useCallback((b,I,j)=>{if(k>=4)return;const w=j==="left"?I:I+1;s(x=>{const $=kr(x,p).assignments,N=new Map;for(const L of u){const M=$.get(L.tabKey)??0,B=M>=w?M+1:M;B>0&&N.set(L.tabKey,B)}return w>0&&N.set(b,w),N}),c(x=>{const $=x.length===k?[...x]:jo(k),N=$[I]??100/k,L=Math.max(15,N/2),M=Math.max(15,N/2),B=[...$];B[I]=L,B.splice(w,0,M);const _=B.reduce((S,O)=>S+O,0);return B.map(S=>S/_*100)}),n(x=>{const $=wo(x,w);return $[w]=b,$}),a(x=>{const $=wo(x,w);return $[w]=[b],$}),r(w)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{kp(e,y)||s(y)},[e,y,s]),o.useEffect(()=>{const{mapping:b,usedGroups:I}=f;n(j=>{const w=vo(j,b);return yo(j,w)?j:w}),a(j=>{const w=vo(j,b);return yo(j,w)?j:w}),r(j=>{const w=l?0:Np(j,I,b);return j===w?j:w}),c(j=>{const w=l?[]:Cp(j,I,f.groupCount);return Sp(j,w)?j:w})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const b=Array.from({length:k},()=>[]);for(const I of u){const j=y.get(I.tabKey)??0,w=Math.min(j,k-1);b[w].push(I)}return b},[u,y,k]),P=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:y,numGroups:k,isSplitMode:T,groupedConvs:C,moveTabToGroup:d,closeGroup:g,handleResizeStart:v,splitTabRelative:h,clearAllSplits:P}}function Ap({ides:e,sendDaemonCommand:s}){const r="0.8.74",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ec(m,r)).sort((m,f)=>Number(er(f,r))-Number(er(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>er(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,y;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(f=k==null?void 0:k.result)!=null&&f.upgraded||(y=k==null?void 0:k.result)!=null&&y.success?u(T=>({...T,[m]:"done"})):u(T=>({...T,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Qn="adhdev_dashboard_notifications_v1",Ca=80;function $r(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function qr(e){return{...e,createdAt:$r(e.createdAt),updatedAt:$r(e.updatedAt,e.createdAt),lastEventAt:$r(e.lastEventAt,e.updatedAt||e.createdAt)}}function Mp(e){const s=di(e);return s==="unknown:"?e.id:s}function Tp(e){return[e.type,li(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Lp(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=$r(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Tp({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(qr({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Si(a),preview:ru(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function _p(e,s,r=Ca){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,qr(i));for(const i of s){const c=qr(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=Mp(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function Rp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Pp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function Dp(e,s,r=Date.now()){return e.map(n=>Or(n,s)?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function $p(e,s){return e.filter(r=>r.id!==s)}function Ep(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Kp(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=os(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function Bp(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Qn),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>qr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function Wp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,Ca);if(s.length===0){window.localStorage.removeItem(Qn);return}window.localStorage.setItem(Qn,JSON.stringify(s))}catch{}}function Op(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 Hp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Ca}=e,a=o.useMemo(()=>Lp(s,r),[s,r]),[i,c]=o.useState(()=>Bp());o.useEffect(()=>{c(k=>{const T=_p(k,a,n);return Op(k,T)?k:T})},[a,n]),o.useEffect(()=>{Wp(i)},[i]);const l=o.useMemo(()=>Ep(i),[i]),u=o.useMemo(()=>Kp(i),[i]),p=o.useCallback((k,T)=>{c(d=>Rp(d,k,T))},[]),m=o.useCallback(k=>{c(T=>Pp(T,k))},[]),f=o.useCallback((k,T)=>{c(d=>Dp(d,k,T))},[]),y=o.useCallback(k=>{c(T=>$p(T,k))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:f,deleteNotification:y}}function fc(){return"select_session"}function Up(){return"open_panel"}function Fp({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function zp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ko(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function So(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ia(e){return e instanceof Error?e.message:String(e||"")}function No(e){const s=Ia(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Co(e,s){const r=Ia(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function rn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),y=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const k=o.useCallback(async v=>{if(!s)return!1;const h=v.trim(),C=ha(s);if(Fp({hasMessage:!!h,blockedMessage:C,sendInFlight:f.current}))return C&&m(C),!1;const P=Date.now(),b={tabKey:s.tabKey,message:h,timestamp:P};if(zp(y.current,b))return m(null),!0;f.current=!0,u(!0),m(null),y.current=b;const I=`${P}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:P,_localId:I},w=!0;r(x=>({...x,[b.tabKey]:[...x[b.tabKey]||[],j]}));try{const x=ir(s);if(!x)return y.current=ko(y.current,b),w&&r(L=>({...L,[b.tabKey]:(L[b.tabKey]||[]).filter(M=>M._localId!==I)})),m("Unable to send message right now."),!1;const $=await e(x,"send_chat",{message:h,...As(s)}),N=So($);if(w&&(N!=null&&N.deduplicated))return r(L=>({...L,[b.tabKey]:(L[b.tabKey]||[]).filter(M=>M._localId!==I)})),m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return setTimeout(()=>{const L=Date.now()-6e4;r(M=>{const B=M[b.tabKey];if(!B)return M;const _=B.filter(S=>S.timestamp>L);return _.length===B.length?M:{...M,[b.tabKey]:_}})},6e4),m(null),!0}catch(x){const $=Ia(x);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",x),y.current=ko(y.current,b),r(N=>({...N,[b.tabKey]:(N[b.tabKey]||[]).filter(L=>L._localId!==I)})),m(ju(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),T=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(v){console.error("Relaunch failed",v)}},[s,e]),d=o.useCallback(async v=>{if(s)try{const C=(s.modalButtons||[]).indexOf(v),P=v.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(P),I=ir(s);if(!I)return;const j=await e(I,"resolve_action",{button:v,action:b?"approve":"reject",...C>=0&&{buttonIndex:C},...As(s)}),w=So(j);w.success||n(x=>[...x,{routeId:s.tabKey,text:Co(v,w==null?void 0:w.error),timestamp:Date.now()}])}catch(h){No(h)||console.error("[ModalButton] Error:",h),n(C=>[...C,{routeId:s.tabKey,text:No(h)?Co(v,h):`❌ **${v}** error`,timestamp:Date.now()}])}},[s,e,n]),g=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Up(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(v){console.error("Focus agent failed",v)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:k,handleRelaunch:T,handleModalButton:d,handleFocusAgent:g}}const Aa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:y,actionLogs:k,userName:T,scrollToBottomRequestNonce:d,isInputActive:g=!0}){const v=ic(s),h=v.status||v.modalMessage||v.modalButtons?{...s,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(pi,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.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(xs,{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,h.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(Uu,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Gn,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:y,actionLogs:k,userName:T,scrollToBottomRequestNonce:d,isInputActive:g})})]}):t.jsx(Gn,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:y,actionLogs:k,userName:T,scrollToBottomRequestNonce:d,isInputActive:g})]})},(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.sendFeedbackMessage===s.sendFeedbackMessage&&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 Vp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:y,onOpenRemote:k,onHideConversation:T,onStopCli:d,cliViewMode:g,onSetCliViewMode:v,handleSendChat:h,handleFocusAgent:C,handleModalButton:P,handleRelaunch:b}){const I=o.useRef(null),j=tt(e)&&!s,w=j&&g==="terminal",x=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 ${x} 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:p,type:"button","aria-label":"Back",children:t.jsx(ra,{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:dt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Ti,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&g&&t.jsx(xa,{mode:g,onChange:v,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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(Nt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:t.jsx(aa,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Tt,{size:14})}),T&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>T(e),type:"button",title:"Close chat",children:t.jsx(Nt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Aa,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:P,handleRelaunch:b,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Cn={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 Gp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function hc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Gp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Cn[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:Cn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Cn[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 xc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Vt}];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 Sr({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 js({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 qs({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 Nr({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}=Os(e.conversation),m=dt(e.conversation),f=gs(e.conversation),y=Bi(e.conversation,{requiresAction:s==="needs_attention"}),k=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",T=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",g=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",C="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] ${k}`,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 ${T}`,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:mi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${g}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} 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…"})]}):y==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,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 Io({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 qp({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:y,onOpenSettings:k,onSectionChange:T,wsStatus:d="connected",isStandalone:g=!1}){const v=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,P=e==="machines"?"Machines":"Chats",b=g?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=g?"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 ${b}`,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:P}),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(Zr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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(Qr,{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] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(qs,{icon:t.jsx(Io,{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(qs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:g?"Waiting for your daemon":"Connect your machines",subtitle:g?"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:!g&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(hc,{})})}):t.jsx(js,{children:c.map((j,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Needs attention",className:"mb-0"}),t.jsx(js,{children:s.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(js,{children:r.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(js,{children:n.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.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(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(js,{children:a.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(qs,{icon:t.jsx(Io,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(qs,{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(Vt,{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(qs,{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(js,{className:"bg-bg-secondary/25",children:i.map((j,w)=>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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(dt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:dt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:gs(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&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(xc,{section:e,onSectionChange:T})]})}function Yp(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 bc(e){const s=[e.workspace||"Workspace unknown"],r=bs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Yp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function nn(...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 Xp(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 an(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Xp(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 Qp(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 Jp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function on(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Jp(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 cn({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 y=Qp(r),k=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(Nt,{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:()=>{!y||a||u(y)},disabled:!y||a,children:[t.jsx(ra,{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:T=>f(T.target.value),onKeyDown:T=>{T.key!=="Enter"||!k||a||(T.preventDefault(),u(k))},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:()=>{!k||a||u(k)},disabled:!k||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(T=>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(T.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(Ls,{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:T.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:T.path})]})]},T.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(k||r),disabled:!k&&!r||a,children:c})]})]})})}function Ma({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:y,modelValue:k,onModelChange:T,historyProviderNode:d,onConfirm:g,onCancel:v}){const h=n==null?void 0:n.find(C=>C.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:v,"aria-label":"Close launch confirmation",children:t.jsx(Nt,{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:C=>i(C.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(C=>t.jsx("option",{value:C.key,children:C.label},C.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(C=>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:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),y&&T&&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:k||"",onChange:C=>T(C.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:C=>f(C.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:v,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:g,disabled:u,children:[t.jsx(oa,{size:14}),u?l:c]})]})]})})}function Ao(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function fs(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?"⭐ ":""}${Ao(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:Ao(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 Zp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function ef(e){return[Zp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function tf(e){return e.lastLaunchedAt?en(e.lastLaunchedAt):""}function gc(e){return{metaText:ef(e),updatedLabel:tf(e)}}function In(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function sf({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,it,ft,ht;const c=ur(),[l,u]=o.useState(!1),p=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),f=e.defaultWorkspaceId||null,[y,k]=o.useState(f||((it=m[0])==null?void 0:it.id)||""),[T,d]=o.useState(""),[g,v]=o.useState(""),[h,C]=o.useState([]),[P,b]=o.useState(!1),[I,j]=o.useState(""),[w,x]=o.useState(!1),[$,N]=o.useState(In(p,s.length,r.length)),L=o.useRef(null),[M,B]=o.useState(null),_=o.useRef("__home__"),[S,O]=o.useState("__home__"),[G,A]=o.useState(""),[K,V]=o.useState(""),[U,ce]=o.useState(""),[Y,oe]=o.useState([]),[Q,te]=o.useState(()=>yt().textQuery),[ue,Ne]=o.useState(()=>yt().workspaceQuery),[le,pe]=o.useState(()=>yt().modelQuery),[ae,z]=o.useState(()=>yt().resumableOnly),[ve,ee]=o.useState(()=>yt().sortMode),[we,re]=o.useState(!1),[ie,ne]=o.useState(!1),je=o.useRef(null),xe=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=y==="__custom__"?T.trim():((ft=m.find(ye=>ye.id===y))==null?void 0:ft.path)||"",ke=y==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ge=y!=="__custom__"&&((ht=m.find(ye=>ye.id===y))==null?void 0:ht.path)||"",Ce=o.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),J=o.useCallback(async ye=>{b(!0),j("");try{const Ue=await a(ye);v(Ue.path),d(Ue.path),C(Ue.directories)}catch(Ue){j(Ue instanceof Error?Ue.message:"Could not load folder")}finally{b(!1)}},[a]),Me=o.useCallback(()=>{var Ue;k("__custom__"),x(!0);const ye=an(e.platform,nn(T.trim(),ge,Ce,e.defaultWorkspacePath,(Ue=m.find(ze=>ze.id===f))==null?void 0:Ue.path,m.map(ze=>ze.path)));J(ye)},[T,f,J,Ce,ge,e.platform,m]),He=o.useCallback(ye=>{if(ye!=null&&ye.workspaceId){k(ye.workspaceId),d("");return}if(ye!=null&&ye.workspacePath){k("__custom__"),d(ye.workspacePath);return}k(""),d("")},[]),$e=o.useCallback(ye=>{if(k(ye),ye==="__custom__"){Me();return}d("")},[Me]),Ze=o.useCallback(ye=>{k("__custom__"),d(ye)},[]),Ge=o.useCallback((ye,Ue)=>{L.current=Ue,_.current=ye.selectedWorkspaceKey||"__home__",O(ye.selectedWorkspaceKey||"__home__"),A(ye.initialArgs||""),V(ye.initialModel||""),ce(""),oe([]);const ze=ye.providerType?`${e.id}:${ye.providerType}`:null;if(Gu(xe.current,ze)){const Xe=yt();te(Xe.textQuery),Ne(Xe.workspaceQuery),pe(Xe.modelQuery),z(Xe.resumableOnly),ee(Xe.sortMode)}xe.current=ze,B(ye),ye.providerType&&i&&(re(!0),i(ye.providerType).then(Xe=>oe(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>re(!1)))},[i,e.id]),Ye=o.useMemo(()=>Hi(Y,{textQuery:Q,workspaceQuery:ue,modelQuery:le,resumableOnly:ae,sortMode:ve}),[le,ae,Y,ve,Q,ue]);o.useEffect(()=>{U&&(Ye.some(ye=>ye.providerSessionId===U)||ce(""))},[Ye,U]);const ot=o.useCallback(()=>{L.current&&(ne(!0),L.current().finally(()=>{L.current=null,ne(!1),B(null)}))},[]),et=o.useCallback(()=>{L.current=null,B(null)},[]),mt=o.useCallback(ye=>{_.current=ye,O(ye)},[]);return o.useEffect(()=>{var ye;je.current!==e.id&&(je.current=e.id,k(f||((ye=m[0])==null?void 0:ye.id)||"__custom__"),d(""),v(""),C([]),j(""),x(!1),te(yt().textQuery),Ne(yt().workspaceQuery),pe(yt().modelQuery),z(yt().resumableOnly),ee(yt().sortMode),xe.current=null,N(In(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var ye;y!=="__custom__"&&(y&&m.some(Ue=>Ue.id===y)||k(f||((ye=m[0])==null?void 0:ye.id)||"__custom__"))},[f,y,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||N(In(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:y,customWorkspacePath:T,browseCurrentPath:g,browseDirectories:h,browseBusy:P,browseError:I,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:M,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:S,launchConfirmArgs:G,launchConfirmModel:K,launchConfirmResumeId:U,launchConfirmSavedSessions:Y,launchConfirmTextFilter:Q,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:le,launchConfirmResumableOnly:ae,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:we,launchConfirmBusy:ie,resolvedWorkspacePath:E,canCreateMissingWorkspace:ke,openBrowseDialog:Me,loadBrowsePath:J,handleWorkspaceChoiceChange:$e,chooseCustomWorkspacePath:Ze,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:N,openLaunchConfirm:Ge,handleConfirmLaunch:ot,closeLaunchConfirm:et,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:mt,setLaunchConfirmArgs:A,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ce,setLaunchConfirmTextFilter:te,setLaunchConfirmWorkspaceFilter:Ne,setLaunchConfirmModelFilter:pe,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ee}}function rf({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:y,onOpenConversation:k,onOpenRecent:T,onOpenMachineDetails:d,onMachineUpgrade:g,onLaunchDetectedIde:v,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:P,onListSavedSessions:b}){const I=S=>S==="ide"?"IDE":S==="cli"?"CLI":"ACP",j=r.slice(0,4),w=s.slice(0,3),x=sf({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:b}),$=o.useMemo(()=>j.map(S=>{const{metaText:O,updatedLabel:G}=gc(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:O,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:K}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:S.workspace});x.openLaunchConfirm({title:S.kind==="ide"?ds("restart-ide",S.label):S.providerSessionId?ya(S.label):ds("start-fresh",S.label),description:S.kind==="ide"?us("restart-ide"):S.providerSessionId?va():us("start-fresh"),confirmLabel:S.kind==="ide"?Es("restart-ide"):S.providerSessionId?zr(!0):Es("start-fresh"),busyLabel:S.kind==="ide"?Ks("restart-ide"):S.providerSessionId?ba(!0):Ks("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:K,details:[{label:"Mode",value:I(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const V=A.find(U=>U.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(V),await T({...S,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[x,T,j]),N=o.useMemo(()=>w.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:dt(S.conversation),secondary:Bu(S.conversation,{timestampLabel:S.timestamp?mi(S.timestamp):null}),unread:S.unread,onClick:()=>k(S.conversation)})),[k,w]),L=x.showAllRecent?$:$.slice(0,4),M=$.length>0,B=N.length>0,_=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 ${_} 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(ra,{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:Mt(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:[B&&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:N.map(S=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),M&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(S=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:S.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:S.primary}),S.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),$.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(S=>!S),children:x.showAllRecent?"Show fewer":`Show ${$.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:S=>x.handleWorkspaceChoiceChange(S.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(S=>t.jsxs("option",{value:S.id,children:[S.id===x.defaultWorkspaceId?"⭐ ":"",sn(S.path,S.label)||S.path]},S.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(Ls,{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(S=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:O,selectedKey:G}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${S.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:O,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:S.name}]},async()=>{const A=O.find(K=>K.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),v(S.type,{workspacePath:(A==null?void 0:A.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:S.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},S.type)):(x.activeLauncherKind==="cli"?n:a).map(S=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const O=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${S.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${O.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:O.toUpperCase()},{label:"Provider",value:S.displayName}],showArgsInput:!0,showModelInput:O==="acp",initialArgs:"",initialModel:"",providerType:S.type},async()=>{const K=G.find(V=>V.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(K),P(O,S.type,{workspaceId:(K==null?void 0:K.workspaceId)??null,workspacePath:(K==null?void 0:K.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:[S.icon?`${S.icon} `:"",S.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},S.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,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:g,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(cn,{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:S=>{x.loadBrowsePath(S)},onConfirm:S=>{x.chooseCustomWorkspacePath(S),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(Ma,{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?zr(!!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:ga()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:S=>x.setLaunchConfirmTextFilter(S.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:S=>x.setLaunchConfirmWorkspaceFilter(S.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:S=>x.setLaunchConfirmModelFilter(S.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:S=>x.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:S=>x.setLaunchConfirmResumableOnly(S.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:S=>x.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Xu()}),x.filteredLaunchConfirmSavedSessions.map(S=>t.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.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 S=x.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===x.launchConfirmResumeId);if(!S)return null;const O=bc(S);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),t.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(xc,{section:p,onSectionChange:y})]})}function yc(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 nf(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:bs(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=ar(n)?"cli":Is(n)?"acp":"ide",i=bs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ar(n)?n.cliName||n.type:Is(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Is(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 af(e,s){const r=new Map;for(const n of s){const a=es(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,y)=>y.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Hn(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=yc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Mt(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?Wu(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 Cr(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 of({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:y,onRequestedMobileSectionConsumed:k,setSelectedTabKey:T,setScreen:d,setSelectedMachineId:g,setSection:v,setMachineBackTarget:h,resetMachineAction:C,markNotificationTargetRead:P}){const b=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const w=Hr(j,c),x=Math.max(Date.now(),is(j),w.lastUpdated||0);Cr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:dt(j),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:is(j),readAt:x}),P({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId}),l(es(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then($=>{Cr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:$})}).catch($=>{Cr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var w;if(!n){d("inbox"),T(((w=e[0])==null?void 0:w.tabKey)||null),b.current=null;return}if(i!=="chat"){b.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;b.current!==j&&(b.current=j,I(n))},[e,I,i,n,d,T]),o.useEffect(()=>{if(!u)return;const j=e.find(w=>w.tabKey===u);j&&(T(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,T]),o.useEffect(()=>{if(!m)return;const j=s.find(w=>w.id===m);j&&(g(j.id),C(),v("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,C,h,d,v,g]),o.useEffect(()=>{y&&(v(y),d("inbox"),k==null||k())},[k,y,d,v]),o.useEffect(()=>{const j=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);j.length!==0&&Cr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(w=>{const x=Hr(w.conversation,c);return{liveState:x,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:dt(w.conversation),serverBucket:x.inboxBucket,computedBucket:w.inboxBucket,serverUnread:x.unread,computedUnread:w.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:is(w.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function cf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Mo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function df({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,C,P)=>{var b;try{i("loading"),l(`Launching ${C}…`);const I={ideType:C,enableCdp:!0};(b=P==null?void 0:P.workspacePath)!=null&&b.trim()&&(I.workspace=P.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${C} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),y=o.useCallback(async(h,C,P)=>{if(C.trim())try{i("loading"),l(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const b=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(b!=null&&b.success){i("done"),l(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((b==null?void 0:b.error)||"Could not save workspace")}catch(b){i("error"),l(b instanceof Error?b.message:"Could not save workspace")}},[e]),k=o.useCallback(async h=>{var C,P,b,I,j,w;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((P=x==null?void 0:x.result)==null?void 0:P.version)||"latest"}.`);return}if((b=x==null?void 0:x.result)!=null&&b.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=x==null?void 0:x.result)==null?void 0:w.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),T=o.useCallback(async(h,C,P,b)=>{var w,x,$;const I=Date.now(),j={machineId:h,kind:C,providerType:P,workspaceId:(b==null?void 0:b.workspaceId)||null,workspacePath:(b==null?void 0:b.workspacePath)||null,resumeSessionId:(b==null?void 0:b.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${P}…`),p(j);const N={cliType:P};(w=b==null?void 0:b.workspacePath)!=null&&w.trim()?N.dir=b.workspacePath.trim():b!=null&&b.workspaceId&&(N.workspaceId=b.workspaceId),b!=null&&b.resumeSessionId&&(N.resumeSessionId=b.resumeSessionId),(x=b==null?void 0:b.args)!=null&&x.trim()&&(N.cliArgs=b.args.trim().split(/\s+/).filter(Boolean)),($=b==null?void 0:b.model)!=null&&$.trim()&&(N.initialModel=b.model.trim());const L=await e(h,"launch_cli",N),M=(L==null?void 0:L.result)||L,B=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(L!=null&&L.success&&B){p(null),i("done"),l(`${P} launched`),s(Jt(B));return}if(L!=null&&L.success){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l((L==null?void 0:L.error)||(M==null?void 0:M.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(N){if(lf(N)){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l(N instanceof Error?N.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,C)=>{try{const P=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),b=(P==null?void 0:P.result)??P;return Array.isArray(b==null?void 0:b.sessions)?b.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),g=o.useCallback(async(h,C)=>on(e,h,C),[e]);o.useEffect(()=>{if(!u)return;const h=Mo(u.workspacePath),C=r.find(b=>{var N,L,M,B;if(!b||b.type==="adhdev-daemon"||cf(b.daemonId||b.id)!==u.machineId||(b.transport==="acp"?"acp":b.transport==="pty"?"cli":null)!==u.kind||String(b.agentType||b.type||"")!==u.providerType)return!1;const x=String(b.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const _=Mo(b.workspace||b.runtimeWorkspaceLabel);return _?_===h:!1}return Number(b.lastUpdated||b._lastUpdate||b.timestamp||((B=(M=(L=(N=b.activeChat)==null?void 0:N.messages)==null?void 0:L.at)==null?void 0:M.call(L,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const P=Mi({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});P&&(p(null),i("done"),l(`${u.providerType} launched`),s(Jt(P)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const v=o.useCallback(async(h,C)=>{if(C.kind==="ide"&&C.providerType){await f(h,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await T(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,T]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:y,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:T,handleListSavedSessions:d,handleBrowseDirectory:g,handleOpenRecent:v}}function uf({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),f=o.useCallback(v=>{const h=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),y=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,h="inbox")=>{l(v),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),T=o.useCallback(v=>{const h=es(v);h&&k(h,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),g=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:y,openMachine:k,openConversationMachine:T,backFromMachine:d,changeMachineSection:g}}function mf(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function pf(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 Ir(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function ff({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:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:T,onOpenHistory:d,onOpenRemote:g,onStopCli:v,wsStatus:h,isConnected:C,onShowHiddenConversation:P,onShowAllHiddenConversations:b,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:w,onMarkNotificationTargetRead:x}){const[$,N]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[L,M]=o.useState(()=>e[0]?"chat":"inbox"),[B,_]=o.useState("chats"),[S,O]=o.useState(null),[G,A]=o.useState("inbox"),K=Bs(),V="0.8.74",U=o.useMemo(()=>e.find(J=>J.tabKey===$)||e[0]||null,[e,$]),ce=o.useMemo(()=>U?r.find(J=>J.id===U.routeId):void 0,[r,U]),Y=o.useMemo(()=>!U||Je(U)||!tt(U)?null:Ps(U),[U]),oe=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(da),[r]),Q=o.useMemo(()=>oe.find(J=>J.id===S)||null,[oe,S]),te=o.useMemo(()=>tn(r),[r]),ue=rn({sendDaemonCommand:a,activeConv:U||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),Ne=df({sendDaemonCommand:a,navigate:K,ides:r,conversations:e}),le=o.useMemo(()=>e.map(J=>{const Me=L==="chat"&&(U==null?void 0:U.tabKey)===J.tabKey,He=la(J,te,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:w}),$e=is(J),Ze=Ki(J);return{conversation:J,timestamp:$e,preview:Ze,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,te,w,L,U]),{markConversationRead:pe}=of({conversations:e,machineEntries:oe,items:le,selectedConversation:U,selectedTabKey:$,screen:L,liveSessionInboxState:te,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:y,requestedMobileSection:k,onRequestedMobileSectionConsumed:T,setSelectedTabKey:N,setScreen:M,setSelectedMachineId:O,setSection:_,setMachineBackTarget:A,resetMachineAction:Ne.resetMachineAction,markNotificationTargetRead:x}),ae=uf({conversations:e,selectedConversation:U,machineBackTarget:G,markConversationRead:pe,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:N,setScreen:M,setSelectedMachineId:O,setSection:_,setMachineBackTarget:A}),z=o.useMemo(()=>Ir(le.filter(J=>J.requiresAction)),[le]),ve=o.useMemo(()=>Ir(le.filter(J=>J.unread&&!J.requiresAction)),[le]),ee=o.useMemo(()=>Ir(le.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[le]),we=o.useMemo(()=>Ir(le.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[le]),re=o.useMemo(()=>Q?le.filter(J=>es(J.conversation)===Q.id):[],[le,Q]),ie=o.useMemo(()=>nf(Q,r),[r,Q]),ne=(Q==null?void 0:Q.version)||null,je=!!Q&&!!ne&&!0&&ne!==V,xe=o.useMemo(()=>(Q==null?void 0:Q.availableProviders)||[],[Q]),E=o.useMemo(()=>xe.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ke=o.useMemo(()=>xe.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ge=o.useMemo(()=>af(oe,le),[le,oe]),Ce=o.useCallback(async J=>{Q&&await Ne.handleOpenRecent(Q.id,J)},[Ne,Q]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&U?t.jsx(Vp,{selectedConversation:U,isAcp:Je(U),isStandalone:l,selectedIdeEntry:ce,actionLogs:n,userName:u,isSendingChat:ue.isSendingChat,sendFeedbackMessage:ue.sendFeedbackMessage,isFocusingAgent:ue.isFocusingAgent,handleModalButton:ue.handleModalButton,handleRelaunch:ue.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:g,onStopCli:v,cliViewMode:Y,onSetCliViewMode:async J=>{if(U&&Y!==J)try{await a(es(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:$t(U),mode:J})}catch(Me){pf(Me)?console.warn("Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:ue.handleSendChat,handleFocusAgent:ue.handleFocusAgent}):L==="machine"&&Q?t.jsx(rf,{selectedMachineEntry:Q,selectedMachineConversations:re,selectedMachineRecentLaunches:ie,cliProviders:E,acpProviders:ke,selectedMachineNeedsUpgrade:je,appVersion:V,machineAction:Ne.machineAction,isStandalone:l,section:B,showBottomNav:G==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:Ce,onOpenMachineDetails:()=>K(`/machines/${Q.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(Q.id),onLaunchDetectedIde:(J,Me)=>Ne.handleLaunchDetectedIde(Q.id,J,Me),onAddWorkspace:(J,Me)=>Ne.handleAddWorkspace(Q.id,J,Me),onBrowseDirectory:J=>Ne.handleBrowseDirectory(Q.id,J),onLaunchWorkspaceProvider:(J,Me,He)=>Ne.handleLaunchWorkspaceProvider(Q.id,J,Me,He),onListSavedSessions:J=>Ne.handleListSavedSessions(Q.id,J)}):t.jsx(qp,{section:B,attentionItems:z,unreadItems:ve,workingItems:ee,completedItems:we,hiddenConversations:s,machineCards:ge,getAvatarText:mf,onOpenConversation:ae.openConversation,onShowConversation:P,onShowAllHidden:b,onOpenNewSession:j,onOpenMachine:ae.openMachine,onOpenSettings:()=>K("/settings"),onSectionChange:_,wsStatus:h,isConnected:C,isStandalone:l})})}function An(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function hf({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 y=o.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!An(s,r)){m("merge");return}const v=g.currentTarget.getBoundingClientRect(),h=g.clientX-v.left,C=v.width/3;h<C?m("split-left"):h>C*2?m("split-right"):m("merge")},[s,r]),T=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(g=>{c.current=0,u(!1);const v=g.dataTransfer.getData("text/tab-key"),h=v?e.some(P=>P.tabKey===v):!1,C=p;if(m(null),i(),!!v){if(g.preventDefault(),C==="split-left"&&An(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&An(s,r)){r==null||r(v,"split-right");return}if(h){a(v);return}n==null||n(v)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:y,handleDragOver:k,handleDragLeave:T,handleDrop:d}}function xf(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 bf({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),y=o.useRef(null),k=o.useRef(n),T=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{T.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const w=xf(j,e);return w.length===j.length&&w.every((x,$)=>x===j[$])?j:w})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const w=new Map(j.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const N=w.get(x.tabKey)??999,L=w.get($.tabKey)??999;return N-L})},[e,p,l]);o.useEffect(()=>{var w,x;if(d.length===0){i!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(i&&d.some($=>$.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const g=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),v=o.useCallback(j=>{var w;c(j),(w=k.current)==null||w.call(k,j)},[]),h=o.useCallback((j,w,x)=>{u($=>{var B;const N=$.filter(_=>_!==j),L=N.indexOf(w);if(L<0)return $;const M=x==="left"?L:L+1;return N.splice(M,0,j),(B=T.current)==null||B.call(T,N),N}),m(null)},[]),C=o.useCallback((j,w,x)=>{const N=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),L=N.indexOf(w);if(L<0)return;const M=x==="left"?L:L+1;N.splice(M,0,j),f.current=N,m(N)},[l,e]),P=o.useCallback(()=>{var w;const j=f.current;j&&(u(j),(w=T.current)==null||w.call(T,j))},[]),b=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(w=>{var $;const x=w.filter(N=>N!==j);return x.push(j),($=T.current)==null||$.call(T,x),x})},[]);return{activeTabId:i,activeConv:g,sortedConversations:d,previewOrderRef:f,draggingTabRef:y,selectTab:v,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:P,clearPreviewOrder:b,moveTabToEnd:I,setDraggingTabKey:j=>{y.current=j}}}function gf({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 Ta({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(hc,{}),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 vc="adhdev-tab-shortcuts";function wc(){try{return JSON.parse(localStorage.getItem(vc)||"{}")}catch{return{}}}function jc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>wc()),[l,u]=o.useState(null),p=o.useCallback(f=>{const y=[];return f.metaKey&&y.push(a?"⌘":"Meta"),f.ctrlKey&&y.push("Ctrl"),f.altKey&&y.push(a?"⌥":"Alt"),f.shiftKey&&y.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(y.push(f.key.length===1?f.key.toUpperCase():f.key),y.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(vc,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){u(null);return}const k=p(y);if(!k)return;const T={...i};for(const[d,g]of Object.entries(T))g===k&&delete T[d];T[l]=k,m(T),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=y=>{if(!(!y.ctrlKey&&!y.metaKey&&!y.altKey)){for(const[k,T]of Object.entries(i))if(s.includes(k)&&p(y)===T){y.preventDefault(),r(),n(k);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 yf=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:y,onCommitPreviewOrder:k,onClearPreviewOrder:T,onDragStateReset:d,onDragTabKeyChange:g,onReceiveTab:v,onOpenContextMenu:h,longPressTimer:C,isGroupActive:P}){const b=Os(s),I=b.isGenerating?"agent-tab-generating":b.isWaiting?"agent-tab-waiting":"",j=b.isReconnecting,w=o.useCallback(O=>{l.current=s.tabKey,g(s.tabKey),O.dataTransfer.setData("text/tab-key",s.tabKey),O.dataTransfer.effectAllowed="move"},[s.tabKey,l,g]),x=o.useCallback(()=>{l.current=null,g(null),k(),T(),d()},[l,g,k,T,d]),$=o.useCallback(O=>{const G=l.current;if(!(!G||G===s.tabKey)&&O.dataTransfer.types.includes("text/tab-key")){O.preventDefault(),O.stopPropagation();const A=O.currentTarget.getBoundingClientRect(),K=O.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,K)}},[s.tabKey,l,f]),N=o.useCallback(O=>{O.preventDefault(),O.stopPropagation();const G=O.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=O.currentTarget.getBoundingClientRect(),K=O.clientX<A.left+A.width/2?"left":"right";c.includes(G)?y(G,s.tabKey,K):v&&v(G)}T()},[s.tabKey,c,y,v,T]),L=o.useCallback(O=>{O.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),M=o.useCallback(O=>{O.preventDefault(),h(O.clientX,O.clientY,s.tabKey)},[s.tabKey,h]),B=o.useCallback(O=>{const G=O.touches[0];C.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,C,h]),_=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),S=["adhdev-dockview-tab",I,r&&"is-active",P&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:S,draggable:!0,onDragStart:w,onDragEnd:x,onDragOver:$,onDrop:N,onClick:L,onContextMenu:M,onTouchStart:B,onTouchEnd:_,onTouchMove:_,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:b.isGenerating?t.jsx("div",{className:"tab-spinner"}):b.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):b.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:dt(s),children:dt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ls(s)}):b.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ls(s),t.jsx("span",{className:"connecting-dots"})]}):ls(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 vf({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:y,onDragTabKeyChange:k,onReceiveTab:T,onHideTab:d,isGroupActive:g,allowTabShortcuts:v=!0}){const[h,C]=o.useState(null),P=o.useRef(null),b=o.useRef(null),I=o.useMemo(()=>e.map(M=>M.tabKey),[e]);cr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:w,shortcutListening:x,setShortcutListening:$,saveShortcuts:N}=jc({enabled:v,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const M=B=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(B.target)||C(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[h]),o.useEffect(()=>{const M=b.current;if(!M)return;const B=_=>{Math.abs(_.deltaY)<=Math.abs(_.deltaX)||(_.preventDefault(),M.scrollLeft+=_.deltaY)};return M.addEventListener("wheel",B,{passive:!1}),()=>M.removeEventListener("wheel",B)},[]);const L=o.useCallback((M,B,_)=>{C({x:M,y:B,tabKey:_})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:b,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(yf,{conv:M,isActive:s===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:v?w[M.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:y,onDragTabKeyChange:k,onReceiveTab:T,onOpenContextMenu:L,longPressTimer:P,isGroupActive:g},M.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:[v&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:M=>{M.stopPropagation(),$(h.tabKey),C(null)},children:["⌨ ",w[h.tabKey]?`Change shortcut (${w[h.tabKey]})`:"Set shortcut"]}),w[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 M={...w};delete M[h.tabKey],N(M),C(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[v&&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),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function wf({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:y,numGroups:k,onMoveTab:T,onReceiveTab:d,style:g,onActiveTabChange:v,initialActiveTabId:h,initialTabOrder:C,onTabOrderChange:P,onHideTab:b,isFocused:I,allowTabShortcuts:j=!0}){const{sendCommand:w}=Lt(),x=o.useRef(null),{activeTabId:$,activeConv:N,sortedConversations:L,draggingTabRef:M,selectTab:B,handleTabReorder:_,updatePreviewOrder:S,commitPreviewOrder:O,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:K}=bf({conversations:e,initialActiveTabId:h,initialTabOrder:C,onActiveTabChange:v,onTabOrderChange:P}),V=rn({sendDaemonCommand:a,activeConv:N,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:U,dropAction:ce,resetDragState:Y,handleDragEnter:oe,handleDragOver:Q,handleDragLeave:te,handleDrop:ue}=hf({conversations:e,numGroups:k,onMoveTab:T,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),Ne=N&&!Je(N)&&Ps(N)==="terminal",le=o.useMemo(()=>N?s.find(ee=>ee.id===N.routeId):void 0,[s,N]),pe=o.useMemo(()=>N?n.filter(ee=>ee.routeId===N.tabKey):[],[n,N]),ae=o.useMemo(()=>tn(s),[s]),z=o.useMemo(()=>new Set(L.filter(ee=>xd(ee,ae,{isOpenConversation:ee.tabKey===$})).map(ee=>ee.tabKey)),[$,ae,L]);cr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:$,dragOver:U});const ve=o.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&w(ee.routeId,fc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[w]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...g,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(vf,{conversations:L,activeTabId:$,groupIndex:m,numGroups:k,unreadTabKeys:z,draggingTabRef:M,onFocus:f,onSelectTab:B,onConversationActivated:ve,onPreviewReorder:S,onReorderTab:_,onCommitPreviewOrder:O,onClearPreviewOrder:G,onDragStateReset:Y,onDragTabKeyChange:K,onMoveTab:T,onReceiveTab:d,onHideTab:b,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:oe,onDragOver:Q,onDragLeave:te,onDrop:ue,children:[U&&t.jsx(gf,{dropAction:ce,canSplit:!!(k<4&&T)}),N?t.jsx(Aa,{activeConv:N,clearToken:r[N.tabKey]||0,isCliTerminal:!!Ne,ideEntry:le,terminalRef:x,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,sendFeedbackMessage:V.sendFeedbackMessage,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:pe,userName:p,isInputActive:!y||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:e.length,isSplitMode:y,isStandalone:l,hasRegisteredMachines:u})})]})]})}function jf({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:y,userName:k,focusedGroup:T,setFocusedGroup:d,moveTabToGroup:g,splitTabRelative:v,closeGroup:h,handleResizeStart:C,groupActiveTabIds:P,setGroupActiveTabIds:b,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:w,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(($,N)=>{const L=s&&n.length===r?`${n[N]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&N>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:M=>C(N-1,M),onDoubleClick:()=>h(N),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(wf,{style:s?{flexBasis:L??`${100/r}%`,flexGrow:L?0:1,flexShrink:L?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:y,userName:k,groupIndex:N,isFocused:s&&T===N,onFocus:()=>d(N),isSplitMode:s,numGroups:r,onMoveTab:(M,B)=>{B==="left"&&N>0?g(M,N-1):B==="right"&&N<r-1?g(M,N+1):B==="split-left"&&r<4?v(M,N,"left"):B==="split-right"&&r<4&&v(M,N,"right")},onReceiveTab:M=>g(M,N),onActiveTabChange:M=>b(B=>(B[N]??null)===(M??null)?B:{...B,[N]:M}),initialActiveTabId:P[N],initialTabOrder:I[N],onTabOrderChange:M=>j(B=>{const _=B[N]||[];return _.length===M.length&&_.every((S,O)=>S===M[O])?B:{...B,[N]:M}}),onHideTab:w,allowTabShortcuts:x})]},N)})})}function kc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const y=new FileReader;y.onload=()=>i(y.result),y.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ut.onStatus)==null?void 0:m.call(ut,(f,y)=>{f===e&&y!=null&&y.screenshotUsage&&l(y.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ut.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?ut.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 Sc="adhdev-dashboard-action-shortcuts",kf=1200,Sf={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Nf(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 Nc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Jn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Yr(e){const s=Object.fromEntries(Nc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Sc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Sf))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Cc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Cf({enabled:e=!0,onTrigger:s}){const r=Nf(),[n,a]=o.useState(()=>Yr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const g=[];return d.metaKey&&g.push(r?"⌘":"Meta"),d.ctrlKey&&g.push("Ctrl"),d.altKey&&g.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(g.push(Cc(d.key)),g.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(Sc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Yr(r),g=Object.entries(n),v=Object.entries(d);g.length===v.length&&g.every(([h,C])=>d[h]===C)||f(d)},[n,r,f]);const y=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},kf))},[]);o.useEffect(()=>{if(!i)return;const d=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),u([]);return}const v=m(g);if(!v)return;const C=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const b=[...l,v].slice(0,2).join(" "),I={...n};for(const[j,w]of Object.entries(I))w===b&&delete I[j];I[i]=b,f(I),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=g=>{if(g.defaultPrevented)return;const v=m(g);if(!v)return;const h=g.metaKey||g.ctrlKey||g.altKey;if(Jn(g.target)&&!h)return;const C=p.current.parts,P=h?[v]:[...C.slice(-1),v].slice(-2),b=P.join(" "),I=P[P.length-1],j=Object.entries(n).filter(([,L])=>!!L),w=j.find(([,L])=>L===b);if(w){g.preventDefault(),y(),s(w[0]);return}if(j.some(([,L])=>L.startsWith(`${b} `))){g.preventDefault(),p.current.parts=P,k();return}const $=j.find(([,L])=>L===I);if($){g.preventDefault(),y(),s($[0]);return}if(j.some(([,L])=>L.startsWith(`${I} `))){g.preventDefault(),p.current.parts=[I],k();return}y()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,y,i]),o.useEffect(()=>()=>y(),[y]);const T=o.useMemo(()=>Nc(r),[r]);return{isMac:r,actionDefinitions:T,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function If({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}function Af(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function To({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Af(n):!0}const Ic=o.createContext(null);function ln(){const e=o.useContext(Ic);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Er(e){return dt(e)||e.tabKey}function Mf(e){return`remote:${e}`}function Yt(e){return e.startsWith("remote:")}function Lo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mn(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 Ar(e,s){e.classList.remove(Bn.className,Wn.className),e.classList.add(s==="light"?Bn.className:Wn.className)}function _o(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 Tf(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 Lf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Er(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Ro(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Yt(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!==Er(n)&&a.api.setTitle(Er(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Er(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 Po(e,s,r){var u,p;const n=r?Mf(r):null;for(const m of[...e.panels])Yt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Kt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Oi(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=>!Yt(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 _f({params:e,api:s}){var f;const r=ln(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=rn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const y=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of y)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(y=>y.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(y=>y.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(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Je(c)&&Ps(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Aa,{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 Rf({params:e}){var u;const s=ln(),r=o.useMemo(()=>Kt([...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}=kc({doId:a,targetSessionId:r?Ci(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(ci,{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 Pf(){const e=ln();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Df(e){var k,T;Tf(e);const s=ln(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Kt([...s.conversationsByTabKey.values()],e.params.routeId),g=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${v?" 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=((T=e.api.group.activePanel)==null?void 0:T.id)===e.api.id,i=e.api.isGroupActive,c=la(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,y=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:dt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var g;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((g=d.target)==null?void 0:g.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:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ls(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ls(n)}):t.jsx("span",{children:ls(n)})})]}),y&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function $f({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:y,registerActionHandlers:k,onActiveTabChange:T,requestedActiveTabKey:d,requestedRemoteIdeId:g,onRequestedActiveTabConsumed:v,scrollToBottomRequest:h,notificationStateBySessionId:C}){var It,q,Ee;const{theme:P}=ka(),{sendCommand:b}=Lt(),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),N=o.useRef(null),L=o.useRef([]),[M,B]=o.useState(null),[_,S]=o.useState(!1),[O,G]=o.useState(!1),[A,K]=o.useState(0),V=o.useRef(null),U=o.useMemo(()=>dc(typeof window<"u"?window.innerWidth:1280),[]),ce=o.useRef(typeof window>"u"?{}:xp(U)),Y=o.useMemo(()=>new Map(e.map(R=>[R.tabKey,R])),[e]),oe=o.useMemo(()=>tn(r),[r]),Q=o.useMemo(()=>{const R=I.current;return R?R.groups.some(W=>{try{const H=W.model.location.type;return H!=="floating"&&H!=="popout"?!1:W.panels.some(F=>Y.has(F.id))}catch{return!1}}):!1},[Y,A,e]),te=o.useCallback(()=>{var R;(R=I.current)==null||R.focus()},[]),ue=o.useCallback(R=>{const W=document,H=R.document;for(const Ie of W.querySelectorAll('link[rel="stylesheet"]')){const We=H.createElement("link");We.rel="stylesheet",We.href=Ie.href,Ie.crossOrigin&&(We.crossOrigin=Ie.crossOrigin),H.head.appendChild(We)}for(const Ie of W.querySelectorAll("style")){const We=H.createElement("style");We.textContent=Ie.textContent,H.head.appendChild(We)}const F=[];for(const Ie of W.styleSheets)try{for(const We of Ie.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&F.push(We.cssText)}catch{}if(F.length>0){const Ie=H.createElement("style");Ie.textContent=F.join(`
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Tm=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Lm(){const{preference:e,setPreference:s}=ka();return t.jsx("div",{className:"flex gap-2",children:Tm.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 _m(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 Rm(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function kn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function fo(e){const{r:s,g:r,b:n}=Rm(e);return .2126*kn(s)+.7152*kn(r)+.0722*kn(n)}function ho(e,s){const r=fo(e),n=fo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function tc(e){const s=_m(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ho(s,r)>=ho(s,n)?r:n}const Yn={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},Xn={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},Pm=[{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"}}}],sc="adhdev-chat-theme",rc="adhdev-chat-theme-custom";function Dr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(sc)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(rc);if(s){const r=JSON.parse(s);return{...e==="dark"?Yn:Xn,...r[e]}}}catch{}return e==="dark"?Yn:Xn}function jr(e,s){try{localStorage.setItem(rc,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(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 Gr(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 Dm={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function tr(e,s){var a;const r=(a=Dm[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",Gr(r,24)),n.style.setProperty("--accent-on-primary",tc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Gr(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function ms(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Gr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",tc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Gr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 Sa(){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 $m(e){try{localStorage.setItem(sc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ps()?"dark":"light";ms(Et(s))}else Sa(),tr(e,ps()?"dark":"light")}function Em(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ps()?"dark":"light";ms(Et(s))}else Sa(),tr(e,ps()?"dark":"light")}function ps(){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 Vs({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 Km({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"?jr(p,f):jr(f,p),ms(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(Vs,{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(Vs,{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(Vs,{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(Vs,{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(Vs,{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?Yn:Xn,u=Et(e?"light":"dark");e?jr(c,u):jr(u,c),a(c),ms(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 Bm(){const[e,s]=o.useState(Dr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(ps());const u=new MutationObserver(()=>{const f=ps();n(f);const b=Dr();b==="custom"?ms(Et(f?"dark":"light")):tr(b,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ps();n(f);const b=Dr();b==="custom"?ms(Et(f?"dark":"light")):tr(b,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"?ms(Et(r?"dark":"light")):(Sa(),tr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=u=>{s(u),$m(u)},l=[...Pm,{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(Km,{dark:r,onColorsChange:u=>i(u)})]})}const nc="adhdev_mobileDashboardMode_v1";function ac(){try{return localStorage.getItem(nc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Wm(e){try{localStorage.setItem(nc,e)}catch{}}function Om(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(ac()==="chat")},[]),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vt,{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),Wm(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function Hm(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 Um(e,s){const{sendData:r}=Lt(),{injectEntries:n,getIdes:a}=Wr(),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=>Zt.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(b=>b.id===u),f=Hm(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 Fm=4e3;function oc(e,s){const{sendData:r}=Lt(),[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=Zt.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)},Fm):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 zm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ic(e){const{sendData:s}=Lt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=zm(e);if(!a||!e.sessionId||!s){n({});return}const i=Zt.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}),Ts.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 cc="adhdev_hiddenTabs";function Vm(){try{const e=localStorage.getItem(cc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ws(e){try{localStorage.setItem(cc,JSON.stringify([...e]))}catch{}}function Gm(){const[e,s]=o.useState(Vm),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),ws(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),ws(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),ws(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return ws(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const b=new Set(f);for(const k of m)b.add(k);return ws(b),b})},[]),l=o.useCallback((p,m)=>{s(f=>{const b=new Set(f);for(const k of m)b.delete(k);return ws(b),b})},[]),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 xo(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 qm(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=xo(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>xo(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function lc(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 Ym(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))lc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Xm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ed()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Wi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Bd(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 Qm(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 Sn(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 Jm(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function bo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Jm(_s(r.content)):"";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 Zm(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||""),bo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),bo(r.activeChat)].join(":"))].join("|")}function ep(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 tp(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 sp(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 rp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of os({routeId:n.routeId}))r.set(i,a);for(const i of os({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of os({tabKey:n.tabKey}))r.set(i,n)}return r}function np(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function ap(e){const s=np(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=_s(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function op({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Qm(e),[e]),c=o.useMemo(()=>Vi(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),b=o.useMemo(()=>{const g=new Map,I=[];for(const $ of i){const{connectionState:N="new",machineName:T}=Gi($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),M=tp($,r),B=Zm($),_=m.current.get($.id);if(_&&_.ide===$&&_.sourceSignature===B&&_.connectionState===N&&_.machineName===T&&sp(_.localRefs,M)){g.set($.id,_),I.push(..._.conversations);continue}const S=ja($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),O={ide:$,sourceSignature:B,connectionState:N,machineName:T,localRefs:M,conversations:S};g.set($.id,O),I.push(...S)}m.current=g;const j=new Map,w=$=>{const N=ap($),T=f.current.get($.tabKey);if(T&&T.signature===N)return j.set($.tabKey,T),T.timestamp;const M={signature:N,timestamp:Ii($)||(T==null?void 0:T.timestamp)||0};return j.set($.tabKey,M),M.timestamp},x=[...I].sort(($,N)=>Ai($,N,w));return f.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const g=ep(b,n);return Sn(l.current,g)?l.current:(l.current=g,g)},[b,n]),L=o.useMemo(()=>{const g=new Map,I=Array.from(new Set(k.map(j=>j.routeId)));for(const j of I){const w=Kt(k,j);w&&g.set(j,w)}return g},[k]),d=o.useMemo(()=>{const g=new Map;for(const I of k){const j=L.get(I.routeId),w=I.streamSource==="native"&&j?j:I;for(const x of os({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))g.set(x,w)}return g},[k,L]),y=o.useMemo(()=>rp(k,L),[k,L]),v=o.useCallback(g=>{if(g)return d.get(g)},[d]),h=o.useCallback(g=>{if(g)return y.get(g)},[y]),C=o.useMemo(()=>{const g=k.filter(I=>!a.has(I.tabKey));return Sn(u.current,g)?u.current:(u.current=g,g)},[k,a]),P=o.useMemo(()=>{const g=C.map(I=>I.tabKey);return Sn(p.current,g)?p.current:(p.current=g,g)},[C]);return{chatIdes:i,conversations:k,visibleConversations:C,visibleTabKeys:P,resolveConversationBySessionId:v,resolveConversationByTarget:h}}function ip({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 cp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{lt.setIdes(e)},[e]),o.useEffect(()=>{lt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=lt.onToast(u=>{r(m=>m.some(b=>b.message===u.message&&u.timestamp-b.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=lt.onSystemMessage((u,p)=>{var k,L;const m=a(u),f=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),b=!!(m&&(m.status==="waiting_approval"||(L=m.modalButtons)!=null&&L.length||m.modalMessage));f&&b||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=lt.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(b=>{var k;return!(b.role==="system"&&((k=b._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Ei.on("status_event",c=>{lt.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var y;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 b=Number(u.buttonIndex),k=u.button||((y=m==null?void 0:m.modalButtons)==null?void 0:y[b])||"Approve",L=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(L);s(f,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(b)&&{buttonIndex:b},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 lp="adhdev_dashboardLayout_v1",dp="adhdev_dashboardDockview_v1",up="adhdev_dashboardDockviewHiddenRestore_v1",Gs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Na(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function dc(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function uc(e){return`${lp}:${e}`}function mp(e){const s=uc(e);return Na(s,null)}function pp(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=uc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function mc(e){return`${dp}:${e}`}function fp(e){const s=mc(e);return Na(s,null)}function hp(e,s){try{const r=mc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function pc(e){return`${up}:${e}`}function xp(e){const s=pc(e);return Na(s,{})}function bp(e,s){try{const r=pc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function gp(){return{groupAssignments:[...Gs.groupAssignments],focusedGroup:Gs.focusedGroup,groupActiveTabIds:{...Gs.groupActiveTabIds},groupTabOrders:{...Gs.groupTabOrders},groupSizes:[...Gs.groupSizes]}}function yp(){const[e]=o.useState(()=>dc(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,b]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,L]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const y=mp(e)??gp();r(new Map(y.groupAssignments)),a(y.focusedGroup),c(y.groupActiveTabIds),u(y.groupTabOrders),m(y.groupSizes),L(!0)},[k,e]);return o.useEffect(()=>{k&&pp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const y=window.matchMedia("(max-width: 767px)"),v=h=>b(h.matches);return y.addEventListener("change",v),()=>y.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function vp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function wp({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:b,handleRefreshHistory:k}){const L=o.useRef(!1),d=o.useRef(!1),y=o.useRef(null),v=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 C=n.get(h.tabKey)??0;c(P=>({...P,[C]:h.tabKey})),l(C),L.current=!0,d.current=!0,y.current!=null&&(window.clearTimeout(y.current),y.current=null),u(P=>{const g=new URLSearchParams(P);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(y.current==null)return y.current=window.setTimeout(()=>{y.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){v.current=!1;return}if(!m||v.current||f)return;const h=b.find(C=>C.id===m.routeId);h&&(!h.chats||h.chats.length===0||vp(h.chats,m))&&(v.current=!0,k())},[p,m,f,b,k]),o.useEffect(()=>{if(!m)return;let h=null,C=0,P=-1,g=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){C<18&&(C+=1,h=requestAnimationFrame(I));return}let w=0;for(const x of j)x.scrollTop=x.scrollHeight,w+=x.scrollHeight;w===P?g+=1:(g=0,P=w),C+=1,!(g>=2||C>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function jp({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),b=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!tt(v)&&!Je(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const h=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===v?h:Kt(i,v)},[i,u,a]),L=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{b&&(p({routeId:b.routeId,tabKey:to(b)}),f(b),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,b]);const d=o.useCallback(v=>{v&&(p({routeId:v.routeId,tabKey:to(v)}),f(v))},[]),y=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:L,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:y}}function Nn(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=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function go({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(y){console.error("Launch failed",y)}},[e]),b=o.useCallback(async(d,y)=>{try{const v=d||(s==null?void 0:s.daemonId)||"",h=await e(v,"switch_chat",{id:y,sessionId:y,...As(s)}),C=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?zs(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?zs(a,`⚠️ Switch error: ${C}`):zs(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),zs(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=ir(s);await e(d,"new_chat",{...As(s)}),c(y=>({...y,[s.tabKey]:Date.now()})),i(y=>({...y,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),L=o.useCallback(async()=>{var d,y;if(!(!s||p)){m(!0);try{const v=ir(s),h=async()=>e(v,"list_chats",{forceExpand:!0,...As(s)});let C=await h(),P=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);Nn(P,s)&&(await new Promise(g=>setTimeout(g,450)),C=await h(),P=(C==null?void 0:C.chats)||((y=C==null?void 0:C.result)==null?void 0:y.chats)),C!=null&&C.success&&Array.isArray(P)&&(n(s.routeId,P),Nn(P,s)&&!Nn(r,s)&&zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:b,handleNewChat:k,handleRefreshHistory:L}}function kp(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 Sp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function yo(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 kr(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 vo(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 Np(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 Cp(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 wo(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 jo(e){return Array(e).fill(100/e)}function Ip({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(()=>kr(e,p),[e,p]),b=f.assignments,k=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),L=k>1,d=o.useCallback((g,I)=>{s(j=>{const w=new Map(kr(j,p).assignments);return I===0?w.delete(g):w.set(g,I),w}),n(j=>({...j,[I]:g})),r(I)},[s,p,n,r]),y=o.useCallback(g=>{s(I=>{const j=kr(I,p).assignments,w=new Map;for(const[x,$]of j)$!==g&&($>g?w.set(x,$-1):w.set(x,$));return w}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(g,1);const w=j.reduce((x,$)=>x+$,0);return w>0?j.map(x=>x/w*100):[]}),r(0)},[s,p,c,r]),v=o.useCallback((g,I)=>{I.preventDefault();const j=m.current;if(!j)return;const w=I.clientX,x=j.offsetWidth,$=i.length===k?[...i]:jo(k),N=M=>{const _=(M.clientX-w)/x*100,S=[...$];S[g]=Math.max(15,$[g]+_),S[g+1]=Math.max(15,$[g+1]-_),c(S)},T=()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",T)},[i,k,c]),h=o.useCallback((g,I,j)=>{if(k>=4)return;const w=j==="left"?I:I+1;s(x=>{const $=kr(x,p).assignments,N=new Map;for(const T of u){const M=$.get(T.tabKey)??0,B=M>=w?M+1:M;B>0&&N.set(T.tabKey,B)}return w>0&&N.set(g,w),N}),c(x=>{const $=x.length===k?[...x]:jo(k),N=$[I]??100/k,T=Math.max(15,N/2),M=Math.max(15,N/2),B=[...$];B[I]=T,B.splice(w,0,M);const _=B.reduce((S,O)=>S+O,0);return B.map(S=>S/_*100)}),n(x=>{const $=wo(x,w);return $[w]=g,$}),a(x=>{const $=wo(x,w);return $[w]=[g],$}),r(w)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{kp(e,b)||s(b)},[e,b,s]),o.useEffect(()=>{const{mapping:g,usedGroups:I}=f;n(j=>{const w=vo(j,g);return yo(j,w)?j:w}),a(j=>{const w=vo(j,g);return yo(j,w)?j:w}),r(j=>{const w=l?0:Np(j,I,g);return j===w?j:w}),c(j=>{const w=l?[]:Cp(j,I,f.groupCount);return Sp(j,w)?j:w})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const g=Array.from({length:k},()=>[]);for(const I of u){const j=b.get(I.tabKey)??0,w=Math.min(j,k-1);g[w].push(I)}return g},[u,b,k]),P=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:b,numGroups:k,isSplitMode:L,groupedConvs:C,moveTabToGroup:d,closeGroup:y,handleResizeStart:v,splitTabRelative:h,clearAllSplits:P}}function Ap({ides:e,sendDaemonCommand:s}){const r="0.8.75",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ec(m,r)).sort((m,f)=>Number(er(f,r))-Number(er(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>er(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,b;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(f=k==null?void 0:k.result)!=null&&f.upgraded||(b=k==null?void 0:k.result)!=null&&b.success?u(L=>({...L,[m]:"done"})):u(L=>({...L,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Qn="adhdev_dashboard_notifications_v1",Ca=80;function $r(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function qr(e){return{...e,createdAt:$r(e.createdAt),updatedAt:$r(e.updatedAt,e.createdAt),lastEventAt:$r(e.lastEventAt,e.updatedAt||e.createdAt)}}function Mp(e){const s=di(e);return s==="unknown:"?e.id:s}function Tp(e){return[e.type,li(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Lp(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=$r(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Tp({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(qr({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Si(a),preview:ru(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function _p(e,s,r=Ca){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,qr(i));for(const i of s){const c=qr(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=Mp(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function Rp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Pp(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function Dp(e,s,r=Date.now()){return e.map(n=>Or(n,s)?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function $p(e,s){return e.filter(r=>r.id!==s)}function Ep(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Kp(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=os(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function Bp(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Qn),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>qr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function Wp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,Ca);if(s.length===0){window.localStorage.removeItem(Qn);return}window.localStorage.setItem(Qn,JSON.stringify(s))}catch{}}function Op(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 Hp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Ca}=e,a=o.useMemo(()=>Lp(s,r),[s,r]),[i,c]=o.useState(()=>Bp());o.useEffect(()=>{c(k=>{const L=_p(k,a,n);return Op(k,L)?k:L})},[a,n]),o.useEffect(()=>{Wp(i)},[i]);const l=o.useMemo(()=>Ep(i),[i]),u=o.useMemo(()=>Kp(i),[i]),p=o.useCallback((k,L)=>{c(d=>Rp(d,k,L))},[]),m=o.useCallback(k=>{c(L=>Pp(L,k))},[]),f=o.useCallback((k,L)=>{c(d=>Dp(d,k,L))},[]),b=o.useCallback(k=>{c(L=>$p(L,k))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:f,deleteNotification:b}}function fc(){return"select_session"}function Up(){return"open_panel"}function Fp({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function zp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ko(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function So(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ia(e){return e instanceof Error?e.message:String(e||"")}function No(e){const s=Ia(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Co(e,s){const r=Ia(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function rn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),b=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const k=o.useCallback(async v=>{if(!s)return!1;const h=v.trim(),C=ha(s);if(Fp({hasMessage:!!h,blockedMessage:C,sendInFlight:f.current}))return C&&m(C),!1;const P=Date.now(),g={tabKey:s.tabKey,message:h,timestamp:P};if(zp(b.current,g))return m(null),!0;f.current=!0,u(!0),m(null),b.current=g;const I=`${P}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:P,_localId:I},w=!0;r(x=>({...x,[g.tabKey]:[...x[g.tabKey]||[],j]}));try{const x=ir(s);if(!x)return b.current=ko(b.current,g),w&&r(T=>({...T,[g.tabKey]:(T[g.tabKey]||[]).filter(M=>M._localId!==I)})),m("Unable to send message right now."),!1;const $=await e(x,"send_chat",{message:h,...As(s)}),N=So($);if(w&&(N!=null&&N.deduplicated))return r(T=>({...T,[g.tabKey]:(T[g.tabKey]||[]).filter(M=>M._localId!==I)})),m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return setTimeout(()=>{const T=Date.now()-6e4;r(M=>{const B=M[g.tabKey];if(!B)return M;const _=B.filter(S=>S.timestamp>T);return _.length===B.length?M:{...M,[g.tabKey]:_}})},6e4),m(null),!0}catch(x){const $=Ia(x);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",x),b.current=ko(b.current,g),r(N=>({...N,[g.tabKey]:(N[g.tabKey]||[]).filter(T=>T._localId!==I)})),m(ju(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),L=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(v){console.error("Relaunch failed",v)}},[s,e]),d=o.useCallback(async v=>{if(s)try{const C=(s.modalButtons||[]).indexOf(v),P=v.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(P),I=ir(s);if(!I)return;const j=await e(I,"resolve_action",{button:v,action:g?"approve":"reject",...C>=0&&{buttonIndex:C},...As(s)}),w=So(j);w.success||n(x=>[...x,{routeId:s.tabKey,text:Co(v,w==null?void 0:w.error),timestamp:Date.now()}])}catch(h){No(h)||console.error("[ModalButton] Error:",h),n(C=>[...C,{routeId:s.tabKey,text:No(h)?Co(v,h):`❌ **${v}** error`,timestamp:Date.now()}])}},[s,e,n]),y=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,Up(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(v){console.error("Focus agent failed",v)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:k,handleRelaunch:L,handleModalButton:d,handleFocusAgent:y}}const Aa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:b,actionLogs:k,userName:L,scrollToBottomRequestNonce:d,isInputActive:y=!0}){const v=ic(s),h=v.status||v.modalMessage||v.modalButtons?{...s,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(pi,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.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(xs,{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,h.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(Uu,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Gn,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:b,actionLogs:k,userName:L,scrollToBottomRequestNonce:d,isInputActive:y})})]}):t.jsx(Gn,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:b,actionLogs:k,userName:L,scrollToBottomRequestNonce:d,isInputActive:y})]})},(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.sendFeedbackMessage===s.sendFeedbackMessage&&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 Vp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:b,onOpenRemote:k,onHideConversation:L,onStopCli:d,cliViewMode:y,onSetCliViewMode:v,handleSendChat:h,handleFocusAgent:C,handleModalButton:P,handleRelaunch:g}){const I=o.useRef(null),j=tt(e)&&!s,w=j&&y==="terminal",x=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 ${x} 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:p,type:"button","aria-label":"Back",children:t.jsx(ra,{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:dt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Ti,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&y&&t.jsx(xa,{mode:y,onChange:v,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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(Nt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:t.jsx(aa,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Tt,{size:14})}),L&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>L(e),type:"button",title:"Close chat",children:t.jsx(Nt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Aa,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:I,handleModalButton:P,handleRelaunch:g,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Cn={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 Gp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function hc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Gp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Cn[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:Cn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Cn[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 xc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Vt}];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 Sr({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 js({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 qs({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 Nr({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}=Os(e.conversation),m=dt(e.conversation),f=gs(e.conversation),b=Bi(e.conversation,{requiresAction:s==="needs_attention"}),k=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",y=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",C="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] ${k}`,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:mi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${y}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} 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…"})]}):b==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,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 Io({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 qp({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:b,onOpenSettings:k,onSectionChange:L,wsStatus:d="connected",isStandalone:y=!1}){const v=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,P=e==="machines"?"Machines":"Chats",g=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=y?"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:P}),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(Zr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,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(Qr,{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] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(qs,{icon:t.jsx(Io,{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(qs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:y?"Waiting for your daemon":"Connect your machines",subtitle:y?"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:!y&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(hc,{})})}):t.jsx(js,{children:c.map((j,w)=>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] ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Needs attention",className:"mb-0"}),t.jsx(js,{children:s.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(js,{children:r.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Sr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(js,{children:n.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.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(Sr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(js,{children:a.map((j,w)=>t.jsx("div",{className:w>0?"border-t border-border-subtle/70":"",children:t.jsx(Nr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(qs,{icon:t.jsx(Io,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(qs,{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(Vt,{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(qs,{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(js,{className:"bg-bg-secondary/25",children:i.map((j,w)=>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 ${w>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(dt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:dt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:gs(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&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(xc,{section:e,onSectionChange:L})]})}function Yp(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 bc(e){const s=[e.workspace||"Workspace unknown"],r=bs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Yp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function nn(...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 Xp(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 an(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Xp(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 Qp(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 Jp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function on(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Jp(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 cn({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 b=Qp(r),k=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(Nt,{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:()=>{!b||a||u(b)},disabled:!b||a,children:[t.jsx(ra,{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"||!k||a||(L.preventDefault(),u(k))},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:()=>{!k||a||u(k)},disabled:!k||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(Ls,{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(k||r),disabled:!k&&!r||a,children:c})]})]})})}function Ma({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:b,modelValue:k,onModelChange:L,historyProviderNode:d,onConfirm:y,onCancel:v}){const h=n==null?void 0:n.find(C=>C.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:v,"aria-label":"Close launch confirmation",children:t.jsx(Nt,{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:C=>i(C.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(C=>t.jsx("option",{value:C.key,children:C.label},C.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(C=>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:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),b&&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:k||"",onChange:C=>L(C.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:C=>f(C.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:v,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:y,disabled:u,children:[t.jsx(oa,{size:14}),u?l:c]})]})]})})}function Ao(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function fs(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?"⭐ ":""}${Ao(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:Ao(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 Zp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function ef(e){return[Zp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function tf(e){return e.lastLaunchedAt?en(e.lastLaunchedAt):""}function gc(e){return{metaText:ef(e),updatedLabel:tf(e)}}function In(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function sf({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,it,ft,ht;const c=ur(),[l,u]=o.useState(!1),p=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),f=e.defaultWorkspaceId||null,[b,k]=o.useState(f||((it=m[0])==null?void 0:it.id)||""),[L,d]=o.useState(""),[y,v]=o.useState(""),[h,C]=o.useState([]),[P,g]=o.useState(!1),[I,j]=o.useState(""),[w,x]=o.useState(!1),[$,N]=o.useState(In(p,s.length,r.length)),T=o.useRef(null),[M,B]=o.useState(null),_=o.useRef("__home__"),[S,O]=o.useState("__home__"),[G,A]=o.useState(""),[K,V]=o.useState(""),[U,ce]=o.useState(""),[Y,oe]=o.useState([]),[Q,te]=o.useState(()=>yt().textQuery),[ue,Ne]=o.useState(()=>yt().workspaceQuery),[le,pe]=o.useState(()=>yt().modelQuery),[ae,z]=o.useState(()=>yt().resumableOnly),[ve,ee]=o.useState(()=>yt().sortMode),[we,re]=o.useState(!1),[ie,ne]=o.useState(!1),je=o.useRef(null),xe=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=b==="__custom__"?L.trim():((ft=m.find(ye=>ye.id===b))==null?void 0:ft.path)||"",ke=b==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),ge=b!=="__custom__"&&((ht=m.find(ye=>ye.id===b))==null?void 0:ht.path)||"",Ce=o.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),J=o.useCallback(async ye=>{g(!0),j("");try{const Ue=await a(ye);v(Ue.path),d(Ue.path),C(Ue.directories)}catch(Ue){j(Ue instanceof Error?Ue.message:"Could not load folder")}finally{g(!1)}},[a]),Me=o.useCallback(()=>{var Ue;k("__custom__"),x(!0);const ye=an(e.platform,nn(L.trim(),ge,Ce,e.defaultWorkspacePath,(Ue=m.find(ze=>ze.id===f))==null?void 0:Ue.path,m.map(ze=>ze.path)));J(ye)},[L,f,J,Ce,ge,e.platform,m]),He=o.useCallback(ye=>{if(ye!=null&&ye.workspaceId){k(ye.workspaceId),d("");return}if(ye!=null&&ye.workspacePath){k("__custom__"),d(ye.workspacePath);return}k(""),d("")},[]),$e=o.useCallback(ye=>{if(k(ye),ye==="__custom__"){Me();return}d("")},[Me]),Ze=o.useCallback(ye=>{k("__custom__"),d(ye)},[]),Ge=o.useCallback((ye,Ue)=>{T.current=Ue,_.current=ye.selectedWorkspaceKey||"__home__",O(ye.selectedWorkspaceKey||"__home__"),A(ye.initialArgs||""),V(ye.initialModel||""),ce(""),oe([]);const ze=ye.providerType?`${e.id}:${ye.providerType}`:null;if(Gu(xe.current,ze)){const Xe=yt();te(Xe.textQuery),Ne(Xe.workspaceQuery),pe(Xe.modelQuery),z(Xe.resumableOnly),ee(Xe.sortMode)}xe.current=ze,B(ye),ye.providerType&&i&&(re(!0),i(ye.providerType).then(Xe=>oe(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>re(!1)))},[i,e.id]),Ye=o.useMemo(()=>Hi(Y,{textQuery:Q,workspaceQuery:ue,modelQuery:le,resumableOnly:ae,sortMode:ve}),[le,ae,Y,ve,Q,ue]);o.useEffect(()=>{U&&(Ye.some(ye=>ye.providerSessionId===U)||ce(""))},[Ye,U]);const ot=o.useCallback(()=>{T.current&&(ne(!0),T.current().finally(()=>{T.current=null,ne(!1),B(null)}))},[]),et=o.useCallback(()=>{T.current=null,B(null)},[]),mt=o.useCallback(ye=>{_.current=ye,O(ye)},[]);return o.useEffect(()=>{var ye;je.current!==e.id&&(je.current=e.id,k(f||((ye=m[0])==null?void 0:ye.id)||"__custom__"),d(""),v(""),C([]),j(""),x(!1),te(yt().textQuery),Ne(yt().workspaceQuery),pe(yt().modelQuery),z(yt().resumableOnly),ee(yt().sortMode),xe.current=null,N(In(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var ye;b!=="__custom__"&&(b&&m.some(Ue=>Ue.id===b)||k(f||((ye=m[0])==null?void 0:ye.id)||"__custom__"))},[f,b,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||N(In(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:b,customWorkspacePath:L,browseCurrentPath:y,browseDirectories:h,browseBusy:P,browseError:I,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:M,launchConfirmWorkspaceKeyRef:_,launchConfirmWorkspaceKey:S,launchConfirmArgs:G,launchConfirmModel:K,launchConfirmResumeId:U,launchConfirmSavedSessions:Y,launchConfirmTextFilter:Q,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:le,launchConfirmResumableOnly:ae,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:Ye,launchConfirmSessionsLoading:we,launchConfirmBusy:ie,resolvedWorkspacePath:E,canCreateMissingWorkspace:ke,openBrowseDialog:Me,loadBrowsePath:J,handleWorkspaceChoiceChange:$e,chooseCustomWorkspacePath:Ze,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:N,openLaunchConfirm:Ge,handleConfirmLaunch:ot,closeLaunchConfirm:et,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:mt,setLaunchConfirmArgs:A,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ce,setLaunchConfirmTextFilter:te,setLaunchConfirmWorkspaceFilter:Ne,setLaunchConfirmModelFilter:pe,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ee}}function rf({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:b,onOpenConversation:k,onOpenRecent:L,onOpenMachineDetails:d,onMachineUpgrade:y,onLaunchDetectedIde:v,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:P,onListSavedSessions:g}){const I=S=>S==="ide"?"IDE":S==="cli"?"CLI":"ACP",j=r.slice(0,4),w=s.slice(0,3),x=sf({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:g}),$=o.useMemo(()=>j.map(S=>{const{metaText:O,updatedLabel:G}=gc(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:O,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:K}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:S.workspace});x.openLaunchConfirm({title:S.kind==="ide"?ds("restart-ide",S.label):S.providerSessionId?ya(S.label):ds("start-fresh",S.label),description:S.kind==="ide"?us("restart-ide"):S.providerSessionId?va():us("start-fresh"),confirmLabel:S.kind==="ide"?Es("restart-ide"):S.providerSessionId?zr(!0):Es("start-fresh"),busyLabel:S.kind==="ide"?Ks("restart-ide"):S.providerSessionId?ba(!0):Ks("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:K,details:[{label:"Mode",value:I(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const V=A.find(U=>U.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(V),await L({...S,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[x,L,j]),N=o.useMemo(()=>w.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:dt(S.conversation),secondary:Bu(S.conversation,{timestampLabel:S.timestamp?mi(S.timestamp):null}),unread:S.unread,onClick:()=>k(S.conversation)})),[k,w]),T=x.showAllRecent?$:$.slice(0,4),M=$.length>0,B=N.length>0,_=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 ${_} 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(ra,{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:Mt(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:[B&&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:N.map(S=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),M&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(S=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:S.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:S.primary}),S.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),$.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(S=>!S),children:x.showAllRecent?"Show fewer":`Show ${$.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:S=>x.handleWorkspaceChoiceChange(S.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(S=>t.jsxs("option",{value:S.id,children:[S.id===x.defaultWorkspaceId?"⭐ ":"",sn(S.path,S.label)||S.path]},S.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(Ls,{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(S=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:O,selectedKey:G}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${S.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:O,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:S.name}]},async()=>{const A=O.find(K=>K.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),v(S.type,{workspacePath:(A==null?void 0:A.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:S.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},S.type)):(x.activeLauncherKind==="cli"?n:a).map(S=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const O=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=fs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${S.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${O.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:O.toUpperCase()},{label:"Provider",value:S.displayName}],showArgsInput:!0,showModelInput:O==="acp",initialArgs:"",initialModel:"",providerType:S.type},async()=>{const K=G.find(V=>V.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(K),P(O,S.type,{workspaceId:(K==null?void 0:K.workspaceId)??null,workspacePath:(K==null?void 0:K.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:[S.icon?`${S.icon} `:"",S.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},S.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,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:y,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(cn,{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:S=>{x.loadBrowsePath(S)},onConfirm:S=>{x.chooseCustomWorkspacePath(S),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(Ma,{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?zr(!!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:ga()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:S=>x.setLaunchConfirmTextFilter(S.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:S=>x.setLaunchConfirmWorkspaceFilter(S.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:S=>x.setLaunchConfirmModelFilter(S.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:S=>x.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:S=>x.setLaunchConfirmResumableOnly(S.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:S=>x.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Xu()}),x.filteredLaunchConfirmSavedSessions.map(S=>t.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.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 S=x.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===x.launchConfirmResumeId);if(!S)return null;const O=bc(S);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),t.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(xc,{section:p,onSectionChange:b})]})}function yc(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 nf(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:bs(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=ar(n)?"cli":Is(n)?"acp":"ide",i=bs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ar(n)?n.cliName||n.type:Is(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Is(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 af(e,s){const r=new Map;for(const n of s){const a=es(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,b)=>b.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Hn(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=yc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Mt(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?Wu(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 Cr(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 of({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:b,onRequestedMobileSectionConsumed:k,setSelectedTabKey:L,setScreen:d,setSelectedMachineId:y,setSection:v,setMachineBackTarget:h,resetMachineAction:C,markNotificationTargetRead:P}){const g=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const w=Hr(j,c),x=Math.max(Date.now(),is(j),w.lastUpdated||0);Cr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:dt(j),inboxBucket:w.inboxBucket,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:is(j),readAt:x}),P({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId}),l(es(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then($=>{Cr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:$})}).catch($=>{Cr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var w;if(!n){d("inbox"),L(((w=e[0])==null?void 0:w.tabKey)||null),g.current=null;return}if(i!=="chat"){g.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;g.current!==j&&(g.current=j,I(n))},[e,I,i,n,d,L]),o.useEffect(()=>{if(!u)return;const j=e.find(w=>w.tabKey===u);j&&(L(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,L]),o.useEffect(()=>{if(!m)return;const j=s.find(w=>w.id===m);j&&(y(j.id),C(),v("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,C,h,d,v,y]),o.useEffect(()=>{b&&(v(b),d("inbox"),k==null||k())},[k,b,d,v]),o.useEffect(()=>{const j=r.filter(w=>w.inboxBucket==="task_complete"||w.unread);j.length!==0&&Cr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(w=>{const x=Hr(w.conversation,c);return{liveState:x,tabKey:w.conversation.tabKey,sessionId:w.conversation.sessionId,displayPrimary:dt(w.conversation),serverBucket:x.inboxBucket,computedBucket:w.inboxBucket,serverUnread:x.unread,computedUnread:w.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:is(w.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function cf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Mo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function df({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,C,P)=>{var g;try{i("loading"),l(`Launching ${C}…`);const I={ideType:C,enableCdp:!0};(g=P==null?void 0:P.workspacePath)!=null&&g.trim()&&(I.workspace=P.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${C} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),b=o.useCallback(async(h,C,P)=>{if(C.trim())try{i("loading"),l(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(P!=null&&P.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]),k=o.useCallback(async h=>{var C,P,g,I,j,w;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((P=x==null?void 0:x.result)==null?void 0:P.version)||"latest"}.`);return}if((g=x==null?void 0:x.result)!=null&&g.upgraded||(I=x==null?void 0:x.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=x==null?void 0:x.result)==null?void 0:w.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),L=o.useCallback(async(h,C,P,g)=>{var w,x,$;const I=Date.now(),j={machineId:h,kind:C,providerType:P,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:I};try{i("loading"),l(`Launching ${P}…`),p(j);const N={cliType:P};(w=g==null?void 0:g.workspacePath)!=null&&w.trim()?N.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(N.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(N.resumeSessionId=g.resumeSessionId),(x=g==null?void 0:g.args)!=null&&x.trim()&&(N.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),($=g==null?void 0:g.model)!=null&&$.trim()&&(N.initialModel=g.model.trim());const T=await e(h,"launch_cli",N),M=(T==null?void 0:T.result)||T,B=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);if(T!=null&&T.success&&B){p(null),i("done"),l(`${P} launched`),s(Jt(B));return}if(T!=null&&T.success){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l((T==null?void 0:T.error)||(M==null?void 0:M.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(N){if(lf(N)){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l(N instanceof Error?N.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,C)=>{try{const P=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),g=(P==null?void 0:P.result)??P;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),y=o.useCallback(async(h,C)=>on(e,h,C),[e]);o.useEffect(()=>{if(!u)return;const h=Mo(u.workspacePath),C=r.find(g=>{var N,T,M,B;if(!g||g.type==="adhdev-daemon"||cf(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const x=String(g.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const _=Mo(g.workspace||g.runtimeWorkspaceLabel);return _?_===h:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((B=(M=(T=(N=g.activeChat)==null?void 0:N.messages)==null?void 0:T.at)==null?void 0:M.call(T,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const P=Mi({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});P&&(p(null),i("done"),l(`${u.providerType} launched`),s(Jt(P)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const v=o.useCallback(async(h,C)=>{if(C.kind==="ide"&&C.providerType){await f(h,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await L(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,L]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:b,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:L,handleListSavedSessions:d,handleBrowseDirectory:y,handleOpenRecent:v}}function uf({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),f=o.useCallback(v=>{const h=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),b=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,h="inbox")=>{l(v),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),L=o.useCallback(v=>{const h=es(v);h&&k(h,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),y=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:b,openMachine:k,openConversationMachine:L,backFromMachine:d,changeMachineSection:y}}function mf(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function pf(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 Ir(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function ff({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:b,requestedMobileSection:k,onRequestedMobileSectionConsumed:L,onOpenHistory:d,onOpenRemote:y,onStopCli:v,wsStatus:h,isConnected:C,onShowHiddenConversation:P,onShowAllHiddenConversations:g,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:w,onMarkNotificationTargetRead:x}){const[$,N]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[T,M]=o.useState(()=>e[0]?"chat":"inbox"),[B,_]=o.useState("chats"),[S,O]=o.useState(null),[G,A]=o.useState("inbox"),K=Bs(),V="0.8.75",U=o.useMemo(()=>e.find(J=>J.tabKey===$)||e[0]||null,[e,$]),ce=o.useMemo(()=>U?r.find(J=>J.id===U.routeId):void 0,[r,U]),Y=o.useMemo(()=>!U||Je(U)||!tt(U)?null:Ps(U),[U]),oe=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(da),[r]),Q=o.useMemo(()=>oe.find(J=>J.id===S)||null,[oe,S]),te=o.useMemo(()=>tn(r),[r]),ue=rn({sendDaemonCommand:a,activeConv:U||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),Ne=df({sendDaemonCommand:a,navigate:K,ides:r,conversations:e}),le=o.useMemo(()=>e.map(J=>{const Me=T==="chat"&&(U==null?void 0:U.tabKey)===J.tabKey,He=la(J,te,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:w}),$e=is(J),Ze=Ki(J);return{conversation:J,timestamp:$e,preview:Ze,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,te,w,T,U]),{markConversationRead:pe}=of({conversations:e,machineEntries:oe,items:le,selectedConversation:U,selectedTabKey:$,screen:T,liveSessionInboxState:te,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:b,requestedMobileSection:k,onRequestedMobileSectionConsumed:L,setSelectedTabKey:N,setScreen:M,setSelectedMachineId:O,setSection:_,setMachineBackTarget:A,resetMachineAction:Ne.resetMachineAction,markNotificationTargetRead:x}),ae=uf({conversations:e,selectedConversation:U,machineBackTarget:G,markConversationRead:pe,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:N,setScreen:M,setSelectedMachineId:O,setSection:_,setMachineBackTarget:A}),z=o.useMemo(()=>Ir(le.filter(J=>J.requiresAction)),[le]),ve=o.useMemo(()=>Ir(le.filter(J=>J.unread&&!J.requiresAction)),[le]),ee=o.useMemo(()=>Ir(le.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[le]),we=o.useMemo(()=>Ir(le.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[le]),re=o.useMemo(()=>Q?le.filter(J=>es(J.conversation)===Q.id):[],[le,Q]),ie=o.useMemo(()=>nf(Q,r),[r,Q]),ne=(Q==null?void 0:Q.version)||null,je=!!Q&&!!ne&&!0&&ne!==V,xe=o.useMemo(()=>(Q==null?void 0:Q.availableProviders)||[],[Q]),E=o.useMemo(()=>xe.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ke=o.useMemo(()=>xe.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[xe]),ge=o.useMemo(()=>af(oe,le),[le,oe]),Ce=o.useCallback(async J=>{Q&&await Ne.handleOpenRecent(Q.id,J)},[Ne,Q]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&U?t.jsx(Vp,{selectedConversation:U,isAcp:Je(U),isStandalone:l,selectedIdeEntry:ce,actionLogs:n,userName:u,isSendingChat:ue.isSendingChat,sendFeedbackMessage:ue.sendFeedbackMessage,isFocusingAgent:ue.isFocusingAgent,handleModalButton:ue.handleModalButton,handleRelaunch:ue.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:y,onStopCli:v,cliViewMode:Y,onSetCliViewMode:async J=>{if(U&&Y!==J)try{await a(es(U)||U.routeId,"set_cli_view_mode",{targetSessionId:U.sessionId,cliType:$t(U),mode:J})}catch(Me){pf(Me)?console.warn("Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:ue.handleSendChat,handleFocusAgent:ue.handleFocusAgent}):T==="machine"&&Q?t.jsx(rf,{selectedMachineEntry:Q,selectedMachineConversations:re,selectedMachineRecentLaunches:ie,cliProviders:E,acpProviders:ke,selectedMachineNeedsUpgrade:je,appVersion:V,machineAction:Ne.machineAction,isStandalone:l,section:B,showBottomNav:G==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:Ce,onOpenMachineDetails:()=>K(`/machines/${Q.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(Q.id),onLaunchDetectedIde:(J,Me)=>Ne.handleLaunchDetectedIde(Q.id,J,Me),onAddWorkspace:(J,Me)=>Ne.handleAddWorkspace(Q.id,J,Me),onBrowseDirectory:J=>Ne.handleBrowseDirectory(Q.id,J),onLaunchWorkspaceProvider:(J,Me,He)=>Ne.handleLaunchWorkspaceProvider(Q.id,J,Me,He),onListSavedSessions:J=>Ne.handleListSavedSessions(Q.id,J)}):t.jsx(qp,{section:B,attentionItems:z,unreadItems:ve,workingItems:ee,completedItems:we,hiddenConversations:s,machineCards:ge,getAvatarText:mf,onOpenConversation:ae.openConversation,onShowConversation:P,onShowAllHidden:g,onOpenNewSession:j,onOpenMachine:ae.openMachine,onOpenSettings:()=>K("/settings"),onSectionChange:_,wsStatus:h,isConnected:C,isStandalone:l})})}function An(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function hf({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 b=o.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!An(s,r)){m("merge");return}const v=y.currentTarget.getBoundingClientRect(),h=y.clientX-v.left,C=v.width/3;h<C?m("split-left"):h>C*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(y=>{c.current=0,u(!1);const v=y.dataTransfer.getData("text/tab-key"),h=v?e.some(P=>P.tabKey===v):!1,C=p;if(m(null),i(),!!v){if(y.preventDefault(),C==="split-left"&&An(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&An(s,r)){r==null||r(v,"split-right");return}if(h){a(v);return}n==null||n(v)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:b,handleDragOver:k,handleDragLeave:L,handleDrop:d}}function xf(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 bf({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),b=o.useRef(null),k=o.useRef(n),L=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{L.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const w=xf(j,e);return w.length===j.length&&w.every((x,$)=>x===j[$])?j:w})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const w=new Map(j.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const N=w.get(x.tabKey)??999,T=w.get($.tabKey)??999;return N-T})},[e,p,l]);o.useEffect(()=>{var w,x;if(d.length===0){i!==null&&(c(null),(w=k.current)==null||w.call(k,null));return}if(i&&d.some($=>$.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const y=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),v=o.useCallback(j=>{var w;c(j),(w=k.current)==null||w.call(k,j)},[]),h=o.useCallback((j,w,x)=>{u($=>{var B;const N=$.filter(_=>_!==j),T=N.indexOf(w);if(T<0)return $;const M=x==="left"?T:T+1;return N.splice(M,0,j),(B=L.current)==null||B.call(L,N),N}),m(null)},[]),C=o.useCallback((j,w,x)=>{const N=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),T=N.indexOf(w);if(T<0)return;const M=x==="left"?T:T+1;N.splice(M,0,j),f.current=N,m(N)},[l,e]),P=o.useCallback(()=>{var w;const j=f.current;j&&(u(j),(w=L.current)==null||w.call(L,j))},[]),g=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(w=>{var $;const x=w.filter(N=>N!==j);return x.push(j),($=L.current)==null||$.call(L,x),x})},[]);return{activeTabId:i,activeConv:y,sortedConversations:d,previewOrderRef:f,draggingTabRef:b,selectTab:v,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:P,clearPreviewOrder:g,moveTabToEnd:I,setDraggingTabKey:j=>{b.current=j}}}function gf({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 Ta({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(hc,{}),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 vc="adhdev-tab-shortcuts";function wc(){try{return JSON.parse(localStorage.getItem(vc)||"{}")}catch{return{}}}function jc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>wc()),[l,u]=o.useState(null),p=o.useCallback(f=>{const b=[];return f.metaKey&&b.push(a?"⌘":"Meta"),f.ctrlKey&&b.push("Ctrl"),f.altKey&&b.push(a?"⌥":"Alt"),f.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(b.push(f.key.length===1?f.key.toUpperCase():f.key),b.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(vc,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){u(null);return}const k=p(b);if(!k)return;const L={...i};for(const[d,y]of Object.entries(L))y===k&&delete L[d];L[l]=k,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=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[k,L]of Object.entries(i))if(s.includes(k)&&p(b)===L){b.preventDefault(),r(),n(k);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 yf=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:b,onCommitPreviewOrder:k,onClearPreviewOrder:L,onDragStateReset:d,onDragTabKeyChange:y,onReceiveTab:v,onOpenContextMenu:h,longPressTimer:C,isGroupActive:P}){const g=Os(s),I=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",j=g.isReconnecting,w=o.useCallback(O=>{l.current=s.tabKey,y(s.tabKey),O.dataTransfer.setData("text/tab-key",s.tabKey),O.dataTransfer.effectAllowed="move"},[s.tabKey,l,y]),x=o.useCallback(()=>{l.current=null,y(null),k(),L(),d()},[l,y,k,L,d]),$=o.useCallback(O=>{const G=l.current;if(!(!G||G===s.tabKey)&&O.dataTransfer.types.includes("text/tab-key")){O.preventDefault(),O.stopPropagation();const A=O.currentTarget.getBoundingClientRect(),K=O.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,K)}},[s.tabKey,l,f]),N=o.useCallback(O=>{O.preventDefault(),O.stopPropagation();const G=O.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=O.currentTarget.getBoundingClientRect(),K=O.clientX<A.left+A.width/2?"left":"right";c.includes(G)?b(G,s.tabKey,K):v&&v(G)}L()},[s.tabKey,c,b,v,L]),T=o.useCallback(O=>{O.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),M=o.useCallback(O=>{O.preventDefault(),h(O.clientX,O.clientY,s.tabKey)},[s.tabKey,h]),B=o.useCallback(O=>{const G=O.touches[0];C.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,C,h]),_=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),S=["adhdev-dockview-tab",I,r&&"is-active",P&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:S,draggable:!0,onDragStart:w,onDragEnd:x,onDragOver:$,onDrop:N,onClick:T,onContextMenu:M,onTouchStart:B,onTouchEnd:_,onTouchMove:_,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:"▲"}):j?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:dt(s),children:dt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ls(s)}):g.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ls(s),t.jsx("span",{className:"connecting-dots"})]}):ls(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 vf({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:b,onDragTabKeyChange:k,onReceiveTab:L,onHideTab:d,isGroupActive:y,allowTabShortcuts:v=!0}){const[h,C]=o.useState(null),P=o.useRef(null),g=o.useRef(null),I=o.useMemo(()=>e.map(M=>M.tabKey),[e]);cr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:w,shortcutListening:x,setShortcutListening:$,saveShortcuts:N}=jc({enabled:v,sortedTabKeys:e.map(M=>M.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const M=B=>{const _=document.querySelector("[data-pane-context-menu]");_&&_.contains(B.target)||C(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[h]),o.useEffect(()=>{const M=g.current;if(!M)return;const B=_=>{Math.abs(_.deltaY)<=Math.abs(_.deltaX)||(_.preventDefault(),M.scrollLeft+=_.deltaY)};return M.addEventListener("wheel",B,{passive:!1}),()=>M.removeEventListener("wheel",B)},[]);const T=o.useCallback((M,B,_)=>{C({x:M,y:B,tabKey:_})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>t.jsx(yf,{conv:M,isActive:s===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:v?w[M.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:b,onDragTabKeyChange:k,onReceiveTab:L,onOpenContextMenu:T,longPressTimer:P,isGroupActive:y},M.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:[v&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:M=>{M.stopPropagation(),$(h.tabKey),C(null)},children:["⌨ ",w[h.tabKey]?`Change shortcut (${w[h.tabKey]})`:"Set shortcut"]}),w[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 M={...w};delete M[h.tabKey],N(M),C(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[v&&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),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function wf({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:b,numGroups:k,onMoveTab:L,onReceiveTab:d,style:y,onActiveTabChange:v,initialActiveTabId:h,initialTabOrder:C,onTabOrderChange:P,onHideTab:g,isFocused:I,allowTabShortcuts:j=!0}){const{sendCommand:w}=Lt(),x=o.useRef(null),{activeTabId:$,activeConv:N,sortedConversations:T,draggingTabRef:M,selectTab:B,handleTabReorder:_,updatePreviewOrder:S,commitPreviewOrder:O,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:K}=bf({conversations:e,initialActiveTabId:h,initialTabOrder:C,onActiveTabChange:v,onTabOrderChange:P}),V=rn({sendDaemonCommand:a,activeConv:N,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:U,dropAction:ce,resetDragState:Y,handleDragEnter:oe,handleDragOver:Q,handleDragLeave:te,handleDrop:ue}=hf({conversations:e,numGroups:k,onMoveTab:L,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),Ne=N&&!Je(N)&&Ps(N)==="terminal",le=o.useMemo(()=>N?s.find(ee=>ee.id===N.routeId):void 0,[s,N]),pe=o.useMemo(()=>N?n.filter(ee=>ee.routeId===N.tabKey):[],[n,N]),ae=o.useMemo(()=>tn(s),[s]),z=o.useMemo(()=>new Set(T.filter(ee=>xd(ee,ae,{isOpenConversation:ee.tabKey===$})).map(ee=>ee.tabKey)),[$,ae,T]);cr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:$,dragOver:U});const ve=o.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&w(ee.routeId,fc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[w]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...y,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(vf,{conversations:T,activeTabId:$,groupIndex:m,numGroups:k,unreadTabKeys:z,draggingTabRef:M,onFocus:f,onSelectTab:B,onConversationActivated:ve,onPreviewReorder:S,onReorderTab:_,onCommitPreviewOrder:O,onClearPreviewOrder:G,onDragStateReset:Y,onDragTabKeyChange:K,onMoveTab:L,onReceiveTab:d,onHideTab:g,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:oe,onDragOver:Q,onDragLeave:te,onDrop:ue,children:[U&&t.jsx(gf,{dropAction:ce,canSplit:!!(k<4&&L)}),N?t.jsx(Aa,{activeConv:N,clearToken:r[N.tabKey]||0,isCliTerminal:!!Ne,ideEntry:le,terminalRef:x,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,sendFeedbackMessage:V.sendFeedbackMessage,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:pe,userName:p,isInputActive:!b||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:e.length,isSplitMode:b,isStandalone:l,hasRegisteredMachines:u})})]})]})}function jf({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:b,userName:k,focusedGroup:L,setFocusedGroup:d,moveTabToGroup:y,splitTabRelative:v,closeGroup:h,handleResizeStart:C,groupActiveTabIds:P,setGroupActiveTabIds:g,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:w,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(($,N)=>{const T=s&&n.length===r?`${n[N]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&N>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:M=>C(N-1,M),onDoubleClick:()=>h(N),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(wf,{style:s?{flexBasis:T??`${100/r}%`,flexGrow:T?0:1,flexShrink:T?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:b,userName:k,groupIndex:N,isFocused:s&&L===N,onFocus:()=>d(N),isSplitMode:s,numGroups:r,onMoveTab:(M,B)=>{B==="left"&&N>0?y(M,N-1):B==="right"&&N<r-1?y(M,N+1):B==="split-left"&&r<4?v(M,N,"left"):B==="split-right"&&r<4&&v(M,N,"right")},onReceiveTab:M=>y(M,N),onActiveTabChange:M=>g(B=>(B[N]??null)===(M??null)?B:{...B,[N]:M}),initialActiveTabId:P[N],initialTabOrder:I[N],onTabOrderChange:M=>j(B=>{const _=B[N]||[];return _.length===M.length&&_.every((S,O)=>S===M[O])?B:{...B,[N]:M}}),onHideTab:w,allowTabShortcuts:x})]},N)})})}function kc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ut.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const b=new FileReader;b.onload=()=>i(b.result),b.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ut.onStatus)==null?void 0:m.call(ut,(f,b)=>{f===e&&b!=null&&b.screenshotUsage&&l(b.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ut.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?ut.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 Sc="adhdev-dashboard-action-shortcuts",kf=1200,Sf={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Nf(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 Nc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Jn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Yr(e){const s=Object.fromEntries(Nc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Sc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Sf))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Cc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Cf({enabled:e=!0,onTrigger:s}){const r=Nf(),[n,a]=o.useState(()=>Yr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const y=[];return d.metaKey&&y.push(r?"⌘":"Meta"),d.ctrlKey&&y.push("Ctrl"),d.altKey&&y.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&y.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(y.push(Cc(d.key)),y.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(Sc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Yr(r),y=Object.entries(n),v=Object.entries(d);y.length===v.length&&y.every(([h,C])=>d[h]===C)||f(d)},[n,r,f]);const b=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},kf))},[]);o.useEffect(()=>{if(!i)return;const d=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){c(null),u([]);return}const v=m(y);if(!v)return;const C=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const g=[...l,v].slice(0,2).join(" "),I={...n};for(const[j,w]of Object.entries(I))w===g&&delete I[j];I[i]=g,f(I),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=y=>{if(y.defaultPrevented)return;const v=m(y);if(!v)return;const h=y.metaKey||y.ctrlKey||y.altKey;if(Jn(y.target)&&!h)return;const C=p.current.parts,P=h?[v]:[...C.slice(-1),v].slice(-2),g=P.join(" "),I=P[P.length-1],j=Object.entries(n).filter(([,T])=>!!T),w=j.find(([,T])=>T===g);if(w){y.preventDefault(),b(),s(w[0]);return}if(j.some(([,T])=>T.startsWith(`${g} `))){y.preventDefault(),p.current.parts=P,k();return}const $=j.find(([,T])=>T===I);if($){y.preventDefault(),b(),s($[0]);return}if(j.some(([,T])=>T.startsWith(`${I} `))){y.preventDefault(),p.current.parts=[I],k();return}b()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,b,i]),o.useEffect(()=>()=>b(),[b]);const L=o.useMemo(()=>Nc(r),[r]);return{isMac:r,actionDefinitions:L,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function If({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}function Af(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function To({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Af(n):!0}const Ic=o.createContext(null);function ln(){const e=o.useContext(Ic);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Er(e){return dt(e)||e.tabKey}function Mf(e){return`remote:${e}`}function Yt(e){return e.startsWith("remote:")}function Lo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mn(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 Ar(e,s){e.classList.remove(Bn.className,Wn.className),e.classList.add(s==="light"?Bn.className:Wn.className)}function _o(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 Tf(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 Lf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Er(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Ro(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Yt(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!==Er(n)&&a.api.setTitle(Er(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Er(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 Po(e,s,r){var u,p;const n=r?Mf(r):null;for(const m of[...e.panels])Yt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Kt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Oi(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=>!Yt(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 _f({params:e,api:s}){var f;const r=ln(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=rn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const b=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of b)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(b=>b.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(b=>b.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(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Je(c)&&Ps(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Aa,{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 Rf({params:e}){var u;const s=ln(),r=o.useMemo(()=>Kt([...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}=kc({doId:a,targetSessionId:r?Ci(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(ci,{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 Pf(){const e=ln();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Df(e){var k,L;Tf(e);const s=ln(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Kt([...s.conversationsByTabKey.values()],e.params.routeId),y=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${v?" 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=la(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,b=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:dt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var y;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((y=d.target)==null?void 0:y.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:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ls(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ls(n)}):t.jsx("span",{children:ls(n)})})]}),b&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function $f({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:b,registerActionHandlers:k,onActiveTabChange:L,requestedActiveTabKey:d,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:v,scrollToBottomRequest:h,notificationStateBySessionId:C}){var It,q,Ee;const{theme:P}=ka(),{sendCommand:g}=Lt(),I=o.useRef(null),j=o.useRef(null),w=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),N=o.useRef(null),T=o.useRef([]),[M,B]=o.useState(null),[_,S]=o.useState(!1),[O,G]=o.useState(!1),[A,K]=o.useState(0),V=o.useRef(null),U=o.useMemo(()=>dc(typeof window<"u"?window.innerWidth:1280),[]),ce=o.useRef(typeof window>"u"?{}:xp(U)),Y=o.useMemo(()=>new Map(e.map(R=>[R.tabKey,R])),[e]),oe=o.useMemo(()=>tn(r),[r]),Q=o.useMemo(()=>{const R=I.current;return R?R.groups.some(W=>{try{const H=W.model.location.type;return H!=="floating"&&H!=="popout"?!1:W.panels.some(F=>Y.has(F.id))}catch{return!1}}):!1},[Y,A,e]),te=o.useCallback(()=>{var R;(R=I.current)==null||R.focus()},[]),ue=o.useCallback(R=>{const W=document,H=R.document;for(const Ie of W.querySelectorAll('link[rel="stylesheet"]')){const We=H.createElement("link");We.rel="stylesheet",We.href=Ie.href,Ie.crossOrigin&&(We.crossOrigin=Ie.crossOrigin),H.head.appendChild(We)}for(const Ie of W.querySelectorAll("style")){const We=H.createElement("style");We.textContent=Ie.textContent,H.head.appendChild(We)}const F=[];for(const Ie of W.styleSheets)try{for(const We of Ie.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&F.push(We.cssText)}catch{}if(F.length>0){const Ie=H.createElement("style");Ie.textContent=F.join(`
|
|
44
44
|
`),H.head.appendChild(Ie)}const se=W.documentElement.getAttribute("data-theme");se&&H.documentElement.setAttribute("data-theme",se),H.documentElement.style.colorScheme=se==="light"?"light":"dark",H.body.className=W.body.className;const Se=W.documentElement.getAttribute("style");Se&&H.documentElement.setAttribute("style",Se);const Te=H.getElementById("dv-popout-window");Te instanceof HTMLElement&&(Te.classList.add("adhdev-dockview"),Ar(Te,P))},[P]),Ne=o.useCallback(()=>{var W;const R=I.current;if(R)for(const H of R.groups)try{const F=(W=H.element)==null?void 0:W.ownerDocument;if(!F||F===document)continue;const se=F.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),Ar(se,P));const Se=document.documentElement.getAttribute("data-theme");Se&&F.documentElement.setAttribute("data-theme",Se),F.documentElement.style.colorScheme=Se==="light"?"light":"dark",F.body.className=document.body.className;const Te=document.documentElement.getAttribute("style");Te?F.documentElement.setAttribute("style",Te):F.documentElement.removeAttribute("style")}catch{}},[P]),le=o.useCallback(()=>{var W;const R=I.current;if(R)for(const H of R.groups)try{const F=(W=H.element)==null?void 0:W.ownerDocument;if(!F||F===document)continue;const se=F.getElementById("dv-popout-window");if(!(se instanceof HTMLElement))continue;se.classList.add("adhdev-dockview"),Ar(se,P),se.classList.toggle("is-showing-dockview-overlay",O),se.classList.toggle("is-dragging-dockview",_)}catch{}},[_,O,P]),pe=o.useCallback(R=>{const W=I.current;if(!W)return;const H=W.getPanel(R);H&&W.addPopoutGroup(H,{popoutUrl:"/popout.html",onDidOpen:({window:F})=>{ue(F),je();const se=Y.get(R);F.document.title=se?`${dt(se)} — ADHDev`:"ADHDev — Popout"}})},[Y,ue]),ae=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);if(!W||!H)return;const F=W.groups.filter(se=>{var Se;try{return((Se=se.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});F.length>0?H.api.moveTo({group:F[0],position:"center"}):H.api.moveTo({position:"center"}),H.api.setActive()},[]),z=o.useCallback(R=>{var F;const W=I.current;if(!W)return!1;const H=W.getPanel(R);if(!H)return!1;try{return((F=H.group.element)==null?void 0:F.ownerDocument)!==document}catch{return!1}},[]),ve=o.useCallback(R=>{z(R)&&ae(R),f(R)},[z,ae,f]),ee=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);!W||!H||W.addFloatingGroup(H,{width:600,height:500})},[]),we=o.useCallback(R=>{var H;const W=(H=I.current)==null?void 0:H.getPanel(R);if(!W)return!1;try{return W.group.model.location.type==="floating"}catch{return!1}},[]),re=o.useCallback(()=>{var W,H;const R=(H=(W=I.current)==null?void 0:W.activePanel)==null?void 0:H.id;return!R||Yt(R)?null:Y.has(R)?R:null},[Y]),ie=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.getPanel(R);if(!W||!H)return;const F=W.groups.filter(se=>{try{return se.model.location.type==="grid"}catch{return!0}});F.length>0?H.api.moveTo({group:F[0],position:"center"}):H.api.moveTo({position:"center"}),H.api.setActive()},[]),ne=o.useCallback(()=>{var Se;const R=I.current;if(!R)return;const H=R.groups.filter(Te=>{var Ie;try{return((Ie=Te.element)==null?void 0:Ie.ownerDocument)===document&&Te.model.location.type==="grid"}catch{return!1}})[0]||null,F=[...R.panels];for(const Te of F){const Ie=(Se=Te.group.element)==null?void 0:Se.ownerDocument,We=Te.group.model.location.type;Ie===document&&We==="grid"||(H&&H.id!==Te.group.id?Te.api.moveTo({group:H,position:"center"}):Te.api.moveTo({position:"center"}))}const se=R.activePanel;se&&(se.group.model.openPanel(se),se.api.setActive()),Mn(document)},[]),je=o.useCallback(()=>{var W,H;const R=I.current;if(R)for(const F of R.groups){const se=(W=F.element)==null?void 0:W.ownerDocument;if(!se||se===document)continue;const Se=se.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Te=null,Ie=se.title||"ADHDev",We="Popout workspace";const Ke=F.activePanel;if(Ke)if(Te=Ke.id,Yt(Ke.id)){const Oe=((H=Ke.params)==null?void 0:H.routeId)||Ke.id.slice(7),De=Kt([...Y.values()],Oe);Ie=Oi(De),We=De!=null&&De.machineName?`Remote view · ${De.machineName}`:"Remote view"}else{const Oe=Y.get(Ke.id);Ie=Oe?dt(Oe):Ke.title||Ke.id,We=Oe?ls(Oe):"Dockview panel"}se.title=`${Ie} — ADHDev`;let Ae=se.getElementById("adhdev-popout-header");Ae instanceof HTMLElement||(Ae=se.createElement("div"),Ae.id="adhdev-popout-header",se.body.appendChild(Ae)),Ae.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(";")),Ae.innerHTML=`
|
|
45
45
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
46
46
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -51,22 +51,22 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
|
|
|
51
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
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
53
|
</div>
|
|
54
|
-
`,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const Z=Ae.querySelector("[data-adhdev-popout-focus]");Z&&(Z.onclick=()=>{window.focus()});const Re=Ae.querySelector("[data-adhdev-popout-dock]");Re&&(Re.disabled=!Te,Re.style.opacity=Te?"1":"0.5",Re.style.cursor=Te?"pointer":"default",Re.onclick=()=>{var Oe;Te&&ae(Te),(Oe=se.defaultView)==null||Oe.focus()})}},[Y,ae]),xe=o.useCallback(R=>{var F;const W=I.current,H=W==null?void 0:W.getPanel(R);if(!(!W||!H)){H.group.model.openPanel(H),H.api.setActive();try{const se=H.group.model.location;se.type==="popout"?se.getWindow().focus():Mn((F=H.group.element)==null?void 0:F.ownerDocument)}catch{}}},[]),E=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.activePanel,F=(W==null?void 0:W.activeGroup)||(H==null?void 0:H.group);if(!W||!H||!F)return;const se=F.panels||[];if(se.length<=1)return;const Se=se.findIndex(We=>We.id===H.id);if(Se<0)return;const Te=(Se+R+se.length)%se.length,Ie=se[Te];Ie&&(Ie.group.model.openPanel(Ie),Ie.api.setActive())},[]),ke=o.useCallback(R=>{var Re;const W=I.current,H=(W==null?void 0:W.activeGroup)||((Re=W==null?void 0:W.activePanel)==null?void 0:Re.group);if(!W||!H)return;const F=W.groups||[],se=F.find(Oe=>Oe.id===H.id);if(!se)return;const Se=se.element.getBoundingClientRect(),Te=Se.left+Se.width/2,Ie=Se.top+Se.height/2,We=(Oe,De,xt,D)=>Math.max(0,Math.min(De,D)-Math.max(Oe,xt)),Ke=Oe=>{const De=Oe.element.getBoundingClientRect(),xt=De.left+De.width/2,D=De.top+De.height/2;let X=0,de=0,Pe=0,fe=!1;if(R==="left"?(fe=xt<Te,X=Math.max(0,Se.left-De.right),de=Math.abs(D-Ie),Pe=We(Se.top,Se.bottom,De.top,De.bottom)):R==="right"?(fe=xt>Te,X=Math.max(0,De.left-Se.right),de=Math.abs(D-Ie),Pe=We(Se.top,Se.bottom,De.top,De.bottom)):R==="above"?(fe=D<Ie,X=Math.max(0,Se.top-De.bottom),de=Math.abs(xt-Te),Pe=We(Se.left,Se.right,De.left,De.right)):(fe=D>Ie,X=Math.max(0,De.top-Se.bottom),de=Math.abs(xt-Te),Pe=We(Se.left,Se.right,De.left,De.right)),!fe)return Number.POSITIVE_INFINITY;const he=Pe>0?0:120;return X*3+de+he};let Ae=null,Z=Number.POSITIVE_INFINITY;for(const Oe of F){if(Oe.id===se.id)continue;const De=Ke(Oe);Number.isFinite(De)&&(De>=Z||(Z=De,Ae=Oe))}return Ae||void 0},[]),ge=o.useCallback(R=>{var F;const W=ke(R);if(!W)return;const H=W.activePanel||W.panels[0];H&&(W.model.openPanel(H),H.api.setActive(),Mn((F=W.element)==null?void 0:F.ownerDocument))},[ke]),Ce=o.useCallback((R,W)=>{const H=I.current,F=H==null?void 0:H.activePanel,se=(H==null?void 0:H.activeGroup)||(F==null?void 0:F.group);if(!H||!F||!se)return;let Se=ke(R);!Se&&(W!=null&&W.createGroupIfMissing)&&(Se=H.addGroup({referenceGroup:se,direction:R})),Se&&(F.api.moveTo({group:Se,position:"center"}),F.group.model.openPanel(F),F.api.setActive())},[ke]),{isMac:J,tabShortcuts:Me,shortcutListening:He,setShortcutListening:$e,saveShortcuts:Ze}=jc({sortedTabKeys:e.map(R=>R.tabKey),onFocus:te,onSelectTab:xe}),Ge=o.useCallback(()=>{var H;const R=I.current;if(!R)return;const W=R.activePanel;if(W){if(Yt(W.id)){const F=((H=W.params)==null?void 0:H.routeId)||W.id.slice(7),se=Kt(e,F);se!=null&&se.tabKey&&$e(se.tabKey);return}Y.has(W.id)&&$e(W.id)}},[Y,xe,$e,e]),Ye=o.useCallback(R=>{const W=[];return R.metaKey&&W.push(J?"⌘":"Meta"),R.ctrlKey&&W.push("Ctrl"),R.altKey&&W.push(J?"⌥":"Alt"),R.shiftKey&&R.key.length!==1&&W.push(J?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(R.key)?null:(W.push(Cc(R.key)),W.join("+"))},[J]),ot=o.useCallback(R=>{var W,H;switch(R){case"splitActiveTabRight":Ce("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ce("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const F=re();F&&ee(F);return}case"popoutActiveTab":{const F=re();F&&pe(F);return}case"dockActiveTab":{const F=re();if(!F)return;z(F)?ae(F):we(F)&&ie(F);return}case"focusLeftPane":ge("left");return;case"focusRightPane":ge("right");return;case"focusUpPane":ge("above");return;case"focusDownPane":ge("below");return;case"moveActiveTabToLeftPane":Ce("left");return;case"moveActiveTabToRightPane":Ce("right");return;case"moveActiveTabToUpPane":Ce("above");return;case"moveActiveTabToDownPane":Ce("below");return;case"selectPreviousGroupTab":E(-1);return;case"selectNextGroupTab":E(1);return;case"setActiveTabShortcut":Ge();return;case"hideCurrentTab":{const F=(H=(W=I.current)==null?void 0:W.activePanel)==null?void 0:H.id;F&&!Yt(F)&&ve(F);return}default:return}},[E,ie,ge,ee,re,ve,we,z,ae,Ce,pe,Ge]);o.useEffect(()=>{if(!M)return;const R=M.sourceDocument,W=R.defaultView??window,H=F=>{const se=R.querySelector("[data-dockview-tab-context-menu]");se&&se.contains(F.target)||B(null)};return W.addEventListener("mousedown",H,!0),W!==window&&window.addEventListener("mousedown",()=>B(null),!0),()=>{W.removeEventListener("mousedown",H,!0),W!==window&&window.removeEventListener("mousedown",()=>B(null),!0)}},[M]);const et=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:Y,hasDetachedConversationPanels:Q,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:oe,notificationStateBySessionId:C,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ve,userName:m,scrollToBottomRequest:h,tabShortcuts:Me,openTabContextMenu:({x:R,y:W,tabKey:H,sourceDocument:F})=>B({x:R,y:W,tabKey:H,sourceDocument:F??document}),popoutTab:pe,moveTabBackToMain:ae,isTabInPopout:z,floatTab:ee,isTabFloating:we}),[n,s,Y,Q,r,l,u,oe,C,a,c,i,ve,m,h,Me,pe,ae,z,ee,we]),mt=M?If({isTabInPopout:z(M.tabKey),isTabFloating:we(M.tabKey),tabShortcut:Me[M.tabKey],actionShortcuts:y}):[],Ve=o.useCallback(R=>{var F;const W=I.current;if((((F=W==null?void 0:W.activePanel)==null?void 0:F.id)??null)===R.id){R.group.model.openPanel(R);return}R.group.model.openPanel(R),R.api.setActive()},[]),it=o.useCallback(R=>{if(!R)return!1;const W=I.current;if(!W)return!1;const H=W.getPanel(R);return H?(Ve(H),v==null||v(),!0):!1},[Ve,v]),ft=o.useCallback(()=>{if($.current)return!1;const R=it(N.current);return R&&($.current=!0),R},[it]),ht=o.useCallback(()=>{var W;const R=I.current;R&&hp(U,{activeTabId:((W=R.activePanel)==null?void 0:W.id)??null,layout:R.toJSON()})},[U]),ye=o.useCallback(()=>{bp(U,ce.current)},[U]),Ue=o.useCallback(R=>{var F,se,Se,Te;const W=I.current;if(!W)return{kind:"grid"};const H=W.toJSON();for(const Ie of H.floatingGroups||[])if((se=(F=Ie.data)==null?void 0:F.views)!=null&&se.includes(R)&&Ie.position)return{kind:"floating",position:Ie.position};for(const Ie of H.popoutGroups||[])if((Te=(Se=Ie.data)==null?void 0:Se.views)!=null&&Te.includes(R))return{kind:"popout",position:Ie.position,popoutUrl:Ie.url};return{kind:"grid"}},[]),ze=o.useCallback(R=>{const W=I.current;if(!W)return;const H=W.getPanel(R),F=ce.current[R];if(!H||!F||F.kind==="grid")return;if(H.group.model.location.type===F.kind){delete ce.current[R],ye();return}if(F.kind==="floating"){W.addFloatingGroup(H,{x:F.position.left??24,y:F.position.top??24,width:F.position.width,height:F.position.height}),delete ce.current[R],ye();return}delete ce.current[R],ye()},[ye]);o.useEffect(()=>(k==null||k({setShortcutForActiveTab:Ge,restoreHiddenTabToSavedLocation:ze,activateConversationTab:xe,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>E(-1),activateNextTabInGroup:()=>E(1),floatActiveTab:()=>{const R=re();R&&ee(R)},popoutActiveTab:()=>{const R=re();R&&pe(R)},dockActiveTab:()=>{const R=re();R&&(z(R)?ae(R):we(R)&&ie(R))},splitActiveTabRight:()=>Ce("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ce("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ge("left"),focusRightPane:()=>ge("right"),focusUpPane:()=>ge("above"),focusDownPane:()=>ge("below"),moveActiveTabToLeftPane:()=>Ce("left"),moveActiveTabToRightPane:()=>Ce("right"),moveActiveTabToUpPane:()=>Ce("above"),moveActiveTabToDownPane:()=>Ce("below")}),()=>k==null?void 0:k(null)),[E,ie,ee,ge,re,we,z,Ce,ae,pe,k,ne,ze,xe,Ge]);const Xe=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const H of W)H.setAttribute("data-adhdev-force-hidden","true")},[]),pt=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const H of W)H.removeAttribute("data-adhdev-force-hidden")},[]),gt=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll(".dv-drop-target-container");for(const se of W)se.remove();const H=R.querySelectorAll(".dv-drop-target-dropzone");for(const se of H)se.remove();const F=R.querySelectorAll(".dv-drop-target");for(const se of F)se.classList.remove("dv-drop-target")},[]),vt=o.useCallback(()=>{S(!1),G(!1),pt(),Xe(),gt(),!(typeof window>"u")&&(V.current!=null&&window.clearTimeout(V.current),window.requestAnimationFrame(()=>{Xe(),gt()}),V.current=window.setTimeout(()=>{Xe(),gt(),V.current=null},80))},[pt,Xe,gt]),Ot=o.useCallback(R=>{var H;I.current=R.api;const W=fp(U);if(N.current=(W==null?void 0:W.activeTabId)??null,W!=null&&W.layout&&R.api.fromJSON(W.layout,{reuseExistingPanels:!1}),x.current=To({hasStoredLayout:!!(W!=null&&W.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),x.current||(Ro(R.api,e),Po(R.api,e,g)),R.api.totalPanels===0&&e.length>0){const F=Lf(R.api,e,d);if(F){const se=R.api.getPanel(F);se&&Ve(se)}}else!x.current&&!it(d)&&ft();w.current=!0,R.api.onDidActivePanelChange(F=>{var Se;if(N.current=(F==null?void 0:F.id)??null,$.current=!0,je(),F&&Yt(F.id)){const Te=((Se=F.params)==null?void 0:Se.routeId)||F.id.slice(7),Ie=Kt(e,Te);T((Ie==null?void 0:Ie.tabKey)??null),ht();return}if(T((F==null?void 0:F.id)??null),ht(),!F)return;const se=Y.get(F.id);(se==null?void 0:se.streamSource)==="agent-stream"&&se.agentType&&b(se.routeId,fc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})}),R.api.onDidLayoutChange(()=>{ht(),je(),K(F=>F+1)}),R.api.onWillDragPanel(()=>{S(!0),G(!1),Xe()}),R.api.onWillDragGroup(()=>{S(!0),G(!1),Xe()}),R.api.onWillShowOverlay(()=>{pt(),G(!0)}),R.api.onDidMovePanel(vt),R.api.onDidDrop(vt),R.api.onDidAddGroup(F=>{requestAnimationFrame(()=>{var se,Se;try{const Te=(se=F.element)==null?void 0:se.ownerDocument;if(!Te||Te===document)return;(Se=Te.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Ie=document.documentElement.getAttribute("data-theme");Ie&&Te.documentElement.setAttribute("data-theme",Ie),Te.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&Te.documentElement.setAttribute("style",We)}catch{}je(),K(Te=>Te+1)})}),T(((H=R.api.activePanel)==null?void 0:H.id)??null)},[Ve,it,vt,pt,Y,r,p,U,Xe,T,ht,d,g,b,je,e]);o.useLayoutEffect(()=>{const R=I.current;if(!R||!w.current||x.current&&To({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;x.current&&(x.current=!1);const W=L.current,H=new Set(W),F=e.map(Ke=>Ke.tabKey),se=new Set(F);let Se=!1;for(const Ke of W)se.has(Ke)||(ce.current[Ke]=Ue(Ke),Se=!0);Se&&ye(),Ro(R,e),Po(R,e,g);const Te=F.filter(Ke=>!H.has(Ke));let Ie=!1;for(const Ke of Te){const Ae=R.getPanel(Ke),Z=ce.current[Ke];if(!Ae||!Z||Z.kind==="grid")continue;if(Ae.group.model.location.type===Z.kind){delete ce.current[Ke],Ie=!0;continue}if(Z.kind==="floating"){R.addFloatingGroup(Ae,{x:Z.position.left??24,y:Z.position.top??24,width:Z.position.width,height:Z.position.height}),delete ce.current[Ke],Ie=!0;continue}}if(Ie&&ye(),L.current=F,d&&it(d))return;!R.activePanel&&R.panels[0]&&Ve(R.panels[0]),!!(R.activePanel&&R.getPanel(R.activePanel.id))||ft()},[Ve,it,ft,r,p,ye,Ue,d,g,e]),o.useEffect(()=>{w.current&&it(d)},[it,d]),o.useEffect(()=>{if(!_||typeof window>"u")return;const R=()=>vt();return window.addEventListener("pointerup",R),window.addEventListener("mouseup",R),window.addEventListener("dragend",R),()=>{window.removeEventListener("pointerup",R),window.removeEventListener("mouseup",R),window.removeEventListener("dragend",R)}},[vt,_]),o.useEffect(()=>()=>{typeof window>"u"||V.current!=null&&window.clearTimeout(V.current)},[]),o.useEffect(()=>{const R=H=>{const F=H.target;if(!F)return;const se=F.querySelector("[data-tab-key]")||F.closest("[data-tab-key]");if(se){const Se=se.getAttribute("data-tab-key");if(Se&&H.dataTransfer){const Te=F.closest(".dv-tab")||se.closest(".dv-tab")||se;H.dataTransfer.effectAllowed="move",H.dataTransfer.setData("text/tab-key",Se),Te instanceof HTMLElement&&H.dataTransfer.setDragImage(Te,Math.max(12,Math.round(Te.clientWidth/2)),Math.max(10,Math.round(Te.clientHeight/2)))}}};window.addEventListener("dragstart",R);const W=_o(I.current);for(const H of W)H.addEventListener("dragstart",R);return()=>{window.removeEventListener("dragstart",R);for(const H of W)H.removeEventListener("dragstart",R)}},[A]),o.useEffect(()=>{var W;const R=(W=j.current)==null?void 0:W.querySelector(".adhdev-dockview");R instanceof HTMLElement&&Ar(R,P),Ne(),je(),le()},[je,le,Ne,P]),o.useEffect(()=>{je(),le()},[je,le]),o.useEffect(()=>{const R=W=>{if(W.defaultPrevented||He)return;const H=Ye(W);if(!H)return;const F=W.metaKey||W.ctrlKey||W.altKey;Jn(W.target)&&!F||Yr(J).setActiveTabShortcut!==H||(W.preventDefault(),W.stopPropagation(),Ge())};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[Ye,J,He,Ge]),o.useEffect(()=>{const R=j.current;if(!R)return;const W=H=>{var Ie,We;if(!H.isTrusted)return;const F=(We=(Ie=H.target)==null?void 0:Ie.closest)==null?void 0:We.call(Ie,".dv-scrollable");if(!F)return;H.preventDefault(),H.stopPropagation();const se=Math.abs(H.deltaX),Se=Math.abs(H.deltaY),Te=se>Se?H.deltaX:H.deltaY;F.dispatchEvent(new WheelEvent("wheel",{deltaY:Te,deltaMode:H.deltaMode,bubbles:!1,cancelable:!0}))};return R.addEventListener("wheel",W,{passive:!1,capture:!0}),()=>R.removeEventListener("wheel",W,{capture:!0})},[]),o.useEffect(()=>{const R=_o(I.current);if(R.length===0)return;const W=R.map(H=>{let F=[],se=null;const Se=()=>{se!=null&&H.clearTimeout(se),se=null,F=[]},Te=()=>{se!=null&&H.clearTimeout(se),se=H.setTimeout(()=>{se=null,F=[]},1200)},Ie=Ke=>{if(!Ke.ctrlKey&&!Ke.metaKey&&!Ke.altKey)return;const Ae=Ye(Ke);if(!Ae)return;const Z=wc();for(const[Re,Oe]of Object.entries(Z))if(e.some(De=>De.tabKey===Re)&&Oe===Ae){Ke.preventDefault(),xe(Re);return}},We=Ke=>{if(Ke.defaultPrevented||He)return;const Ae=Ye(Ke);if(!Ae)return;const Z=Ke.metaKey||Ke.ctrlKey||Ke.altKey;if(Jn(Ke.target)&&!Z)return;const Re=Yr(J),Oe=Object.entries(Re).filter(([he,Qe])=>!!Qe&&(he==="splitActiveTabRight"||he==="splitActiveTabDown"||he==="floatActiveTab"||he==="popoutActiveTab"||he==="dockActiveTab"||he==="focusLeftPane"||he==="focusRightPane"||he==="focusUpPane"||he==="focusDownPane"||he==="moveActiveTabToLeftPane"||he==="moveActiveTabToRightPane"||he==="moveActiveTabToUpPane"||he==="moveActiveTabToDownPane"||he==="selectPreviousGroupTab"||he==="selectNextGroupTab"||he==="setActiveTabShortcut"||he==="hideCurrentTab")),De=Z?[Ae]:[...F.slice(-1),Ae].slice(-2),xt=De.join(" "),D=De[De.length-1],X=Oe.find(([,he])=>he===xt);if(X){Ke.preventDefault(),Se(),ot(X[0]);return}if(Oe.some(([,he])=>he.startsWith(`${xt} `))){Ke.preventDefault(),F=De,Te();return}const Pe=Oe.find(([,he])=>he===D);if(Pe){Ke.preventDefault(),Se(),ot(Pe[0]);return}if(Oe.some(([,he])=>he.startsWith(`${D} `))){Ke.preventDefault(),F=[D],Te();return}Se()};return H.addEventListener("keydown",Ie),H.addEventListener("keydown",We),()=>{Se(),H.removeEventListener("keydown",Ie),H.removeEventListener("keydown",We)}});return()=>{for(const H of W)H()}},[Ye,J,A,xe,He,ot,e]);const Bt=P==="light"?Bn:Wn,Ct=((Ee=(q=(It=I.current)==null?void 0:It.activePanel)==null?void 0:q.group.element)==null?void 0:Ee.ownerDocument)??document;return t.jsxs(Ic.Provider,{value:et,children:[t.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(ll,{className:`h-full min-h-0 min-w-0 adhdev-dockview${_?" is-dragging-dockview":""}${O?" is-showing-dockview-overlay":""}`,components:{conversation:_f,remote:Rf},defaultTabComponent:Df,watermarkComponent:Pf,onReady:Ot,singleTabMode:"default",tabAnimation:"smooth",theme:Bt,popoutUrl:"/popout.html"})}),M&&rr.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:M.x,top:M.y},children:mt.map(R=>{if(R.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},R.id);let W=t.jsx(Xl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{};switch(R.id){case"dockInWindow":case"dockBackToGrid":W=t.jsx(Jl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ie(M.tabKey),B(null)};break;case"moveBackToMain":W=t.jsx(Yl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ae(M.tabKey),B(null)};break;case"floatAsPanel":W=t.jsx(Ql,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ee(M.tabKey),B(null)};break;case"openInNewWindow":W=t.jsx(ql,{size:13,className:"shrink-0 opacity-70"}),H=()=>{pe(M.tabKey),B(null)};break;case"setShortcut":H=F=>{F.stopPropagation(),$e(M.tabKey),B(null)};break;case"removeShortcut":W=t.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),H=()=>{const F={...Me};delete F[M.tabKey],Ze(F),B(null)};break;case"hideTab":W=t.jsx(ri,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ve(M.tabKey),B(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 ${R.tone==="muted"?"text-text-muted":""}`,onClick:H,children:[W,t.jsx("span",{className:"flex-1 min-w-0",children:R.label}),R.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:R.shortcut}):null]},R.id)})}),M.sourceDocument.body),He&&rr.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:()=>$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:R=>R.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"})]})}),Ct.body)]})}const Ac="adhdev-recent-launch-args-v1",Ef=8;function Kf(e){return String(e||"").trim().replace(/\s+/g," ")}function Mc(e,s){return`${e.trim()}::${s.trim()}`}function Tc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ac)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Bf(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ac,JSON.stringify(e))}catch{}}function Lc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Tc().byKey[Mc(r,n)])==null?void 0:i.items)||[]}function _c(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=Kf(r);if(!n||!a||!i)return;const c=Tc(),l=Mc(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Ef);c.byKey[l]={items:p},Bf(c)}function Wf(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 La(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 Rc(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=La((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 Pc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ms(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 Tn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Of(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Do(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function $o(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 Hf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Uf(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 Ff(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 zf({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,y]=o.useState(null),[k,T]=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]),g=o.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const K=Of(A.daemonId||A.id);return!!(d!=null&&d.id)&&K===d.id}),[d==null?void 0:d.id,r]),v=oc(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=v.diagnostics,C=v.loading,P=v.applyDiagnostics,b=o.useMemo(()=>{const A=new Map;for(const K of g){const V=s.find(U=>U.sessionId===K.sessionId||U.routeId===K.id);K.sessionId&&V&&A.set(K.sessionId,V)}return A},[g,s]),I=o.useCallback(async()=>{if(d!=null&&d.id){T(!0);try{const A=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),K=Tn(A);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Could not load hosted runtime diagnostics");P(K.diagnostics||K.result||null),m("")}catch(A){const K=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";m(K)}finally{T(!1)}}},[d==null?void 0:d.id,P,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||C||k||I()},[d==null?void 0:d.id,h,C,I,k]);const j=o.useCallback(async(A,K)=>{if(!(d!=null&&d.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${K.displayName}?
|
|
55
|
-
This will terminate the hosted runtime.`))return;const V=`${A}:${K.sessionId}`;
|
|
56
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){y("session_host_prune_duplicate_sessions");try{const K=await a(d.id,"session_host_prune_duplicate_sessions",{}),V=Tn(K);if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Duplicate prune failed");const U=V.result||{},ce=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,Y=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;lt.showToast(`Pruned ${ce} duplicate runtime(s) across ${Y} group(s)`,"success"),await I()}catch(K){const V=K instanceof Error?K.message:"Duplicate prune failed";m(V),lt.showToast(V,"warning")}finally{y(K=>K==="session_host_prune_duplicate_sessions"?null:K)}}},[d==null?void 0:d.id,I,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((A,K)=>(K.lastActivityAt||0)-(A.lastActivityAt||0)),[h==null?void 0:h.sessions]),$=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)||[]}:Rc(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),N=$.liveRuntimes,L=$.recoverySnapshots,M=$.inactiveRecords,B=o.useMemo(()=>Ff(N),[N]),_=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[h==null?void 0:h.recentLogs]),S=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),O=(A,K)=>{var le,pe;const V=b.get(A.sessionId),U=g.find(ae=>ae.sessionId===A.sessionId),ce=f===`session_host_resume_session:${A.sessionId}`,Y=f===`session_host_restart_session:${A.sessionId}`,oe=f===`session_host_stop_session:${A.sessionId}`,Q=La(A.meta),te=typeof((le=A.meta)==null?void 0:le.runtimeRecoveryError)=="string"?String(A.meta.runtimeRecoveryError):"",ue=K==="recovery"?"Recover":"Resume",Ne=Pc(K);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||(U==null?void 0:U.runtimeDisplayName)||(U==null?void 0:U.cliName)||A.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Uf(A.lifecycle)}`,children:A.lifecycle}),Q&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Q})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(U==null?void 0:U.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:((pe=A.writeOwner)==null?void 0:pe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Hf(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(na,{size:11})," ",A.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",$o(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:"",` · Next: ${Ne}`]}),te&&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:te})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[V&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(V),c()},children:"Open chat"}),K==="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:()=>{j("session_host_resume_session",A)},children:ce?`${ue}ing…`:ue}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",A)},children:Y?"Restarting…":"Restart"}),K==="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:()=>{j("session_host_stop_session",A)},children:oe?"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(zt,{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:()=>{I()},disabled:C||k,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Ws,{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(Nt,{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(xs,{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:L.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:$o(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Do(h.hostStartedAt)})]})]}),_&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(xs,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:_.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Jr,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{w()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[g.length," dashboard session",g.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:Ms("live")}),N.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:N.map(A=>O(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:Ms("recovery")}),L.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:L.map(A=>O(A,"recovery"))})]}),M.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:Ms("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:M.map(A=>O(A,"inactive"))})]}),S.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:S.map(A=>{const K=x.find(V=>V.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:(K==null?void 0:K.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:Do(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Dc(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Qs({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 $c({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?bc(n):null;return t.jsxs(Qs,{title:"Saved history",description:ga(),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:Zu()})]}),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 Ln(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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Ct,It;const f=ur(),y=o.useMemo(()=>[...e].sort(da),[e]),[k,T]=o.useState(((Ct=y[0])==null?void 0:Ct.id)||""),d=o.useMemo(()=>y.find(q=>q.id===k)||y[0],[k,y]),g=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[d]),v=(d==null?void 0:d.defaultWorkspaceId)||null,[h,C]=o.useState(""),[P,b]=o.useState(""),[I,j]=o.useState(Ln(y[0])),[w,x]=o.useState(""),[$,N]=o.useState(""),[L,M]=o.useState([]),[B,_]=o.useState(""),[S,O]=o.useState([]),[G,A]=o.useState(!1),[K,V]=o.useState(!1),[U,ce]=o.useState(""),[Y,oe]=o.useState(!1),[Q,te]=o.useState(()=>yt()),[ue,Ne]=o.useState(!1),[le,pe]=o.useState(null),[ae,z]=o.useState(!1),[ve,ee]=o.useState(""),[we,re]=o.useState(!1),[ie,ne]=o.useState(""),[je,xe]=o.useState([]),[E,ke]=o.useState(!1),[ge,Ce]=o.useState(""),[J,Me]=o.useState(!1),He=o.useRef(null),$e=o.useRef(0);o.useEffect(()=>{var q;!k&&((q=y[0])!=null&&q.id)&&T(y[0].id)},[k,y]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ze=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[d]),Ye=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]),ot=o.useMemo(()=>I==="cli"?Ze.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):I==="acp"?Ge.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):Ye,[Ge,I,Ze,Ye]);o.useEffect(()=>{var Ee;if(!d)return;if(He.current!==d.id){He.current=d.id,C(v||((Ee=g[0])==null?void 0:Ee.id)||"__home__"),b(""),j(Ln(d)),x(""),N(""),_(""),O([]),V(!1),ce(""),te(yt()),ee("");return}C(R=>{var W;return R==="__custom__"||R==="__home__"||g.some(H=>H.id===R)?R:v||((W=g[0])==null?void 0:W.id)||"__home__"}),j(R=>R==="ide"&&Ye.length>0||R==="cli"&&Ze.length>0||R==="acp"&&Ge.length>0?R:Ln(d))},[Ge.length,Ze.length,v,Ye.length,d,g]),o.useEffect(()=>{var q;I&&(ot.some(Ee=>Ee.id===w)||x(((q=ot[0])==null?void 0:q.id)||""))},[I,ot,w]);const et=o.useCallback(async(q,Ee)=>{const R=$e.current+1;return $e.current=R,A(!0),ce(""),u(q,Ee).then(W=>{$e.current===R&&O(W)}).catch(W=>{$e.current===R&&(O([]),ce(W instanceof Error?W.message:"Could not load saved sessions"))}).finally(()=>{$e.current===R&&(A(!1),V(!0))})},[u]),mt=o.useCallback((q,Ee)=>{M(Lc(q,Ee))},[]);o.useEffect(()=>{if(_(""),te(yt()),!d||!w||I==="ide"?M([]):mt(d.id,w),V(!1),I!=="cli"){O([]),ce(""),A(!1);return}if(!d||!w){O([]),ce(""),A(!1);return}et(d.id,w)},[I,mt,et,d,w]),o.useEffect(()=>{if(!B)return;const q=S.find(Ee=>Ee.providerSessionId===B);q!=null&&q.canResume||_("")},[S,B]);const Ve=h==="__custom__"?P.trim():h==="__home__"?"":((It=g.find(q=>q.id===h))==null?void 0:It.path)||"",it=o.useMemo(()=>d?r.filter(q=>q.id!==d.id&&q.daemonId===d.id).map(q=>q.workspace):[],[r,d]),ft=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(q=>q.workspace),[d]),ht=o.useCallback(q=>{const Ee=String(q.workspace||"").trim();if(!Ee)return;const R=g.find(W=>Mr(W.path)===Mr(Ee));if(R){C(R.id),b("");return}C("__custom__"),b(Ee)},[g]),ye=o.useCallback(q=>{const Ee=String(q.workspace||"").trim();if(!Ee)return{workspaceId:null,workspacePath:null};const R=g.find(W=>Mr(W.path)===Mr(Ee));return R?{workspaceId:R.id,workspacePath:null}:{workspaceId:null,workspacePath:Ee}},[g]),Ue=o.useMemo(()=>S.find(q=>q.providerSessionId===B)||null,[S,B]),ze=o.useMemo(()=>{var Ee;if(I!=="cli"||!d||!w)return null;const q=((Ee=Ze.find(R=>R.type===w))==null?void 0:Ee.displayName)||w;return{routeId:d.id,daemonId:d.id,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:q,agentType:w,status:"idle",title:q,messages:[],ideType:w,workspaceName:Ve,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${w}`,machineName:Mt(d,{fallbackId:d.id})}},[I,Ze,Ve,d,B,w]),Xe=o.useCallback(()=>{var Ee;if(!d)return;C("__custom__"),re(!0),Ce("");const q=an(d.platform,nn(P.trim(),Ve,it,ft,d.defaultWorkspacePath,(Ee=g.find(R=>R.id===v))==null?void 0:Ee.path,g.map(R=>R.path)));ke(!0),a(d.id,q).then(R=>{ne(R.path),b(R.path),xe(R.directories)}).catch(R=>{Ce(R instanceof Error?R.message:"Could not load folder")}).finally(()=>ke(!1))},[P,v,ft,it,a,Ve,d,g]),pt=o.useCallback(q=>{d&&(ke(!0),Ce(""),a(d.id,q).then(Ee=>{ne(Ee.path),b(Ee.path),xe(Ee.directories)}).catch(Ee=>{Ce(Ee instanceof Error?Ee.message:"Could not load folder")}).finally(()=>ke(!1)))},[a,d]),gt=o.useCallback(async()=>{if(!d||!Ve)return;Me(!0),ee("");const q=await i(d.id,Ve);if(Me(!1),!q.ok){ee(q.error||"Could not save workspace");return}ee("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Ve,d]),vt=o.useCallback(async()=>{if(!d||!I||!w)return;z(!0),ee("");const q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],Ee=I==="ide"?await c(d.id,w,{workspacePath:Ve||null}):await l(d.id,I,w,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ve||null,resumeSessionId:I==="cli"&&B?B:null,cliArgs:q});if(z(!1),!Ee.ok){ee(Ee.error||"Could not start session");return}I!=="ide"&&$.trim()&&(_c(d.id,w,$),mt(d.id,w)),n()},[I,$,mt,n,c,l,Ve,d,B,w,h]),Ot=I?Ui(I,I==="cli"&&!!B):"Start",Bt=I?Fi(I,I==="cli"&&!!B):"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(Nt,{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(Qs,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:q=>T(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:ae,children:y.map(q=>t.jsx("option",{value:q.id,children:Mt(q,{fallbackId:q.id})},q.id))})}),I==="cli"&&t.jsx(Qs,{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:ae||!d,onClick:()=>Ne(!0),children:[t.jsx(zt,{size:14}),Qu()]})}),t.jsxs(Qs,{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:Xe,disabled:ae,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:q=>{const Ee=q.target.value;C(Ee),Ee==="__custom__"?Xe():ee("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),g.map(q=>t.jsxs("option",{value:q.id,children:[q.id===v?"⭐ ":"",sn(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.":Ve||"Select a workspace folder."}),h==="__custom__"&&Ve&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:ae,children:[t.jsx(Ls,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:gt,disabled:ae||J,children:J?"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:Ze.length>0},{id:"ide",label:"IDE",enabled:Ye.length>0},{id:"acp",label:"ACP",enabled:Ge.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(q.id),disabled:!q.enabled||ae,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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(q.id),disabled:ae,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)),ot.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."})]})]}),I!=="ide"&&t.jsxs(Qs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:q=>N(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:ae}),L.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:L.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>N(q),disabled:ae,title:q,children:q},q))})]}),I==="cli"&&t.jsx($c,{busy:ae,savedSessionsLoading:G,savedSessionsError:U,selectedSession:Ue,onRefresh:()=>{!d||!w||et(d.id,w)},onOpenHistory:()=>{!d||!w||(oe(!0),Dc({hasLoadedInitialResults:K,isLoading:G})&&et(d.id,w))},onClearSelection:()=>_("")}),ve&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ve.includes("saved")||ve.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ve})]}),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:ae,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:vt,disabled:ae||!I||!w||h==="__custom__"&&!Ve,children:[t.jsx(oa,{size:14}),ae?Bt:Ot]})]})]})}),we&&t.jsx(cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ie,directories:je,busy:E,error:ge,onClose:()=>re(!1),onNavigate:pt,onConfirm:q=>{b(q),ne(q),C("__custom__"),re(!1)}}),Y&&ze&&t.jsx(wa,{activeConv:ze,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:S,isSavedSessionsLoading:G,isResumingSavedSessionId:le,savedHistoryFilters:Q,onSavedHistoryFiltersChange:te,onClose:()=>oe(!1),onNewChat:()=>{_(""),oe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!w||et(d.id,w)},onResumeSavedSession:q=>{if(!d||!w||le||!q.canResume)return;const Ee=ye(q);_(q.providerSessionId),ht(q),pe(q.providerSessionId),oe(!1),z(!0),ee(""),l(d.id,"cli",w,{workspaceId:Ee.workspaceId,workspacePath:Ee.workspacePath,resumeSessionId:q.providerSessionId}).then(R=>{if(!R.ok){ee(R.error||"Could not resume session");return}n()}).finally(()=>{z(!1),pe(R=>R===q.providerSessionId?null:R)})}}),ue&&d&&t.jsx(zf,{machineCards:[{id:d.id,label:Mt(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",yc(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:q=>{Ne(!1),n(),m(q)},onClose:()=>Ne(!1)})]}):null}function Gf(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 qf(e){return e instanceof Error?e.message:String(e||"")}function Yf(e){const s=qf(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Xf({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:y,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:v,isStandalone:h,initialDataLoaded:C,userName:P,requestedMobileTabKey:b,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:w,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,containerRef:N,isSplitMode:L,numGroups:M,groupSizes:B,groupedConvs:_,clearedTabs:S,focusedGroup:O,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:K,closeGroup:V,handleResizeStart:U,groupActiveTabIds:ce,setGroupActiveTabIds:Y,groupTabOrders:oe,setGroupTabOrders:Q,toggleHiddenTab:te,visibleConversations:ue,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:pe,onHideConversation:ae,onShowHiddenConversation:z,onShowAllHiddenConversations:ve,scrollToBottomRequest:ee,machineEntries:we,onBrowseMachineDirectory:re,onSaveMachineWorkspace:ie,onLaunchMachineIde:ne,onLaunchMachineProvider:je,onListMachineSavedSessions:xe,notifications:E,notificationUnreadCount:ke,notificationStateBySessionId:ge,onMarkNotificationRead:Ce,onMarkNotificationUnread:J,onDeleteNotification:Me,onMarkNotificationTargetRead:He}){const $e=nt.useRef(null),[Ze,Ge]=nt.useState(!1),[Ye,ot]=nt.useState(!1),[et,mt]=nt.useState(!1),[Ve,it]=nt.useState(!1),ft=nt.useCallback(Z=>{var Re;rr.flushSync(()=>{z(Z)}),(Re=$e.current)==null||Re.restoreHiddenTabToSavedLocation(Z.tabKey)},[z]),ht=nt.useCallback(Z=>{var Oe;const Re=f.find(De=>Or(De,Z))||y.find(De=>Or(De,Z));Re&&(y.some(De=>De.tabKey===Re.tabKey)&&ft(Re),pe(Re.tabKey),(Oe=$e.current)==null||Oe.activateConversationTab(Re.tabKey)),Ce(Z.id),(Z.sessionId||Z.providerSessionId||Z.tabKey||Z.routeId)&&He({sessionId:Z.sessionId,providerSessionId:Z.providerSessionId,tabKey:Z.tabKey,routeId:Z.routeId}),Ge(!1)},[ft,y,f,pe,Ce,He]),[ye,Ue]=nt.useState(!1),[ze,Xe]=nt.useState("quickstart"),[pt,gt]=nt.useState("workspace"),vt=!e&&!s,Ot=nt.useCallback(Z=>{Ge(Z),Z&&ot(!1)},[]),Bt=nt.useCallback(Z=>{ot(Z),Z&&Ge(!1)},[]),Ct=nt.useCallback(()=>{var Re;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Re=$e.current)==null||Re.resetAllPanelsToMain(),ot(!1))},[]),It=nt.useCallback(()=>{Xe(ue.length===0?"quickstart":"shortcuts"),gt("workspace"),mt(!0),Ge(!1),ot(!1)},[ue.length]),q=nt.useCallback(async Z=>{var D;if(!r)return;const Re=(D=r.modalButtons)==null?void 0:D[Z];if(!Re)return;const Oe=ir(r);if(!Oe)return;const De=Re.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),xt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(De);try{await d(Oe,"resolve_action",{button:Re,action:xt?"approve":"reject",buttonIndex:Z,...As(r)})}catch(X){Yf(X)||console.error("[Shortcut approval] Failed:",X)}},[r,d]),{isMac:Ee,actionDefinitions:R,actionShortcuts:W,shortcutListening:H,shortcutListeningDraft:F,setShortcutListening:se,setShortcutListeningDraft:Se,saveShortcuts:Te}=Cf({enabled:vt&&!et,onTrigger:Z=>{var Re,Oe,De,xt,D,X,de,Pe,fe,he,Qe,St,ct,qt,ts,pr;if(Z==="openShortcutHelp"){It();return}if(Z==="hideCurrentTab"){r&&ae(r);return}if(Z==="toggleHiddenTabs"){Bt(!Ye);return}if(Z==="openHistoryForActiveTab"){r&&!Je(r)&&c(r);return}if(Z==="openRemoteForActiveTab"){r&&!tt(r)&&!Je(r)&&l(r);return}if(Z==="splitActiveTabRight"){(Re=$e.current)==null||Re.splitActiveTabRight();return}if(Z==="splitActiveTabDown"){(Oe=$e.current)==null||Oe.splitActiveTabDown();return}if(Z==="floatActiveTab"){(De=$e.current)==null||De.floatActiveTab();return}if(Z==="popoutActiveTab"){(xt=$e.current)==null||xt.popoutActiveTab();return}if(Z==="dockActiveTab"){(D=$e.current)==null||D.dockActiveTab();return}if(Z==="focusLeftPane"){(X=$e.current)==null||X.focusLeftPane();return}if(Z==="focusRightPane"){(de=$e.current)==null||de.focusRightPane();return}if(Z==="focusUpPane"){(Pe=$e.current)==null||Pe.focusUpPane();return}if(Z==="focusDownPane"){(fe=$e.current)==null||fe.focusDownPane();return}if(Z==="moveActiveTabToLeftPane"){(he=$e.current)==null||he.moveActiveTabToLeftPane();return}if(Z==="moveActiveTabToRightPane"){(Qe=$e.current)==null||Qe.moveActiveTabToRightPane();return}if(Z==="moveActiveTabToUpPane"){(St=$e.current)==null||St.moveActiveTabToUpPane();return}if(Z==="moveActiveTabToDownPane"){(ct=$e.current)==null||ct.moveActiveTabToDownPane();return}if(Z==="triggerPrimaryApprovalAction"){q(0);return}if(Z==="triggerSecondaryApprovalAction"){q(1);return}if(Z==="triggerTertiaryApprovalAction"){q(2);return}if(Z==="setActiveTabShortcut"){(qt=$e.current)==null||qt.setShortcutForActiveTab();return}if(Z==="selectPreviousGroupTab"){(ts=$e.current)==null||ts.activatePreviousTabInGroup();return}if(Z==="selectNextGroupTab"){(pr=$e.current)==null||pr.activateNextTabInGroup();return}!r||!tt(r)||Je(r)||Z==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),Ie=nt.useCallback(()=>{mt(!1),se(null),Se([])},[se,Se]),We=nt.useMemo(()=>pt==="all"?R:R.filter(Z=>Gf(Z)===pt),[R,pt]),Ke=nt.useCallback(()=>{const Z=Object.fromEntries(R.map(Re=>[Re.id,""]));Te(Z)},[R,Te]),Ae=nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Z=Object.fromEntries(R.map(Re=>[Re.id,Re.defaultShortcut]));Te(Z)},[R,Te]);return nt.useEffect(()=>{const Z=Re=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Re.metaKey&&Re.key.toLowerCase()==="w":Re.ctrlKey&&Re.key.toLowerCase()==="w")&&(Re.preventDefault(),r&&ae&&ae(r))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[r,ae]),nt.useEffect(()=>{if(!et||H)return;const Z=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Ie())};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[Ie,et,H]),nt.useEffect(()=>{if(!vt){Ue(!1);return}Ue(!0);const Z=window.setTimeout(()=>{Ue(!1)},1e4);return()=>window.clearTimeout(Z)},[vt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Vu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:ue,hiddenConversations:y,onOpenHistory:c,onHideConversation:ae,onShowConversation:ft,onShowAllHidden:ve,onResetPanelsToMain:Ct,notifications:E,notificationUnreadCount:ke,onOpenNotification:ht,onMarkNotificationRead:Ce,onMarkNotificationUnread:J,onDeleteNotification:Me,inboxOpen:Ze,onInboxOpenChange:Ot,hiddenOpen:Ye,onHiddenOpenChange:Bt,onOpenNewSession:s?void 0:()=>it(!0),actionShortcuts:W,onOpenRemote:()=>{!r||tt(r)||Je(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(ff,{conversations:f,hiddenConversations:y,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:v,isStandalone:h,userName:P,requestedActiveTabKey:b,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:w,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ft,onShowAllHiddenConversations:ve,onOpenNewSession:()=>it(!0),notificationStateBySessionId:ge,onMarkNotificationTargetRead:He}):s?t.jsx(jf,{containerRef:N,isSplitMode:L,numGroups:M,groupSizes:B,groupedConvs:_,clearedTabs:S,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:v,isStandalone:h,hasRegisteredMachines:we.length>0,userName:P,focusedGroup:O,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:K,closeGroup:V,handleResizeStart:U,groupActiveTabIds:ce,setGroupActiveTabIds:Y,groupTabOrders:oe,setGroupTabOrders:Q,toggleHiddenTab:te,allowTabShortcuts:!1}):t.jsx($f,{visibleConversations:ue,clearedTabs:S,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:g,setActionLogs:v,isStandalone:h,hasRegisteredMachines:we.length>0,initialDataLoaded:C,userName:P,toggleHiddenTab:te,actionShortcuts:W,registerActionHandlers:Z=>{$e.current=Z},notificationStateBySessionId:ge,onActiveTabChange:pe,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:le,scrollToBottomRequest:ee}),Ve&&t.jsx(Vf,{machines:we,conversations:f,ides:k,onClose:()=>it(!1),onBrowseDirectory:re,onSaveWorkspace:ie,onLaunchIde:ne,onLaunchProvider:je,onListSavedSessions:xe,sendDaemonCommand:d,onOpenConversation:Z=>{it(!1),z(Z),pe(Z.tabKey)}}),et&&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:Ie,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:Z=>Z.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:Ie,"aria-label":"Close dashboard guide",children:t.jsx(Nt,{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(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${ze===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>Xe(Z.id),children:Z.label},Z.id))}),ze==="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 ",Ee?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ze==="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."]})]})]})]}),ze==="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(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${pt===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>gt(Z.id),children:Z.label},Z.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ke,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:Ae,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:We.map(Z=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${H===Z.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:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Z.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:H===Z.id?F.length>0?`${F.join(" ")} ...`:"Listening...":W[Z.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{se(Z.id),Se([])},children:H===Z.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Re={...W};Re[Z.id]="",Te(Re)},children:"Disable"})]})]})},Z.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ee?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:It,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${ye?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),ye&&t.jsx("span",{children:"Guide"})]})]})}const _n=[{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 Qf({onClose:e}){const[s,r]=o.useState(0),n=_n[s],a=s===_n.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(Nt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:_n.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:`
|
|
54
|
+
`,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const Z=Ae.querySelector("[data-adhdev-popout-focus]");Z&&(Z.onclick=()=>{window.focus()});const Re=Ae.querySelector("[data-adhdev-popout-dock]");Re&&(Re.disabled=!Te,Re.style.opacity=Te?"1":"0.5",Re.style.cursor=Te?"pointer":"default",Re.onclick=()=>{var Oe;Te&&ae(Te),(Oe=se.defaultView)==null||Oe.focus()})}},[Y,ae]),xe=o.useCallback(R=>{var F;const W=I.current,H=W==null?void 0:W.getPanel(R);if(!(!W||!H)){H.group.model.openPanel(H),H.api.setActive();try{const se=H.group.model.location;se.type==="popout"?se.getWindow().focus():Mn((F=H.group.element)==null?void 0:F.ownerDocument)}catch{}}},[]),E=o.useCallback(R=>{const W=I.current,H=W==null?void 0:W.activePanel,F=(W==null?void 0:W.activeGroup)||(H==null?void 0:H.group);if(!W||!H||!F)return;const se=F.panels||[];if(se.length<=1)return;const Se=se.findIndex(We=>We.id===H.id);if(Se<0)return;const Te=(Se+R+se.length)%se.length,Ie=se[Te];Ie&&(Ie.group.model.openPanel(Ie),Ie.api.setActive())},[]),ke=o.useCallback(R=>{var Re;const W=I.current,H=(W==null?void 0:W.activeGroup)||((Re=W==null?void 0:W.activePanel)==null?void 0:Re.group);if(!W||!H)return;const F=W.groups||[],se=F.find(Oe=>Oe.id===H.id);if(!se)return;const Se=se.element.getBoundingClientRect(),Te=Se.left+Se.width/2,Ie=Se.top+Se.height/2,We=(Oe,De,xt,D)=>Math.max(0,Math.min(De,D)-Math.max(Oe,xt)),Ke=Oe=>{const De=Oe.element.getBoundingClientRect(),xt=De.left+De.width/2,D=De.top+De.height/2;let X=0,de=0,Pe=0,fe=!1;if(R==="left"?(fe=xt<Te,X=Math.max(0,Se.left-De.right),de=Math.abs(D-Ie),Pe=We(Se.top,Se.bottom,De.top,De.bottom)):R==="right"?(fe=xt>Te,X=Math.max(0,De.left-Se.right),de=Math.abs(D-Ie),Pe=We(Se.top,Se.bottom,De.top,De.bottom)):R==="above"?(fe=D<Ie,X=Math.max(0,Se.top-De.bottom),de=Math.abs(xt-Te),Pe=We(Se.left,Se.right,De.left,De.right)):(fe=D>Ie,X=Math.max(0,De.top-Se.bottom),de=Math.abs(xt-Te),Pe=We(Se.left,Se.right,De.left,De.right)),!fe)return Number.POSITIVE_INFINITY;const he=Pe>0?0:120;return X*3+de+he};let Ae=null,Z=Number.POSITIVE_INFINITY;for(const Oe of F){if(Oe.id===se.id)continue;const De=Ke(Oe);Number.isFinite(De)&&(De>=Z||(Z=De,Ae=Oe))}return Ae||void 0},[]),ge=o.useCallback(R=>{var F;const W=ke(R);if(!W)return;const H=W.activePanel||W.panels[0];H&&(W.model.openPanel(H),H.api.setActive(),Mn((F=W.element)==null?void 0:F.ownerDocument))},[ke]),Ce=o.useCallback((R,W)=>{const H=I.current,F=H==null?void 0:H.activePanel,se=(H==null?void 0:H.activeGroup)||(F==null?void 0:F.group);if(!H||!F||!se)return;let Se=ke(R);!Se&&(W!=null&&W.createGroupIfMissing)&&(Se=H.addGroup({referenceGroup:se,direction:R})),Se&&(F.api.moveTo({group:Se,position:"center"}),F.group.model.openPanel(F),F.api.setActive())},[ke]),{isMac:J,tabShortcuts:Me,shortcutListening:He,setShortcutListening:$e,saveShortcuts:Ze}=jc({sortedTabKeys:e.map(R=>R.tabKey),onFocus:te,onSelectTab:xe}),Ge=o.useCallback(()=>{var H;const R=I.current;if(!R)return;const W=R.activePanel;if(W){if(Yt(W.id)){const F=((H=W.params)==null?void 0:H.routeId)||W.id.slice(7),se=Kt(e,F);se!=null&&se.tabKey&&$e(se.tabKey);return}Y.has(W.id)&&$e(W.id)}},[Y,xe,$e,e]),Ye=o.useCallback(R=>{const W=[];return R.metaKey&&W.push(J?"⌘":"Meta"),R.ctrlKey&&W.push("Ctrl"),R.altKey&&W.push(J?"⌥":"Alt"),R.shiftKey&&R.key.length!==1&&W.push(J?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(R.key)?null:(W.push(Cc(R.key)),W.join("+"))},[J]),ot=o.useCallback(R=>{var W,H;switch(R){case"splitActiveTabRight":Ce("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Ce("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const F=re();F&&ee(F);return}case"popoutActiveTab":{const F=re();F&&pe(F);return}case"dockActiveTab":{const F=re();if(!F)return;z(F)?ae(F):we(F)&&ie(F);return}case"focusLeftPane":ge("left");return;case"focusRightPane":ge("right");return;case"focusUpPane":ge("above");return;case"focusDownPane":ge("below");return;case"moveActiveTabToLeftPane":Ce("left");return;case"moveActiveTabToRightPane":Ce("right");return;case"moveActiveTabToUpPane":Ce("above");return;case"moveActiveTabToDownPane":Ce("below");return;case"selectPreviousGroupTab":E(-1);return;case"selectNextGroupTab":E(1);return;case"setActiveTabShortcut":Ge();return;case"hideCurrentTab":{const F=(H=(W=I.current)==null?void 0:W.activePanel)==null?void 0:H.id;F&&!Yt(F)&&ve(F);return}default:return}},[E,ie,ge,ee,re,ve,we,z,ae,Ce,pe,Ge]);o.useEffect(()=>{if(!M)return;const R=M.sourceDocument,W=R.defaultView??window,H=F=>{const se=R.querySelector("[data-dockview-tab-context-menu]");se&&se.contains(F.target)||B(null)};return W.addEventListener("mousedown",H,!0),W!==window&&window.addEventListener("mousedown",()=>B(null),!0),()=>{W.removeEventListener("mousedown",H,!0),W!==window&&window.removeEventListener("mousedown",()=>B(null),!0)}},[M]);const et=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:Y,hasDetachedConversationPanels:Q,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:oe,notificationStateBySessionId:C,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ve,userName:m,scrollToBottomRequest:h,tabShortcuts:Me,openTabContextMenu:({x:R,y:W,tabKey:H,sourceDocument:F})=>B({x:R,y:W,tabKey:H,sourceDocument:F??document}),popoutTab:pe,moveTabBackToMain:ae,isTabInPopout:z,floatTab:ee,isTabFloating:we}),[n,s,Y,Q,r,l,u,oe,C,a,c,i,ve,m,h,Me,pe,ae,z,ee,we]),mt=M?If({isTabInPopout:z(M.tabKey),isTabFloating:we(M.tabKey),tabShortcut:Me[M.tabKey],actionShortcuts:b}):[],Ve=o.useCallback(R=>{var F;const W=I.current;if((((F=W==null?void 0:W.activePanel)==null?void 0:F.id)??null)===R.id){R.group.model.openPanel(R);return}R.group.model.openPanel(R),R.api.setActive()},[]),it=o.useCallback(R=>{if(!R)return!1;const W=I.current;if(!W)return!1;const H=W.getPanel(R);return H?(Ve(H),v==null||v(),!0):!1},[Ve,v]),ft=o.useCallback(()=>{if($.current)return!1;const R=it(N.current);return R&&($.current=!0),R},[it]),ht=o.useCallback(()=>{var W;const R=I.current;R&&hp(U,{activeTabId:((W=R.activePanel)==null?void 0:W.id)??null,layout:R.toJSON()})},[U]),ye=o.useCallback(()=>{bp(U,ce.current)},[U]),Ue=o.useCallback(R=>{var F,se,Se,Te;const W=I.current;if(!W)return{kind:"grid"};const H=W.toJSON();for(const Ie of H.floatingGroups||[])if((se=(F=Ie.data)==null?void 0:F.views)!=null&&se.includes(R)&&Ie.position)return{kind:"floating",position:Ie.position};for(const Ie of H.popoutGroups||[])if((Te=(Se=Ie.data)==null?void 0:Se.views)!=null&&Te.includes(R))return{kind:"popout",position:Ie.position,popoutUrl:Ie.url};return{kind:"grid"}},[]),ze=o.useCallback(R=>{const W=I.current;if(!W)return;const H=W.getPanel(R),F=ce.current[R];if(!H||!F||F.kind==="grid")return;if(H.group.model.location.type===F.kind){delete ce.current[R],ye();return}if(F.kind==="floating"){W.addFloatingGroup(H,{x:F.position.left??24,y:F.position.top??24,width:F.position.width,height:F.position.height}),delete ce.current[R],ye();return}delete ce.current[R],ye()},[ye]);o.useEffect(()=>(k==null||k({setShortcutForActiveTab:Ge,restoreHiddenTabToSavedLocation:ze,activateConversationTab:xe,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>E(-1),activateNextTabInGroup:()=>E(1),floatActiveTab:()=>{const R=re();R&&ee(R)},popoutActiveTab:()=>{const R=re();R&&pe(R)},dockActiveTab:()=>{const R=re();R&&(z(R)?ae(R):we(R)&&ie(R))},splitActiveTabRight:()=>Ce("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Ce("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ge("left"),focusRightPane:()=>ge("right"),focusUpPane:()=>ge("above"),focusDownPane:()=>ge("below"),moveActiveTabToLeftPane:()=>Ce("left"),moveActiveTabToRightPane:()=>Ce("right"),moveActiveTabToUpPane:()=>Ce("above"),moveActiveTabToDownPane:()=>Ce("below")}),()=>k==null?void 0:k(null)),[E,ie,ee,ge,re,we,z,Ce,ae,pe,k,ne,ze,xe,Ge]);const Xe=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const H of W)H.setAttribute("data-adhdev-force-hidden","true")},[]),pt=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const H of W)H.removeAttribute("data-adhdev-force-hidden")},[]),gt=o.useCallback(()=>{const R=j.current;if(!R)return;const W=R.querySelectorAll(".dv-drop-target-container");for(const se of W)se.remove();const H=R.querySelectorAll(".dv-drop-target-dropzone");for(const se of H)se.remove();const F=R.querySelectorAll(".dv-drop-target");for(const se of F)se.classList.remove("dv-drop-target")},[]),vt=o.useCallback(()=>{S(!1),G(!1),pt(),Xe(),gt(),!(typeof window>"u")&&(V.current!=null&&window.clearTimeout(V.current),window.requestAnimationFrame(()=>{Xe(),gt()}),V.current=window.setTimeout(()=>{Xe(),gt(),V.current=null},80))},[pt,Xe,gt]),Ot=o.useCallback(R=>{var H;I.current=R.api;const W=fp(U);if(N.current=(W==null?void 0:W.activeTabId)??null,W!=null&&W.layout&&R.api.fromJSON(W.layout,{reuseExistingPanels:!1}),x.current=To({hasStoredLayout:!!(W!=null&&W.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),x.current||(Ro(R.api,e),Po(R.api,e,y)),R.api.totalPanels===0&&e.length>0){const F=Lf(R.api,e,d);if(F){const se=R.api.getPanel(F);se&&Ve(se)}}else!x.current&&!it(d)&&ft();w.current=!0,R.api.onDidActivePanelChange(F=>{var Se;if(N.current=(F==null?void 0:F.id)??null,$.current=!0,je(),F&&Yt(F.id)){const Te=((Se=F.params)==null?void 0:Se.routeId)||F.id.slice(7),Ie=Kt(e,Te);L((Ie==null?void 0:Ie.tabKey)??null),ht();return}if(L((F==null?void 0:F.id)??null),ht(),!F)return;const se=Y.get(F.id);(se==null?void 0:se.streamSource)==="agent-stream"&&se.agentType&&g(se.routeId,fc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})}),R.api.onDidLayoutChange(()=>{ht(),je(),K(F=>F+1)}),R.api.onWillDragPanel(()=>{S(!0),G(!1),Xe()}),R.api.onWillDragGroup(()=>{S(!0),G(!1),Xe()}),R.api.onWillShowOverlay(()=>{pt(),G(!0)}),R.api.onDidMovePanel(vt),R.api.onDidDrop(vt),R.api.onDidAddGroup(F=>{requestAnimationFrame(()=>{var se,Se;try{const Te=(se=F.element)==null?void 0:se.ownerDocument;if(!Te||Te===document)return;(Se=Te.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Ie=document.documentElement.getAttribute("data-theme");Ie&&Te.documentElement.setAttribute("data-theme",Ie),Te.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&Te.documentElement.setAttribute("style",We)}catch{}je(),K(Te=>Te+1)})}),L(((H=R.api.activePanel)==null?void 0:H.id)??null)},[Ve,it,vt,pt,Y,r,p,U,Xe,L,ht,d,y,g,je,e]);o.useLayoutEffect(()=>{const R=I.current;if(!R||!w.current||x.current&&To({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;x.current&&(x.current=!1);const W=T.current,H=new Set(W),F=e.map(Ke=>Ke.tabKey),se=new Set(F);let Se=!1;for(const Ke of W)se.has(Ke)||(ce.current[Ke]=Ue(Ke),Se=!0);Se&&ye(),Ro(R,e),Po(R,e,y);const Te=F.filter(Ke=>!H.has(Ke));let Ie=!1;for(const Ke of Te){const Ae=R.getPanel(Ke),Z=ce.current[Ke];if(!Ae||!Z||Z.kind==="grid")continue;if(Ae.group.model.location.type===Z.kind){delete ce.current[Ke],Ie=!0;continue}if(Z.kind==="floating"){R.addFloatingGroup(Ae,{x:Z.position.left??24,y:Z.position.top??24,width:Z.position.width,height:Z.position.height}),delete ce.current[Ke],Ie=!0;continue}}if(Ie&&ye(),T.current=F,d&&it(d))return;!R.activePanel&&R.panels[0]&&Ve(R.panels[0]),!!(R.activePanel&&R.getPanel(R.activePanel.id))||ft()},[Ve,it,ft,r,p,ye,Ue,d,y,e]),o.useEffect(()=>{w.current&&it(d)},[it,d]),o.useEffect(()=>{if(!_||typeof window>"u")return;const R=()=>vt();return window.addEventListener("pointerup",R),window.addEventListener("mouseup",R),window.addEventListener("dragend",R),()=>{window.removeEventListener("pointerup",R),window.removeEventListener("mouseup",R),window.removeEventListener("dragend",R)}},[vt,_]),o.useEffect(()=>()=>{typeof window>"u"||V.current!=null&&window.clearTimeout(V.current)},[]),o.useEffect(()=>{const R=H=>{const F=H.target;if(!F)return;const se=F.querySelector("[data-tab-key]")||F.closest("[data-tab-key]");if(se){const Se=se.getAttribute("data-tab-key");if(Se&&H.dataTransfer){const Te=F.closest(".dv-tab")||se.closest(".dv-tab")||se;H.dataTransfer.effectAllowed="move",H.dataTransfer.setData("text/tab-key",Se),Te instanceof HTMLElement&&H.dataTransfer.setDragImage(Te,Math.max(12,Math.round(Te.clientWidth/2)),Math.max(10,Math.round(Te.clientHeight/2)))}}};window.addEventListener("dragstart",R);const W=_o(I.current);for(const H of W)H.addEventListener("dragstart",R);return()=>{window.removeEventListener("dragstart",R);for(const H of W)H.removeEventListener("dragstart",R)}},[A]),o.useEffect(()=>{var W;const R=(W=j.current)==null?void 0:W.querySelector(".adhdev-dockview");R instanceof HTMLElement&&Ar(R,P),Ne(),je(),le()},[je,le,Ne,P]),o.useEffect(()=>{je(),le()},[je,le]),o.useEffect(()=>{const R=W=>{if(W.defaultPrevented||He)return;const H=Ye(W);if(!H)return;const F=W.metaKey||W.ctrlKey||W.altKey;Jn(W.target)&&!F||Yr(J).setActiveTabShortcut!==H||(W.preventDefault(),W.stopPropagation(),Ge())};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[Ye,J,He,Ge]),o.useEffect(()=>{const R=j.current;if(!R)return;const W=H=>{var Ie,We;if(!H.isTrusted)return;const F=(We=(Ie=H.target)==null?void 0:Ie.closest)==null?void 0:We.call(Ie,".dv-scrollable");if(!F)return;H.preventDefault(),H.stopPropagation();const se=Math.abs(H.deltaX),Se=Math.abs(H.deltaY),Te=se>Se?H.deltaX:H.deltaY;F.dispatchEvent(new WheelEvent("wheel",{deltaY:Te,deltaMode:H.deltaMode,bubbles:!1,cancelable:!0}))};return R.addEventListener("wheel",W,{passive:!1,capture:!0}),()=>R.removeEventListener("wheel",W,{capture:!0})},[]),o.useEffect(()=>{const R=_o(I.current);if(R.length===0)return;const W=R.map(H=>{let F=[],se=null;const Se=()=>{se!=null&&H.clearTimeout(se),se=null,F=[]},Te=()=>{se!=null&&H.clearTimeout(se),se=H.setTimeout(()=>{se=null,F=[]},1200)},Ie=Ke=>{if(!Ke.ctrlKey&&!Ke.metaKey&&!Ke.altKey)return;const Ae=Ye(Ke);if(!Ae)return;const Z=wc();for(const[Re,Oe]of Object.entries(Z))if(e.some(De=>De.tabKey===Re)&&Oe===Ae){Ke.preventDefault(),xe(Re);return}},We=Ke=>{if(Ke.defaultPrevented||He)return;const Ae=Ye(Ke);if(!Ae)return;const Z=Ke.metaKey||Ke.ctrlKey||Ke.altKey;if(Jn(Ke.target)&&!Z)return;const Re=Yr(J),Oe=Object.entries(Re).filter(([he,Qe])=>!!Qe&&(he==="splitActiveTabRight"||he==="splitActiveTabDown"||he==="floatActiveTab"||he==="popoutActiveTab"||he==="dockActiveTab"||he==="focusLeftPane"||he==="focusRightPane"||he==="focusUpPane"||he==="focusDownPane"||he==="moveActiveTabToLeftPane"||he==="moveActiveTabToRightPane"||he==="moveActiveTabToUpPane"||he==="moveActiveTabToDownPane"||he==="selectPreviousGroupTab"||he==="selectNextGroupTab"||he==="setActiveTabShortcut"||he==="hideCurrentTab")),De=Z?[Ae]:[...F.slice(-1),Ae].slice(-2),xt=De.join(" "),D=De[De.length-1],X=Oe.find(([,he])=>he===xt);if(X){Ke.preventDefault(),Se(),ot(X[0]);return}if(Oe.some(([,he])=>he.startsWith(`${xt} `))){Ke.preventDefault(),F=De,Te();return}const Pe=Oe.find(([,he])=>he===D);if(Pe){Ke.preventDefault(),Se(),ot(Pe[0]);return}if(Oe.some(([,he])=>he.startsWith(`${D} `))){Ke.preventDefault(),F=[D],Te();return}Se()};return H.addEventListener("keydown",Ie),H.addEventListener("keydown",We),()=>{Se(),H.removeEventListener("keydown",Ie),H.removeEventListener("keydown",We)}});return()=>{for(const H of W)H()}},[Ye,J,A,xe,He,ot,e]);const Bt=P==="light"?Bn:Wn,Ct=((Ee=(q=(It=I.current)==null?void 0:It.activePanel)==null?void 0:q.group.element)==null?void 0:Ee.ownerDocument)??document;return t.jsxs(Ic.Provider,{value:et,children:[t.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(ll,{className:`h-full min-h-0 min-w-0 adhdev-dockview${_?" is-dragging-dockview":""}${O?" is-showing-dockview-overlay":""}`,components:{conversation:_f,remote:Rf},defaultTabComponent:Df,watermarkComponent:Pf,onReady:Ot,singleTabMode:"default",tabAnimation:"smooth",theme:Bt,popoutUrl:"/popout.html"})}),M&&rr.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:M.x,top:M.y},children:mt.map(R=>{if(R.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},R.id);let W=t.jsx(Xl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{};switch(R.id){case"dockInWindow":case"dockBackToGrid":W=t.jsx(Jl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ie(M.tabKey),B(null)};break;case"moveBackToMain":W=t.jsx(Yl,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ae(M.tabKey),B(null)};break;case"floatAsPanel":W=t.jsx(Ql,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ee(M.tabKey),B(null)};break;case"openInNewWindow":W=t.jsx(ql,{size:13,className:"shrink-0 opacity-70"}),H=()=>{pe(M.tabKey),B(null)};break;case"setShortcut":H=F=>{F.stopPropagation(),$e(M.tabKey),B(null)};break;case"removeShortcut":W=t.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),H=()=>{const F={...Me};delete F[M.tabKey],Ze(F),B(null)};break;case"hideTab":W=t.jsx(ri,{size:13,className:"shrink-0 opacity-70"}),H=()=>{ve(M.tabKey),B(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 ${R.tone==="muted"?"text-text-muted":""}`,onClick:H,children:[W,t.jsx("span",{className:"flex-1 min-w-0",children:R.label}),R.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:R.shortcut}):null]},R.id)})}),M.sourceDocument.body),He&&rr.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:()=>$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:R=>R.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"})]})}),Ct.body)]})}const Ac="adhdev-recent-launch-args-v1",Ef=8;function Kf(e){return String(e||"").trim().replace(/\s+/g," ")}function Mc(e,s){return`${e.trim()}::${s.trim()}`}function Tc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ac)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Bf(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ac,JSON.stringify(e))}catch{}}function Lc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Tc().byKey[Mc(r,n)])==null?void 0:i.items)||[]}function _c(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=Kf(r);if(!n||!a||!i)return;const c=Tc(),l=Mc(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Ef);c.byKey[l]={items:p},Bf(c)}function Wf(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 La(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 Rc(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=La((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 Pc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ms(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 Tn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Of(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Do(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function $o(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 Hf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Uf(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 Ff(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 zf({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,b]=o.useState(null),[k,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]),y=o.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const K=Of(A.daemonId||A.id);return!!(d!=null&&d.id)&&K===d.id}),[d==null?void 0:d.id,r]),v=oc(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=v.diagnostics,C=v.loading,P=v.applyDiagnostics,g=o.useMemo(()=>{const A=new Map;for(const K of y){const V=s.find(U=>U.sessionId===K.sessionId||U.routeId===K.id);K.sessionId&&V&&A.set(K.sessionId,V)}return A},[y,s]),I=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}),K=Tn(A);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Could not load hosted runtime diagnostics");P(K.diagnostics||K.result||null),m("")}catch(A){const K=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";m(K)}finally{L(!1)}}},[d==null?void 0:d.id,P,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||C||k||I()},[d==null?void 0:d.id,h,C,I,k]);const j=o.useCallback(async(A,K)=>{if(!(d!=null&&d.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${K.displayName}?
|
|
55
|
+
This will terminate the hosted runtime.`))return;const V=`${A}:${K.sessionId}`;b(V);try{const U=await a(d.id,A,{sessionId:K.sessionId}),ce=Tn(U);if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Session host action failed");const Y=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${Y}: ${K.displayName}`,"success"),await I()}catch(U){const ce=U instanceof Error?U.message:"Session host action failed";m(ce),lt.showToast(ce,"warning")}finally{b(U=>U===V?null:U)}},[d==null?void 0:d.id,I,a]),w=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.`))){b("session_host_prune_duplicate_sessions");try{const K=await a(d.id,"session_host_prune_duplicate_sessions",{}),V=Tn(K);if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Duplicate prune failed");const U=V.result||{},ce=Array.isArray(U.prunedSessionIds)?U.prunedSessionIds.length:0,Y=typeof U.duplicateGroupCount=="number"?U.duplicateGroupCount:0;lt.showToast(`Pruned ${ce} duplicate runtime(s) across ${Y} group(s)`,"success"),await I()}catch(K){const V=K instanceof Error?K.message:"Duplicate prune failed";m(V),lt.showToast(V,"warning")}finally{b(K=>K==="session_host_prune_duplicate_sessions"?null:K)}}},[d==null?void 0:d.id,I,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((A,K)=>(K.lastActivityAt||0)-(A.lastActivityAt||0)),[h==null?void 0:h.sessions]),$=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)||[]}:Rc(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),N=$.liveRuntimes,T=$.recoverySnapshots,M=$.inactiveRecords,B=o.useMemo(()=>Ff(N),[N]),_=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[h==null?void 0:h.recentLogs]),S=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),O=(A,K)=>{var le,pe;const V=g.get(A.sessionId),U=y.find(ae=>ae.sessionId===A.sessionId),ce=f===`session_host_resume_session:${A.sessionId}`,Y=f===`session_host_restart_session:${A.sessionId}`,oe=f===`session_host_stop_session:${A.sessionId}`,Q=La(A.meta),te=typeof((le=A.meta)==null?void 0:le.runtimeRecoveryError)=="string"?String(A.meta.runtimeRecoveryError):"",ue=K==="recovery"?"Recover":"Resume",Ne=Pc(K);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||(U==null?void 0:U.runtimeDisplayName)||(U==null?void 0:U.cliName)||A.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${Uf(A.lifecycle)}`,children:A.lifecycle}),Q&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Q})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(U==null?void 0:U.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:((pe=A.writeOwner)==null?void 0:pe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Hf(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(na,{size:11})," ",A.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",$o(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:"",` · Next: ${Ne}`]}),te&&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:te})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[V&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(V),c()},children:"Open chat"}),K==="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:()=>{j("session_host_resume_session",A)},children:ce?`${ue}ing…`:ue}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",A)},children:Y?"Restarting…":"Restart"}),K==="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:()=>{j("session_host_stop_session",A)},children:oe?"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(zt,{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:()=>{I()},disabled:C||k,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Ws,{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(Nt,{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(xs,{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:T.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:$o(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Do(h.hostStartedAt)})]})]}),_&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(xs,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:_.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Jr,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{w()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[y.length," dashboard session",y.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:Ms("live")}),N.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:N.map(A=>O(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:Ms("recovery")}),T.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:T.map(A=>O(A,"recovery"))})]}),M.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:Ms("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:M.map(A=>O(A,"inactive"))})]}),S.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:S.map(A=>{const K=x.find(V=>V.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:(K==null?void 0:K.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:Do(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Dc(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Qs({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 $c({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?bc(n):null;return t.jsxs(Qs,{title:"Saved history",description:ga(),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:Zu()})]}),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 Ln(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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Ct,It;const f=ur(),b=o.useMemo(()=>[...e].sort(da),[e]),[k,L]=o.useState(((Ct=b[0])==null?void 0:Ct.id)||""),d=o.useMemo(()=>b.find(q=>q.id===k)||b[0],[k,b]),y=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[d]),v=(d==null?void 0:d.defaultWorkspaceId)||null,[h,C]=o.useState(""),[P,g]=o.useState(""),[I,j]=o.useState(Ln(b[0])),[w,x]=o.useState(""),[$,N]=o.useState(""),[T,M]=o.useState([]),[B,_]=o.useState(""),[S,O]=o.useState([]),[G,A]=o.useState(!1),[K,V]=o.useState(!1),[U,ce]=o.useState(""),[Y,oe]=o.useState(!1),[Q,te]=o.useState(()=>yt()),[ue,Ne]=o.useState(!1),[le,pe]=o.useState(null),[ae,z]=o.useState(!1),[ve,ee]=o.useState(""),[we,re]=o.useState(!1),[ie,ne]=o.useState(""),[je,xe]=o.useState([]),[E,ke]=o.useState(!1),[ge,Ce]=o.useState(""),[J,Me]=o.useState(!1),He=o.useRef(null),$e=o.useRef(0);o.useEffect(()=>{var q;!k&&((q=b[0])!=null&&q.id)&&L(b[0].id)},[k,b]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ze=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[d]),Ye=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]),ot=o.useMemo(()=>I==="cli"?Ze.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):I==="acp"?Ge.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):Ye,[Ge,I,Ze,Ye]);o.useEffect(()=>{var Ee;if(!d)return;if(He.current!==d.id){He.current=d.id,C(v||((Ee=y[0])==null?void 0:Ee.id)||"__home__"),g(""),j(Ln(d)),x(""),N(""),_(""),O([]),V(!1),ce(""),te(yt()),ee("");return}C(R=>{var W;return R==="__custom__"||R==="__home__"||y.some(H=>H.id===R)?R:v||((W=y[0])==null?void 0:W.id)||"__home__"}),j(R=>R==="ide"&&Ye.length>0||R==="cli"&&Ze.length>0||R==="acp"&&Ge.length>0?R:Ln(d))},[Ge.length,Ze.length,v,Ye.length,d,y]),o.useEffect(()=>{var q;I&&(ot.some(Ee=>Ee.id===w)||x(((q=ot[0])==null?void 0:q.id)||""))},[I,ot,w]);const et=o.useCallback(async(q,Ee)=>{const R=$e.current+1;return $e.current=R,A(!0),ce(""),u(q,Ee).then(W=>{$e.current===R&&O(W)}).catch(W=>{$e.current===R&&(O([]),ce(W instanceof Error?W.message:"Could not load saved sessions"))}).finally(()=>{$e.current===R&&(A(!1),V(!0))})},[u]),mt=o.useCallback((q,Ee)=>{M(Lc(q,Ee))},[]);o.useEffect(()=>{if(_(""),te(yt()),!d||!w||I==="ide"?M([]):mt(d.id,w),V(!1),I!=="cli"){O([]),ce(""),A(!1);return}if(!d||!w){O([]),ce(""),A(!1);return}et(d.id,w)},[I,mt,et,d,w]),o.useEffect(()=>{if(!B)return;const q=S.find(Ee=>Ee.providerSessionId===B);q!=null&&q.canResume||_("")},[S,B]);const Ve=h==="__custom__"?P.trim():h==="__home__"?"":((It=y.find(q=>q.id===h))==null?void 0:It.path)||"",it=o.useMemo(()=>d?r.filter(q=>q.id!==d.id&&q.daemonId===d.id).map(q=>q.workspace):[],[r,d]),ft=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(q=>q.workspace),[d]),ht=o.useCallback(q=>{const Ee=String(q.workspace||"").trim();if(!Ee)return;const R=y.find(W=>Mr(W.path)===Mr(Ee));if(R){C(R.id),g("");return}C("__custom__"),g(Ee)},[y]),ye=o.useCallback(q=>{const Ee=String(q.workspace||"").trim();if(!Ee)return{workspaceId:null,workspacePath:null};const R=y.find(W=>Mr(W.path)===Mr(Ee));return R?{workspaceId:R.id,workspacePath:null}:{workspaceId:null,workspacePath:Ee}},[y]),Ue=o.useMemo(()=>S.find(q=>q.providerSessionId===B)||null,[S,B]),ze=o.useMemo(()=>{var Ee;if(I!=="cli"||!d||!w)return null;const q=((Ee=Ze.find(R=>R.type===w))==null?void 0:Ee.displayName)||w;return{routeId:d.id,daemonId:d.id,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:q,agentType:w,status:"idle",title:q,messages:[],ideType:w,workspaceName:Ve,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${w}`,machineName:Mt(d,{fallbackId:d.id})}},[I,Ze,Ve,d,B,w]),Xe=o.useCallback(()=>{var Ee;if(!d)return;C("__custom__"),re(!0),Ce("");const q=an(d.platform,nn(P.trim(),Ve,it,ft,d.defaultWorkspacePath,(Ee=y.find(R=>R.id===v))==null?void 0:Ee.path,y.map(R=>R.path)));ke(!0),a(d.id,q).then(R=>{ne(R.path),g(R.path),xe(R.directories)}).catch(R=>{Ce(R instanceof Error?R.message:"Could not load folder")}).finally(()=>ke(!1))},[P,v,ft,it,a,Ve,d,y]),pt=o.useCallback(q=>{d&&(ke(!0),Ce(""),a(d.id,q).then(Ee=>{ne(Ee.path),g(Ee.path),xe(Ee.directories)}).catch(Ee=>{Ce(Ee instanceof Error?Ee.message:"Could not load folder")}).finally(()=>ke(!1)))},[a,d]),gt=o.useCallback(async()=>{if(!d||!Ve)return;Me(!0),ee("");const q=await i(d.id,Ve);if(Me(!1),!q.ok){ee(q.error||"Could not save workspace");return}ee("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Ve,d]),vt=o.useCallback(async()=>{if(!d||!I||!w)return;z(!0),ee("");const q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],Ee=I==="ide"?await c(d.id,w,{workspacePath:Ve||null}):await l(d.id,I,w,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ve||null,resumeSessionId:I==="cli"&&B?B:null,cliArgs:q});if(z(!1),!Ee.ok){ee(Ee.error||"Could not start session");return}I!=="ide"&&$.trim()&&(_c(d.id,w,$),mt(d.id,w)),n()},[I,$,mt,n,c,l,Ve,d,B,w,h]),Ot=I?Ui(I,I==="cli"&&!!B):"Start",Bt=I?Fi(I,I==="cli"&&!!B):"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(Nt,{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(Qs,{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:ae,children:b.map(q=>t.jsx("option",{value:q.id,children:Mt(q,{fallbackId:q.id})},q.id))})}),I==="cli"&&t.jsx(Qs,{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:ae||!d,onClick:()=>Ne(!0),children:[t.jsx(zt,{size:14}),Qu()]})}),t.jsxs(Qs,{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:Xe,disabled:ae,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:q=>{const Ee=q.target.value;C(Ee),Ee==="__custom__"?Xe():ee("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),y.map(q=>t.jsxs("option",{value:q.id,children:[q.id===v?"⭐ ":"",sn(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.":Ve||"Select a workspace folder."}),h==="__custom__"&&Ve&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:ae,children:[t.jsx(Ls,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:gt,disabled:ae||J,children:J?"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:Ze.length>0},{id:"ide",label:"IDE",enabled:Ye.length>0},{id:"acp",label:"ACP",enabled:Ge.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(q.id),disabled:!q.enabled||ae,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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(q.id),disabled:ae,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)),ot.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."})]})]}),I!=="ide"&&t.jsxs(Qs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:q=>N(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:ae}),T.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:T.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>N(q),disabled:ae,title:q,children:q},q))})]}),I==="cli"&&t.jsx($c,{busy:ae,savedSessionsLoading:G,savedSessionsError:U,selectedSession:Ue,onRefresh:()=>{!d||!w||et(d.id,w)},onOpenHistory:()=>{!d||!w||(oe(!0),Dc({hasLoadedInitialResults:K,isLoading:G})&&et(d.id,w))},onClearSelection:()=>_("")}),ve&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ve.includes("saved")||ve.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ve})]}),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:ae,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:vt,disabled:ae||!I||!w||h==="__custom__"&&!Ve,children:[t.jsx(oa,{size:14}),ae?Bt:Ot]})]})]})}),we&&t.jsx(cn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ie,directories:je,busy:E,error:ge,onClose:()=>re(!1),onNavigate:pt,onConfirm:q=>{g(q),ne(q),C("__custom__"),re(!1)}}),Y&&ze&&t.jsx(wa,{activeConv:ze,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:S,isSavedSessionsLoading:G,isResumingSavedSessionId:le,savedHistoryFilters:Q,onSavedHistoryFiltersChange:te,onClose:()=>oe(!1),onNewChat:()=>{_(""),oe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!w||et(d.id,w)},onResumeSavedSession:q=>{if(!d||!w||le||!q.canResume)return;const Ee=ye(q);_(q.providerSessionId),ht(q),pe(q.providerSessionId),oe(!1),z(!0),ee(""),l(d.id,"cli",w,{workspaceId:Ee.workspaceId,workspacePath:Ee.workspacePath,resumeSessionId:q.providerSessionId}).then(R=>{if(!R.ok){ee(R.error||"Could not resume session");return}n()}).finally(()=>{z(!1),pe(R=>R===q.providerSessionId?null:R)})}}),ue&&d&&t.jsx(zf,{machineCards:[{id:d.id,label:Mt(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",yc(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:q=>{Ne(!1),n(),m(q)},onClose:()=>Ne(!1)})]}):null}function Gf(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 qf(e){return e instanceof Error?e.message:String(e||"")}function Yf(e){const s=qf(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Xf({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:b,ides:k,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:y,setActionLogs:v,isStandalone:h,initialDataLoaded:C,userName:P,requestedMobileTabKey:g,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:w,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,containerRef:N,isSplitMode:T,numGroups:M,groupSizes:B,groupedConvs:_,clearedTabs:S,focusedGroup:O,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:K,closeGroup:V,handleResizeStart:U,groupActiveTabIds:ce,setGroupActiveTabIds:Y,groupTabOrders:oe,setGroupTabOrders:Q,toggleHiddenTab:te,visibleConversations:ue,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:pe,onHideConversation:ae,onShowHiddenConversation:z,onShowAllHiddenConversations:ve,scrollToBottomRequest:ee,machineEntries:we,onBrowseMachineDirectory:re,onSaveMachineWorkspace:ie,onLaunchMachineIde:ne,onLaunchMachineProvider:je,onListMachineSavedSessions:xe,notifications:E,notificationUnreadCount:ke,notificationStateBySessionId:ge,onMarkNotificationRead:Ce,onMarkNotificationUnread:J,onDeleteNotification:Me,onMarkNotificationTargetRead:He}){const $e=nt.useRef(null),[Ze,Ge]=nt.useState(!1),[Ye,ot]=nt.useState(!1),[et,mt]=nt.useState(!1),[Ve,it]=nt.useState(!1),ft=nt.useCallback(Z=>{var Re;rr.flushSync(()=>{z(Z)}),(Re=$e.current)==null||Re.restoreHiddenTabToSavedLocation(Z.tabKey)},[z]),ht=nt.useCallback(Z=>{var Oe;const Re=f.find(De=>Or(De,Z))||b.find(De=>Or(De,Z));Re&&(b.some(De=>De.tabKey===Re.tabKey)&&ft(Re),pe(Re.tabKey),(Oe=$e.current)==null||Oe.activateConversationTab(Re.tabKey)),Ce(Z.id),(Z.sessionId||Z.providerSessionId||Z.tabKey||Z.routeId)&&He({sessionId:Z.sessionId,providerSessionId:Z.providerSessionId,tabKey:Z.tabKey,routeId:Z.routeId}),Ge(!1)},[ft,b,f,pe,Ce,He]),[ye,Ue]=nt.useState(!1),[ze,Xe]=nt.useState("quickstart"),[pt,gt]=nt.useState("workspace"),vt=!e&&!s,Ot=nt.useCallback(Z=>{Ge(Z),Z&&ot(!1)},[]),Bt=nt.useCallback(Z=>{ot(Z),Z&&Ge(!1)},[]),Ct=nt.useCallback(()=>{var Re;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Re=$e.current)==null||Re.resetAllPanelsToMain(),ot(!1))},[]),It=nt.useCallback(()=>{Xe(ue.length===0?"quickstart":"shortcuts"),gt("workspace"),mt(!0),Ge(!1),ot(!1)},[ue.length]),q=nt.useCallback(async Z=>{var D;if(!r)return;const Re=(D=r.modalButtons)==null?void 0:D[Z];if(!Re)return;const Oe=ir(r);if(!Oe)return;const De=Re.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),xt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(De);try{await d(Oe,"resolve_action",{button:Re,action:xt?"approve":"reject",buttonIndex:Z,...As(r)})}catch(X){Yf(X)||console.error("[Shortcut approval] Failed:",X)}},[r,d]),{isMac:Ee,actionDefinitions:R,actionShortcuts:W,shortcutListening:H,shortcutListeningDraft:F,setShortcutListening:se,setShortcutListeningDraft:Se,saveShortcuts:Te}=Cf({enabled:vt&&!et,onTrigger:Z=>{var Re,Oe,De,xt,D,X,de,Pe,fe,he,Qe,St,ct,qt,ts,pr;if(Z==="openShortcutHelp"){It();return}if(Z==="hideCurrentTab"){r&&ae(r);return}if(Z==="toggleHiddenTabs"){Bt(!Ye);return}if(Z==="openHistoryForActiveTab"){r&&!Je(r)&&c(r);return}if(Z==="openRemoteForActiveTab"){r&&!tt(r)&&!Je(r)&&l(r);return}if(Z==="splitActiveTabRight"){(Re=$e.current)==null||Re.splitActiveTabRight();return}if(Z==="splitActiveTabDown"){(Oe=$e.current)==null||Oe.splitActiveTabDown();return}if(Z==="floatActiveTab"){(De=$e.current)==null||De.floatActiveTab();return}if(Z==="popoutActiveTab"){(xt=$e.current)==null||xt.popoutActiveTab();return}if(Z==="dockActiveTab"){(D=$e.current)==null||D.dockActiveTab();return}if(Z==="focusLeftPane"){(X=$e.current)==null||X.focusLeftPane();return}if(Z==="focusRightPane"){(de=$e.current)==null||de.focusRightPane();return}if(Z==="focusUpPane"){(Pe=$e.current)==null||Pe.focusUpPane();return}if(Z==="focusDownPane"){(fe=$e.current)==null||fe.focusDownPane();return}if(Z==="moveActiveTabToLeftPane"){(he=$e.current)==null||he.moveActiveTabToLeftPane();return}if(Z==="moveActiveTabToRightPane"){(Qe=$e.current)==null||Qe.moveActiveTabToRightPane();return}if(Z==="moveActiveTabToUpPane"){(St=$e.current)==null||St.moveActiveTabToUpPane();return}if(Z==="moveActiveTabToDownPane"){(ct=$e.current)==null||ct.moveActiveTabToDownPane();return}if(Z==="triggerPrimaryApprovalAction"){q(0);return}if(Z==="triggerSecondaryApprovalAction"){q(1);return}if(Z==="triggerTertiaryApprovalAction"){q(2);return}if(Z==="setActiveTabShortcut"){(qt=$e.current)==null||qt.setShortcutForActiveTab();return}if(Z==="selectPreviousGroupTab"){(ts=$e.current)==null||ts.activatePreviousTabInGroup();return}if(Z==="selectNextGroupTab"){(pr=$e.current)==null||pr.activateNextTabInGroup();return}!r||!tt(r)||Je(r)||Z==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),Ie=nt.useCallback(()=>{mt(!1),se(null),Se([])},[se,Se]),We=nt.useMemo(()=>pt==="all"?R:R.filter(Z=>Gf(Z)===pt),[R,pt]),Ke=nt.useCallback(()=>{const Z=Object.fromEntries(R.map(Re=>[Re.id,""]));Te(Z)},[R,Te]),Ae=nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Z=Object.fromEntries(R.map(Re=>[Re.id,Re.defaultShortcut]));Te(Z)},[R,Te]);return nt.useEffect(()=>{const Z=Re=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Re.metaKey&&Re.key.toLowerCase()==="w":Re.ctrlKey&&Re.key.toLowerCase()==="w")&&(Re.preventDefault(),r&&ae&&ae(r))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[r,ae]),nt.useEffect(()=>{if(!et||H)return;const Z=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Ie())};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[Ie,et,H]),nt.useEffect(()=>{if(!vt){Ue(!1);return}Ue(!0);const Z=window.setTimeout(()=>{Ue(!1)},1e4);return()=>window.clearTimeout(Z)},[vt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Vu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:ue,hiddenConversations:b,onOpenHistory:c,onHideConversation:ae,onShowConversation:ft,onShowAllHidden:ve,onResetPanelsToMain:Ct,notifications:E,notificationUnreadCount:ke,onOpenNotification:ht,onMarkNotificationRead:Ce,onMarkNotificationUnread:J,onDeleteNotification:Me,inboxOpen:Ze,onInboxOpenChange:Ot,hiddenOpen:Ye,onHiddenOpenChange:Bt,onOpenNewSession:s?void 0:()=>it(!0),actionShortcuts:W,onOpenRemote:()=>{!r||tt(r)||Je(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(ff,{conversations:f,hiddenConversations:b,ides:k,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:y,setActionLogs:v,isStandalone:h,userName:P,requestedActiveTabKey:g,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:w,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ft,onShowAllHiddenConversations:ve,onOpenNewSession:()=>it(!0),notificationStateBySessionId:ge,onMarkNotificationTargetRead:He}):s?t.jsx(jf,{containerRef:N,isSplitMode:T,numGroups:M,groupSizes:B,groupedConvs:_,clearedTabs:S,ides:k,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:y,setActionLogs:v,isStandalone:h,hasRegisteredMachines:we.length>0,userName:P,focusedGroup:O,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:K,closeGroup:V,handleResizeStart:U,groupActiveTabIds:ce,setGroupActiveTabIds:Y,groupTabOrders:oe,setGroupTabOrders:Q,toggleHiddenTab:te,allowTabShortcuts:!1}):t.jsx($f,{visibleConversations:ue,clearedTabs:S,ides:k,actionLogs:L,sendDaemonCommand:d,setLocalUserMessages:y,setActionLogs:v,isStandalone:h,hasRegisteredMachines:we.length>0,initialDataLoaded:C,userName:P,toggleHiddenTab:te,actionShortcuts:W,registerActionHandlers:Z=>{$e.current=Z},notificationStateBySessionId:ge,onActiveTabChange:pe,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:le,scrollToBottomRequest:ee}),Ve&&t.jsx(Vf,{machines:we,conversations:f,ides:k,onClose:()=>it(!1),onBrowseDirectory:re,onSaveWorkspace:ie,onLaunchIde:ne,onLaunchProvider:je,onListSavedSessions:xe,sendDaemonCommand:d,onOpenConversation:Z=>{it(!1),z(Z),pe(Z.tabKey)}}),et&&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:Ie,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:Z=>Z.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:Ie,"aria-label":"Close dashboard guide",children:t.jsx(Nt,{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(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${ze===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>Xe(Z.id),children:Z.label},Z.id))}),ze==="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 ",Ee?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ze==="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."]})]})]})]}),ze==="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(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${pt===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>gt(Z.id),children:Z.label},Z.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ke,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:Ae,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:We.map(Z=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${H===Z.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:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Z.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:H===Z.id?F.length>0?`${F.join(" ")} ...`:"Listening...":W[Z.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{se(Z.id),Se([])},children:H===Z.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Re={...W};Re[Z.id]="",Te(Re)},children:"Disable"})]})]})},Z.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ee?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:It,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${ye?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),ye&&t.jsx("span",{children:"Guide"})]})]})}const _n=[{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 Qf({onClose:e}){const[s,r]=o.useState(0),n=_n[s],a=s===_n.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(Nt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:_n.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
57
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
58
58
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
59
|
-
`})]})}function Jf({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 Zf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Vi(s),[s]),p=o.useMemo(()=>e?ja(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(g=>g.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(g=>g.streamSource==="agent-stream"),[p]),y=o.useMemo(()=>e?Kt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!y)return;const g=y.streamSource==="native"?"native":y.tabKey;!g||c===g||c==="native"&&l(g)},[c,y,i]),o.useEffect(()=>{var g;c!=="native"&&(f.some(v=>v.tabKey===c)||l(((g=f[0])==null?void 0:g.tabKey)||"native"))},[c,f]),o.useEffect(()=>{c==="native"&&(m||f[0]&&l(f[0].tabKey))},[c,m,f]);const k=o.useMemo(()=>c==="native"&&m?m:f.find(g=>g.tabKey===c)||y||m||f[0],[c,m,y,f]),T=o.useMemo(()=>f.map(g=>({tabKey:g.tabKey,title:Wi(g)||a,status:g.status})),[f,a]),d=o.useCallback(g=>{if(g)return p.find(v=>Or(v,{sessionId:g,routeId:g,tabKey:g,providerSessionId:g}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:k,conversations:p,extensionTabs:T,hasExtensions:T.length>0,resolveConversationByTarget:d}}function eh({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:y,onClose:k}){const[T,d]=o.useState("split"),[g,v]=o.useState(()=>Qt(e)?"native":e.tabKey),h=o.useRef(null),C=o.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),P=o.useMemo(()=>at((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:b,extensionTabs:I,hasExtensions:j}=Zf({ideData:C,allIdes:r,connectionStates:n,localUserMessages:i,ideName:P||"IDE",preferredTabKey:Qt(e)?void 0:e.tabKey}),w=o.useMemo(()=>C?Kt(b,C.id):null,[C,b]);o.useEffect(()=>{const A=h.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=K,!(A&&A.routeId===K.routeId&&A.tabKey===K.tabKey&&A.streamSource===K.streamSource)){if(Qt(e)){v("native");return}v(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(g==="native"){if(b.some(A=>A.streamSource==="native"))return;(w==null?void 0:w.streamSource)==="agent-stream"&&v(w.tabKey);return}if(!b.some(A=>A.tabKey===g)){if((w==null?void 0:w.streamSource)==="agent-stream"){v(w.tabKey);return}v("native")}},[b,g,w]);const x=o.useMemo(()=>g==="native"?b.find(A=>A.streamSource==="native")||e:b.find(A=>A.tabKey===g)||e,[e,b,g]),$=ic(x),N=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...x,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:x,[x,$]),L=dr(N),M=rn({sendDaemonCommand:c,activeConv:N,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:B,screenshotUsage:_,handleRemoteAction:S}=kc({doId:L,targetSessionId:Ci(N),connState:N.connectionState||"new",viewMode:T}),O=o.useMemo(()=>a.filter(A=>A.routeId===N.tabKey),[a,N.tabKey]);o.useEffect(()=>{y==null||y(N)},[N,y]),o.useEffect(()=>{const A=K=>{K.key==="Escape"&&k()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[k]);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:k,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(Tt,{size:16})}),t.jsx("span",{className:"truncate",children:ma(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:k,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 K=T===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"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(Dl,{size:15}):t.jsx(Tt,{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(aa,{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:k,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${T==="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:[T!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${T==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Jf,{hasExtensions:j,ideName:P||"IDE",activeChatTab:g,extensionTabs:I,onSelectTab:v}),t.jsx(pi,{activeConv:N,onModalButton:M.handleModalButton}),t.jsx(Gn,{activeConv:N,ideEntry:C,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:O,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${T==="split"?"order-1 md:order-2":""}`,children:t.jsx(ci,{addLog:()=>{},connState:N.connectionState||"new",connScreenshot:B,screenshotUsage:_,transportType:N.transport,onAction:S})})]})]})})}function th({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Hu(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 sh({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:y,remoteDialogConv:k,remoteDialogIdeEntry:T,connectionStates:d,actionLogs:g,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:b,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:w,onCloseRemoteDialog:x,cliStopDialogOpen:$,cliStopTargetConv:N,onCancelCliStop:L,onStopCliNow:M,onSaveCliAndStop:B,toasts:_,onDismissToast:S,onClickToast:O,showOnboarding:G,onCloseOnboarding:A}){var U;const[K,V]=nt.useState(()=>yt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(wa,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:K,onSavedHistoryFiltersChange:V,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:y}),k&&t.jsx(eh,{activeConv:k,ideEntry:T,ides:r,connectionStates:d,actionLogs:g,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:b,userName:I,onOpenHistory:j,onConversationChange:w,onClose:x}),$&&N&&(tt(N)||Je(N))&&t.jsx(th,{activeConv:N,canSaveAndStop:tt(N)&&!Je(N)&&!!((U=N.resume)!=null&&U.supported),onCancel:L,onStopNow:M,onSaveAndStop:B}),t.jsx(zi,{toasts:_,onDismiss:S,onClickToast:O}),G&&t.jsx(Qf,{onClose:A})]})}function rh({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(Ws,{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=Mt(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(Nt,{size:16})})]})}function nh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Eo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ah(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function oh(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 ih(){var $a,Ea,Ka,Ba,Wa;const{sendCommand:e}=Lt(),s=ur(),r=sa(),n=Bs(),[a,i]=dl(),c=a.get("activeTab"),l=(($a=r.state)==null?void 0:$a.openRemoteForTabKey)||null,u=((Ea=r.state)==null?void 0:Ea.openMachineId)||null,p=((Ka=r.state)==null?void 0:Ka.mobileSection)||null,m=$i(),f=m.ides||[],y=m.initialLoaded??!0,{updateRouteChats:k,setToasts:T}=m,[d,g]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),v=m.toasts||[],h=m.wsStatus||"connected",C=m.isConnected??!0,P=m.connectionStates||{},b=m.showReconnected||!1,{groupAssignments:I,setGroupAssignments:j,focusedGroup:w,setFocusedGroup:x,groupActiveTabIds:$,setGroupActiveTabIds:N,groupTabOrders:L,setGroupTabOrders:M,groupSizes:B,setGroupSizes:_,isMobile:S,hasHydratedStoredLayout:O,hydrateStoredLayout:G}=yp(),[A,K]=o.useState(!1),[V,U]=o.useState(!1),[ce,Y]=o.useState(null),[oe,Q]=o.useState([]),[te,ue]=o.useState(!1),[Ne,le]=o.useState(null),[pe]=o.useState(()=>ac()),[ae,z]=o.useState([]),[ve,ee]=o.useState({}),[we,re]=o.useState({}),[ie,ne]=o.useState({}),[je,xe]=o.useState(null),[E,ke]=o.useState(null),[ge,Ce]=o.useState(null),J=o.useRef(null);cr("Dashboard",{ideCount:f.length,toastCount:v.length,focusedGroup:w,groupCount:Object.keys(I).length,localMessageTabs:Object.keys(ve).length,actionLogCount:ae.length});const Me=f.find(be=>be.type==="adhdev-daemon"),He=o.useMemo(()=>f.filter(be=>be.type==="adhdev-daemon").sort(da),[f]),$e=!!Me;o.useEffect(()=>{!Me||!(!Me.detectedIdes||!Me.availableProviders||!Me.recentLaunches||!Me.workspaces)||s(Me.id,{minFreshMs:3e4}).catch(()=>{})},[Me,s]);const Ze=(Me==null?void 0:Me.terminalBackend)||null,Ge=Me?Mt(Me,{fallbackId:Me.id}):null,Ye=(Me==null?void 0:Me.id)||null,ot=o.useMemo(()=>qm(f,we),[f,we]),{hiddenTabs:et,hideTab:mt,toggleTab:Ve,showTab:it,showAllTabs:ft}=Gm(),{chatIdes:ht,conversations:ye,visibleConversations:Ue,visibleTabKeys:ze,resolveConversationBySessionId:Xe,resolveConversationByTarget:pt}=op({ides:ot,connectionStates:P,localUserMessages:ve,clearedTabs:ie,hiddenTabs:et});_u(ye),o.useEffect(()=>{Object.keys(we).length!==0&&re(be=>Ym(be,f))},[f,we]);const gt=o.useMemo(()=>tn(f),[f]),{notifications:vt,unreadCount:Ot,notificationStateBySessionId:Bt,markRead:Ct,markUnread:It,markTargetRead:q,deleteNotification:Ee}=Hp({conversations:ye,liveSessionInboxState:gt}),R=o.useRef(null),{containerRef:W,normalizedGroupAssignments:H,numGroups:F,isSplitMode:se,groupedConvs:Se,moveTabToGroup:Te,closeGroup:Ie,handleResizeStart:We,splitTabRelative:Ke}=Ip({groupAssignments:I,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:N,setGroupTabOrders:M,groupSizes:B,setGroupSizes:_,isMobile:S,visibleConversations:Ue,visibleTabKeys:ze}),Ae=o.useMemo(()=>{var _e,Le;if(!S){if(je){const me=ye.find(Fe=>Fe.tabKey===je);if(me)return me}return Ue[0]}const be=$[w];if(be){const me=ye.find(Fe=>Fe.tabKey===be);if(me)return me}return((_e=Se[w])==null?void 0:_e[0])||((Le=Se[0])==null?void 0:Le[0])},[je,S,$,w,ye,Se,Ue]);o.useEffect(()=>{if(S){R.current=null;return}if(!(Ae!=null&&Ae.sessionId)){R.current=null;return}const be=Hr(Ae,gt),_e=ui(Ae),Le=[Ae.tabKey,lr(Ae)||"",Ae.lastMessageHash||"",String(Ae.lastMessageAt||0),be.inboxBucket,be.unread?"1":"0"].join(":");if(R.current===Le)return;const me=()=>{if(document.visibilityState!=="visible"||R.current===Le)return;R.current=Le;const Fe=Math.max(Date.now(),is(Ae),be.lastUpdated||0);q({..._e},Fe),e(Ae.daemonId||Ae.routeId,"mark_session_seen",{sessionId:Ae.sessionId,seenAt:Fe}).catch(()=>{})};if(document.visibilityState==="visible"){const Fe=setTimeout(me,1500),st=()=>{document.visibilityState!=="visible"&&clearTimeout(Fe)};return document.addEventListener("visibilitychange",st),()=>{clearTimeout(Fe),document.removeEventListener("visibilitychange",st)}}else{const Fe=()=>{document.visibilityState==="visible"&&(setTimeout(me,800),document.removeEventListener("visibilitychange",Fe))};return document.addEventListener("visibilitychange",Fe),()=>{document.removeEventListener("visibilitychange",Fe)}}},[Ae,S,gt,q,e]);const{requestedDesktopTabKey:Z,requestedMobileTabKey:Re,consumeRequestedActiveTab:Oe}=ip({isMobile:S,urlActiveTab:c,resolveConversationBySessionId:Xe,setSearchParams:i}),{remoteDialogConv:De,remoteDialogIdeEntry:xt,remoteDialogActiveConv:D,setRemoteDialogActiveConv:X,openRemoteDialog:de,closeRemoteDialog:Pe}=jp({isMobile:S,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:Z,conversations:ye,ides:f,resolveConversationByTarget:pt}),fe=D||De||Ae,he=!!fe&&tt(fe)&&!Je(fe),Qe=o.useMemo(()=>{if(!fe||!he)return null;const be=fe.daemonId||fe.routeId||"",_e=$t(fe);return`${be}:${_e}`},[fe,he]),St=o.useMemo(()=>Ue,[Ue]),ct=S&&pe==="chat",qt=o.useMemo(()=>ye.filter(be=>et.has(be.tabKey)),[ye,et]),ts=o.useCallback(be=>{const _e=new URLSearchParams(a);_e.set("activeTab",be),i(_e,{replace:!0})},[a,i]),pr=o.useCallback(async(be,_e)=>on(e,be,_e),[e]),Ec=o.useCallback(async(be,_e)=>{if(!_e.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Le=await e(be,"workspace_add",{path:_e.trim()});return Le!=null&&Le.success?{ok:!0}:{ok:!1,error:(Le==null?void 0:Le.error)||"Could not save workspace"}}catch(Le){return{ok:!1,error:Le instanceof Error?Le.message:"Could not save workspace"}}},[e]),Kc=o.useCallback(async(be,_e,Le)=>{var me;try{const Fe={ideType:_e,enableCdp:!0};(me=Le==null?void 0:Le.workspacePath)!=null&&me.trim()&&(Fe.workspace=Le.workspacePath.trim());const st=await e(be,"launch_ide",Fe);return!(st!=null&&st.success)&&(st==null?void 0:st.success)!==void 0?{ok:!1,error:(st==null?void 0:st.error)||"Could not launch IDE"}:(Ce({machineId:be,kind:"ide",providerType:_e,workspacePath:(Le==null?void 0:Le.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Fe){return{ok:!1,error:Fe instanceof Error?Fe.message:"Could not launch IDE"}}},[e]),Bc=o.useCallback(async(be,_e,Le,me)=>{var st,Hs,vs;const Fe=Date.now();try{const At={cliType:Le};(st=me==null?void 0:me.workspacePath)!=null&&st.trim()?At.dir=me.workspacePath.trim():me!=null&&me.workspaceId&&(At.workspaceId=me.workspaceId),(Hs=me==null?void 0:me.resumeSessionId)!=null&&Hs.trim()&&(At.resumeSessionId=me.resumeSessionId.trim()),Array.isArray(me==null?void 0:me.cliArgs)&&me.cliArgs.length>0&&(At.cliArgs=me.cliArgs),(vs=me==null?void 0:me.initialModel)!=null&&vs.trim()&&(At.initialModel=me.initialModel.trim());const bt=await e(be,"launch_cli",At),_t=(bt==null?void 0:bt.result)||bt,Us=(_t==null?void 0:_t.sessionId)||(_t==null?void 0:_t.id);return bt!=null&&bt.success&&Us?(ts(Us),{ok:!0}):bt!=null&&bt.success?(Ce({machineId:be,kind:_e,providerType:Le,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:(bt==null?void 0:bt.error)||(_t==null?void 0:_t.error)||`Could not launch ${_e.toUpperCase()} session`}}catch(At){return ah(At)?(Ce({machineId:be,kind:_e,providerType:Le,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:At instanceof Error?At.message:`Could not launch ${_e.toUpperCase()} session`}}},[ts,e]),Wc=o.useCallback(async(be,_e)=>{if(!be||!_e)return[];try{const Le=await e(be,"list_saved_sessions",{providerType:_e,kind:"cli",limit:30}),me=(Le==null?void 0:Le.result)??Le;return Array.isArray(me==null?void 0:me.sessions)?me.sessions:[]}catch(Le){return console.error("List saved sessions failed",Le),[]}},[e]);o.useEffect(()=>{if(!ge)return;const be=Eo(ge.workspacePath),_e=f.find(me=>{var At,bt,_t,Us;if(!me||me.type==="adhdev-daemon"||nh(me.daemonId||me.id)!==ge.machineId||(ar(me)?"cli":Is(me)?"acp":"ide")!==ge.kind||String(me.agentType||me.type||"")!==ge.providerType)return!1;if(ge.resumeSessionId)return String(me.providerSessionId||"")===ge.resumeSessionId;if(be){const un=Eo(me.workspace||me.runtimeWorkspaceLabel);return un?un===be:!1}return Number(me.lastUpdated||me._lastUpdate||me.timestamp||((Us=(_t=(bt=(At=me.activeChat)==null?void 0:At.messages)==null?void 0:bt.at)==null?void 0:_t.call(bt,-1))==null?void 0:Us.timestamp)||0)>=ge.startedAt-5e3});if(!_e)return;const Le=Mi({entrySessionId:_e.sessionId,entryInstanceId:_e.instanceId,entryRouteId:_e.id,conversations:ye});Le&&(Ce(null),ts(Le))},[ye,ts,f,ge]),o.useEffect(()=>{if(!ge)return;const be=window.setTimeout(()=>{Ce(_e=>!_e||_e.startedAt!==ge.startedAt?_e:null)},45e3);return()=>window.clearTimeout(be)},[ge]),Xm({visibleConversations:Ue,clearedTabs:ie,setClearedTabs:ne,setActionLogs:z}),cp({ides:f,sendDaemonCommand:e,setToasts:T,setLocalUserMessages:ee,resolveConversationByTarget:pt});const{isRefreshingHistory:Oc,handleRefreshHistory:Hc}=go({sendDaemonCommand:e,activeConv:Ae,chats:(Ba=f.find(be=>be.id===(Ae==null?void 0:Ae.routeId)))==null?void 0:Ba.chats,updateRouteChats:k,setToasts:T,setLocalUserMessages:ee,setClearedTabs:ne}),{isCreatingChat:Uc,isRefreshingHistory:Fc,handleSwitchSession:zc,handleNewChat:Vc,handleRefreshHistory:Gc}=go({sendDaemonCommand:e,activeConv:fe,chats:(Wa=f.find(be=>be.id===(fe==null?void 0:fe.routeId)))==null?void 0:Wa.chats,updateRouteChats:k,setToasts:T,setLocalUserMessages:ee,setClearedTabs:ne}),dn=o.useCallback(async()=>{if(!(!fe||!he||te)){ue(!0);try{const be=fe.daemonId||fe.routeId,_e=$t(fe),Le=await e(be,"list_saved_sessions",{agentType:_e,providerType:_e,kind:"cli",limit:50}),me=(Le==null?void 0:Le.result)??Le;Q(Array.isArray(me==null?void 0:me.sessions)?me.sessions:[])}catch(be){console.error("Refresh saved sessions failed",be),Q([])}finally{ue(!1)}}},[fe,te,he,e]);o.useEffect(()=>{if(!A){J.current=null;return}if(!he){J.current=null,Q([]),ue(!1);return}!Qe||te||J.current!==Qe&&(J.current=Qe,dn())},[dn,A,te,he,Qe]);const qc=o.useCallback(async be=>{if(!fe||!he||!be.providerSessionId||!be.workspace)return;const _e=fe.daemonId||fe.routeId,Le=$t(fe);try{le(be.providerSessionId);const me=await e(_e,"launch_cli",{cliType:Le,dir:be.workspace,resumeSessionId:be.providerSessionId,initialModel:bi(be.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Fe=(me==null?void 0:me.result)??me,st=typeof(Fe==null?void 0:Fe.sessionId)=="string"?Fe.sessionId:typeof(Fe==null?void 0:Fe.id)=="string"?Fe.id:"";st&&i(Hs=>{const vs=new URLSearchParams(Hs);return vs.set("activeTab",st),vs},{replace:!0}),K(!1)}catch(me){console.error("Resume saved session failed",me)}finally{le(null)}},[fe,he,e,i]);wp({urlActiveTab:S&&!ct?c:null,conversations:ye,resolveConversationBySessionId:Xe,normalizedGroupAssignments:H,hasHydratedStoredLayout:S&&!ct?O:!0,hydrateStoredLayout:S&&!ct?G:()=>{},setGroupActiveTabIds:N,setFocusedGroup:x,setSearchParams:i,historyModalOpen:A,activeConv:Ae,isRefreshingHistory:Oc,ides:f,handleRefreshHistory:Hc});const _a=o.useCallback(async(be,_e)=>{const Le=_e||ce||Ae;if(!Le||!tt(Le)&&!Je(Le))return;const me=$t(Le),Fe=Le.routeId||Le.daemonId||"";try{await e(Fe,"stop_cli",{cliType:me,targetSessionId:Le.sessionId,mode:be})}catch(st){console.error("Stop CLI failed:",st)}},[Ae,ce,e]),Yc=o.useCallback(async be=>{const _e=be||Ae;!_e||!tt(_e)&&!Je(_e)||(Y(_e),U(!0))},[Ae]),Xc=o.useMemo(()=>!Ae||!tt(Ae)||Je(Ae)?null:Ps(Ae),[Ae]),Qc=o.useCallback(async be=>{if(!Ae||!tt(Ae)||Je(Ae))return;const _e=Ps(Ae);if(_e===be)return;const Le=Ae.sessionId;Le&&re(me=>({...me,[Le]:be}));try{await e(es(Ae)||Ae.routeId,"set_cli_view_mode",{targetSessionId:Ae.sessionId,cliType:$t(Ae),mode:be})}catch(me){Le&&re(Fe=>{const st={...Fe};return _e===lc(f,Le)?delete st[Le]:st[Le]=_e,st}),oh(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[Ae,f,e]),{versionMismatchDaemons:Jc,hasRequiredVersionDaemons:Ra,appVersion:Zc,versionBannerDismissed:el,setVersionBannerDismissed:tl,upgradingDaemons:sl,handleBannerUpgrade:rl}=Ap({ides:f,sendDaemonCommand:e}),Pa=o.useCallback(be=>{xe(be.tabKey),i(_e=>{const Le=new URLSearchParams(_e),me=au(be);return me?Le.set("activeTab",me):Le.delete("activeTab"),Le},{replace:!0})},[i]),Da=o.useCallback(be=>{it(be.tabKey),Pa(be)},[Pa,it]),nl=o.useCallback(be=>{mt(be.tabKey)},[mt]);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(Fu,{wsStatus:h,showReconnected:b}),t.jsx(zu,{terminalBackend:Ze,isStandalone:$e,machineLabel:Ge,machineKey:Ye}),(!el||Ra)&&t.jsx(rh,{daemons:Jc,targetVersion:Zc,required:Ra,upgradingDaemons:sl,onUpgrade:rl,onDismiss:()=>tl(!0)}),t.jsx(Xf,{showMobileChatMode:ct,isMobile:S,activeConv:Ae,chatIdes:ht,wsStatus:h,isConnected:C,onOpenHistory:be=>{be&&X(be),K(!0)},onOpenRemote:de,onStopCli:Yc,activeCliViewMode:Xc,onSetActiveCliViewMode:Qc,mobileChatConversations:St,ides:f,actionLogs:ae,sendDaemonCommand:e,setLocalUserMessages:ee,setActionLogs:z,isStandalone:$e,initialDataLoaded:y,userName:m.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Oe,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:W,isSplitMode:se,numGroups:F,groupSizes:B,groupedConvs:Se,clearedTabs:ie,focusedGroup:w,setFocusedGroup:x,moveTabToGroup:Te,splitTabRelative:Ke,closeGroup:Ie,handleResizeStart:We,groupActiveTabIds:$,setGroupActiveTabIds:N,groupTabOrders:L,setGroupTabOrders:M,toggleHiddenTab:Ve,visibleConversations:Ue,hiddenConversations:qt,requestedDesktopTabKey:Z,onRequestedDesktopTabConsumed:Oe,onDesktopActiveTabChange:xe,onHideConversation:nl,onShowHiddenConversation:Da,onShowAllHiddenConversations:ft,scrollToBottomRequest:E,machineEntries:He,onBrowseMachineDirectory:pr,onSaveMachineWorkspace:Ec,onLaunchMachineIde:Kc,onLaunchMachineProvider:Bc,onListMachineSavedSessions:Wc,notifications:vt,notificationUnreadCount:Ot,notificationStateBySessionId:Bt,onMarkNotificationRead:Ct,onMarkNotificationUnread:It,onDeleteNotification:Ee,onMarkNotificationTargetRead:q}),t.jsx("style",{children:`
|
|
59
|
+
`})]})}function Jf({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 Zf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Vi(s),[s]),p=o.useMemo(()=>e?ja(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(y=>y.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(y=>y.streamSource==="agent-stream"),[p]),b=o.useMemo(()=>e?Kt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!b)return;const y=b.streamSource==="native"?"native":b.tabKey;!y||c===y||c==="native"&&l(y)},[c,b,i]),o.useEffect(()=>{var y;c!=="native"&&(f.some(v=>v.tabKey===c)||l(((y=f[0])==null?void 0:y.tabKey)||"native"))},[c,f]),o.useEffect(()=>{c==="native"&&(m||f[0]&&l(f[0].tabKey))},[c,m,f]);const k=o.useMemo(()=>c==="native"&&m?m:f.find(y=>y.tabKey===c)||b||m||f[0],[c,m,b,f]),L=o.useMemo(()=>f.map(y=>({tabKey:y.tabKey,title:Wi(y)||a,status:y.status})),[f,a]),d=o.useCallback(y=>{if(y)return p.find(v=>Or(v,{sessionId:y,routeId:y,tabKey:y,providerSessionId:y}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:k,conversations:p,extensionTabs:L,hasExtensions:L.length>0,resolveConversationByTarget:d}}function eh({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:b,onClose:k}){const[L,d]=o.useState("split"),[y,v]=o.useState(()=>Qt(e)?"native":e.tabKey),h=o.useRef(null),C=o.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),P=o.useMemo(()=>at((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:g,extensionTabs:I,hasExtensions:j}=Zf({ideData:C,allIdes:r,connectionStates:n,localUserMessages:i,ideName:P||"IDE",preferredTabKey:Qt(e)?void 0:e.tabKey}),w=o.useMemo(()=>C?Kt(g,C.id):null,[C,g]);o.useEffect(()=>{const A=h.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=K,!(A&&A.routeId===K.routeId&&A.tabKey===K.tabKey&&A.streamSource===K.streamSource)){if(Qt(e)){v("native");return}v(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(y==="native"){if(g.some(A=>A.streamSource==="native"))return;(w==null?void 0:w.streamSource)==="agent-stream"&&v(w.tabKey);return}if(!g.some(A=>A.tabKey===y)){if((w==null?void 0:w.streamSource)==="agent-stream"){v(w.tabKey);return}v("native")}},[g,y,w]);const x=o.useMemo(()=>y==="native"?g.find(A=>A.streamSource==="native")||e:g.find(A=>A.tabKey===y)||e,[e,g,y]),$=ic(x),N=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...x,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:x,[x,$]),T=dr(N),M=rn({sendDaemonCommand:c,activeConv:N,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:B,screenshotUsage:_,handleRemoteAction:S}=kc({doId:T,targetSessionId:Ci(N),connState:N.connectionState||"new",viewMode:L}),O=o.useMemo(()=>a.filter(A=>A.routeId===N.tabKey),[a,N.tabKey]);o.useEffect(()=>{b==null||b(N)},[N,b]),o.useEffect(()=>{const A=K=>{K.key==="Escape"&&k()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[k]);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:k,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(Tt,{size:16})}),t.jsx("span",{className:"truncate",children:ma(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:k,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 K=L===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"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(Dl,{size:15}):t.jsx(Tt,{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(aa,{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:k,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(Jf,{hasExtensions:j,ideName:P||"IDE",activeChatTab:y,extensionTabs:I,onSelectTab:v}),t.jsx(pi,{activeConv:N,onModalButton:M.handleModalButton}),t.jsx(Gn,{activeConv:N,ideEntry:C,showMetaChips:!1,handleSendChat:M.handleSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:O,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(ci,{addLog:()=>{},connState:N.connectionState||"new",connScreenshot:B,screenshotUsage:_,transportType:N.transport,onAction:S})})]})]})})}function th({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Hu(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 sh({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:b,remoteDialogConv:k,remoteDialogIdeEntry:L,connectionStates:d,actionLogs:y,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:g,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:w,onCloseRemoteDialog:x,cliStopDialogOpen:$,cliStopTargetConv:N,onCancelCliStop:T,onStopCliNow:M,onSaveCliAndStop:B,toasts:_,onDismissToast:S,onClickToast:O,showOnboarding:G,onCloseOnboarding:A}){var U;const[K,V]=nt.useState(()=>yt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(wa,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:K,onSavedHistoryFiltersChange:V,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:b}),k&&t.jsx(eh,{activeConv:k,ideEntry:L,ides:r,connectionStates:d,actionLogs:y,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:g,userName:I,onOpenHistory:j,onConversationChange:w,onClose:x}),$&&N&&(tt(N)||Je(N))&&t.jsx(th,{activeConv:N,canSaveAndStop:tt(N)&&!Je(N)&&!!((U=N.resume)!=null&&U.supported),onCancel:T,onStopNow:M,onSaveAndStop:B}),t.jsx(zi,{toasts:_,onDismiss:S,onClickToast:O}),G&&t.jsx(Qf,{onClose:A})]})}function rh({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(Ws,{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=Mt(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(Nt,{size:16})})]})}function nh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Eo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ah(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function oh(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 ih(){var $a,Ea,Ka,Ba,Wa;const{sendCommand:e}=Lt(),s=ur(),r=sa(),n=Bs(),[a,i]=dl(),c=a.get("activeTab"),l=(($a=r.state)==null?void 0:$a.openRemoteForTabKey)||null,u=((Ea=r.state)==null?void 0:Ea.openMachineId)||null,p=((Ka=r.state)==null?void 0:Ka.mobileSection)||null,m=$i(),f=m.ides||[],b=m.initialLoaded??!0,{updateRouteChats:k,setToasts:L}=m,[d,y]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),v=m.toasts||[],h=m.wsStatus||"connected",C=m.isConnected??!0,P=m.connectionStates||{},g=m.showReconnected||!1,{groupAssignments:I,setGroupAssignments:j,focusedGroup:w,setFocusedGroup:x,groupActiveTabIds:$,setGroupActiveTabIds:N,groupTabOrders:T,setGroupTabOrders:M,groupSizes:B,setGroupSizes:_,isMobile:S,hasHydratedStoredLayout:O,hydrateStoredLayout:G}=yp(),[A,K]=o.useState(!1),[V,U]=o.useState(!1),[ce,Y]=o.useState(null),[oe,Q]=o.useState([]),[te,ue]=o.useState(!1),[Ne,le]=o.useState(null),[pe]=o.useState(()=>ac()),[ae,z]=o.useState([]),[ve,ee]=o.useState({}),[we,re]=o.useState({}),[ie,ne]=o.useState({}),[je,xe]=o.useState(null),[E,ke]=o.useState(null),[ge,Ce]=o.useState(null),J=o.useRef(null);cr("Dashboard",{ideCount:f.length,toastCount:v.length,focusedGroup:w,groupCount:Object.keys(I).length,localMessageTabs:Object.keys(ve).length,actionLogCount:ae.length});const Me=f.find(be=>be.type==="adhdev-daemon"),He=o.useMemo(()=>f.filter(be=>be.type==="adhdev-daemon").sort(da),[f]),$e=!!Me;o.useEffect(()=>{!Me||!(!Me.detectedIdes||!Me.availableProviders||!Me.recentLaunches||!Me.workspaces)||s(Me.id,{minFreshMs:3e4}).catch(()=>{})},[Me,s]);const Ze=(Me==null?void 0:Me.terminalBackend)||null,Ge=Me?Mt(Me,{fallbackId:Me.id}):null,Ye=(Me==null?void 0:Me.id)||null,ot=o.useMemo(()=>qm(f,we),[f,we]),{hiddenTabs:et,hideTab:mt,toggleTab:Ve,showTab:it,showAllTabs:ft}=Gm(),{chatIdes:ht,conversations:ye,visibleConversations:Ue,visibleTabKeys:ze,resolveConversationBySessionId:Xe,resolveConversationByTarget:pt}=op({ides:ot,connectionStates:P,localUserMessages:ve,clearedTabs:ie,hiddenTabs:et});_u(ye),o.useEffect(()=>{Object.keys(we).length!==0&&re(be=>Ym(be,f))},[f,we]);const gt=o.useMemo(()=>tn(f),[f]),{notifications:vt,unreadCount:Ot,notificationStateBySessionId:Bt,markRead:Ct,markUnread:It,markTargetRead:q,deleteNotification:Ee}=Hp({conversations:ye,liveSessionInboxState:gt}),R=o.useRef(null),{containerRef:W,normalizedGroupAssignments:H,numGroups:F,isSplitMode:se,groupedConvs:Se,moveTabToGroup:Te,closeGroup:Ie,handleResizeStart:We,splitTabRelative:Ke}=Ip({groupAssignments:I,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:N,setGroupTabOrders:M,groupSizes:B,setGroupSizes:_,isMobile:S,visibleConversations:Ue,visibleTabKeys:ze}),Ae=o.useMemo(()=>{var _e,Le;if(!S){if(je){const me=ye.find(Fe=>Fe.tabKey===je);if(me)return me}return Ue[0]}const be=$[w];if(be){const me=ye.find(Fe=>Fe.tabKey===be);if(me)return me}return((_e=Se[w])==null?void 0:_e[0])||((Le=Se[0])==null?void 0:Le[0])},[je,S,$,w,ye,Se,Ue]);o.useEffect(()=>{if(S){R.current=null;return}if(!(Ae!=null&&Ae.sessionId)){R.current=null;return}const be=Hr(Ae,gt),_e=ui(Ae),Le=[Ae.tabKey,lr(Ae)||"",Ae.lastMessageHash||"",String(Ae.lastMessageAt||0),be.inboxBucket,be.unread?"1":"0"].join(":");if(R.current===Le)return;const me=()=>{if(document.visibilityState!=="visible"||R.current===Le)return;R.current=Le;const Fe=Math.max(Date.now(),is(Ae),be.lastUpdated||0);q({..._e},Fe),e(Ae.daemonId||Ae.routeId,"mark_session_seen",{sessionId:Ae.sessionId,seenAt:Fe}).catch(()=>{})};if(document.visibilityState==="visible"){const Fe=setTimeout(me,1500),st=()=>{document.visibilityState!=="visible"&&clearTimeout(Fe)};return document.addEventListener("visibilitychange",st),()=>{clearTimeout(Fe),document.removeEventListener("visibilitychange",st)}}else{const Fe=()=>{document.visibilityState==="visible"&&(setTimeout(me,800),document.removeEventListener("visibilitychange",Fe))};return document.addEventListener("visibilitychange",Fe),()=>{document.removeEventListener("visibilitychange",Fe)}}},[Ae,S,gt,q,e]);const{requestedDesktopTabKey:Z,requestedMobileTabKey:Re,consumeRequestedActiveTab:Oe}=ip({isMobile:S,urlActiveTab:c,resolveConversationBySessionId:Xe,setSearchParams:i}),{remoteDialogConv:De,remoteDialogIdeEntry:xt,remoteDialogActiveConv:D,setRemoteDialogActiveConv:X,openRemoteDialog:de,closeRemoteDialog:Pe}=jp({isMobile:S,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:Z,conversations:ye,ides:f,resolveConversationByTarget:pt}),fe=D||De||Ae,he=!!fe&&tt(fe)&&!Je(fe),Qe=o.useMemo(()=>{if(!fe||!he)return null;const be=fe.daemonId||fe.routeId||"",_e=$t(fe);return`${be}:${_e}`},[fe,he]),St=o.useMemo(()=>Ue,[Ue]),ct=S&&pe==="chat",qt=o.useMemo(()=>ye.filter(be=>et.has(be.tabKey)),[ye,et]),ts=o.useCallback(be=>{const _e=new URLSearchParams(a);_e.set("activeTab",be),i(_e,{replace:!0})},[a,i]),pr=o.useCallback(async(be,_e)=>on(e,be,_e),[e]),Ec=o.useCallback(async(be,_e)=>{if(!_e.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Le=await e(be,"workspace_add",{path:_e.trim()});return Le!=null&&Le.success?{ok:!0}:{ok:!1,error:(Le==null?void 0:Le.error)||"Could not save workspace"}}catch(Le){return{ok:!1,error:Le instanceof Error?Le.message:"Could not save workspace"}}},[e]),Kc=o.useCallback(async(be,_e,Le)=>{var me;try{const Fe={ideType:_e,enableCdp:!0};(me=Le==null?void 0:Le.workspacePath)!=null&&me.trim()&&(Fe.workspace=Le.workspacePath.trim());const st=await e(be,"launch_ide",Fe);return!(st!=null&&st.success)&&(st==null?void 0:st.success)!==void 0?{ok:!1,error:(st==null?void 0:st.error)||"Could not launch IDE"}:(Ce({machineId:be,kind:"ide",providerType:_e,workspacePath:(Le==null?void 0:Le.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Fe){return{ok:!1,error:Fe instanceof Error?Fe.message:"Could not launch IDE"}}},[e]),Bc=o.useCallback(async(be,_e,Le,me)=>{var st,Hs,vs;const Fe=Date.now();try{const At={cliType:Le};(st=me==null?void 0:me.workspacePath)!=null&&st.trim()?At.dir=me.workspacePath.trim():me!=null&&me.workspaceId&&(At.workspaceId=me.workspaceId),(Hs=me==null?void 0:me.resumeSessionId)!=null&&Hs.trim()&&(At.resumeSessionId=me.resumeSessionId.trim()),Array.isArray(me==null?void 0:me.cliArgs)&&me.cliArgs.length>0&&(At.cliArgs=me.cliArgs),(vs=me==null?void 0:me.initialModel)!=null&&vs.trim()&&(At.initialModel=me.initialModel.trim());const bt=await e(be,"launch_cli",At),_t=(bt==null?void 0:bt.result)||bt,Us=(_t==null?void 0:_t.sessionId)||(_t==null?void 0:_t.id);return bt!=null&&bt.success&&Us?(ts(Us),{ok:!0}):bt!=null&&bt.success?(Ce({machineId:be,kind:_e,providerType:Le,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:(bt==null?void 0:bt.error)||(_t==null?void 0:_t.error)||`Could not launch ${_e.toUpperCase()} session`}}catch(At){return ah(At)?(Ce({machineId:be,kind:_e,providerType:Le,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Fe}),{ok:!0}):{ok:!1,error:At instanceof Error?At.message:`Could not launch ${_e.toUpperCase()} session`}}},[ts,e]),Wc=o.useCallback(async(be,_e)=>{if(!be||!_e)return[];try{const Le=await e(be,"list_saved_sessions",{providerType:_e,kind:"cli",limit:30}),me=(Le==null?void 0:Le.result)??Le;return Array.isArray(me==null?void 0:me.sessions)?me.sessions:[]}catch(Le){return console.error("List saved sessions failed",Le),[]}},[e]);o.useEffect(()=>{if(!ge)return;const be=Eo(ge.workspacePath),_e=f.find(me=>{var At,bt,_t,Us;if(!me||me.type==="adhdev-daemon"||nh(me.daemonId||me.id)!==ge.machineId||(ar(me)?"cli":Is(me)?"acp":"ide")!==ge.kind||String(me.agentType||me.type||"")!==ge.providerType)return!1;if(ge.resumeSessionId)return String(me.providerSessionId||"")===ge.resumeSessionId;if(be){const un=Eo(me.workspace||me.runtimeWorkspaceLabel);return un?un===be:!1}return Number(me.lastUpdated||me._lastUpdate||me.timestamp||((Us=(_t=(bt=(At=me.activeChat)==null?void 0:At.messages)==null?void 0:bt.at)==null?void 0:_t.call(bt,-1))==null?void 0:Us.timestamp)||0)>=ge.startedAt-5e3});if(!_e)return;const Le=Mi({entrySessionId:_e.sessionId,entryInstanceId:_e.instanceId,entryRouteId:_e.id,conversations:ye});Le&&(Ce(null),ts(Le))},[ye,ts,f,ge]),o.useEffect(()=>{if(!ge)return;const be=window.setTimeout(()=>{Ce(_e=>!_e||_e.startedAt!==ge.startedAt?_e:null)},45e3);return()=>window.clearTimeout(be)},[ge]),Xm({visibleConversations:Ue,clearedTabs:ie,setClearedTabs:ne,setActionLogs:z}),cp({ides:f,sendDaemonCommand:e,setToasts:L,setLocalUserMessages:ee,resolveConversationByTarget:pt});const{isRefreshingHistory:Oc,handleRefreshHistory:Hc}=go({sendDaemonCommand:e,activeConv:Ae,chats:(Ba=f.find(be=>be.id===(Ae==null?void 0:Ae.routeId)))==null?void 0:Ba.chats,updateRouteChats:k,setToasts:L,setLocalUserMessages:ee,setClearedTabs:ne}),{isCreatingChat:Uc,isRefreshingHistory:Fc,handleSwitchSession:zc,handleNewChat:Vc,handleRefreshHistory:Gc}=go({sendDaemonCommand:e,activeConv:fe,chats:(Wa=f.find(be=>be.id===(fe==null?void 0:fe.routeId)))==null?void 0:Wa.chats,updateRouteChats:k,setToasts:L,setLocalUserMessages:ee,setClearedTabs:ne}),dn=o.useCallback(async()=>{if(!(!fe||!he||te)){ue(!0);try{const be=fe.daemonId||fe.routeId,_e=$t(fe),Le=await e(be,"list_saved_sessions",{agentType:_e,providerType:_e,kind:"cli",limit:50}),me=(Le==null?void 0:Le.result)??Le;Q(Array.isArray(me==null?void 0:me.sessions)?me.sessions:[])}catch(be){console.error("Refresh saved sessions failed",be),Q([])}finally{ue(!1)}}},[fe,te,he,e]);o.useEffect(()=>{if(!A){J.current=null;return}if(!he){J.current=null,Q([]),ue(!1);return}!Qe||te||J.current!==Qe&&(J.current=Qe,dn())},[dn,A,te,he,Qe]);const qc=o.useCallback(async be=>{if(!fe||!he||!be.providerSessionId||!be.workspace)return;const _e=fe.daemonId||fe.routeId,Le=$t(fe);try{le(be.providerSessionId);const me=await e(_e,"launch_cli",{cliType:Le,dir:be.workspace,resumeSessionId:be.providerSessionId,initialModel:bi(be.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Fe=(me==null?void 0:me.result)??me,st=typeof(Fe==null?void 0:Fe.sessionId)=="string"?Fe.sessionId:typeof(Fe==null?void 0:Fe.id)=="string"?Fe.id:"";st&&i(Hs=>{const vs=new URLSearchParams(Hs);return vs.set("activeTab",st),vs},{replace:!0}),K(!1)}catch(me){console.error("Resume saved session failed",me)}finally{le(null)}},[fe,he,e,i]);wp({urlActiveTab:S&&!ct?c:null,conversations:ye,resolveConversationBySessionId:Xe,normalizedGroupAssignments:H,hasHydratedStoredLayout:S&&!ct?O:!0,hydrateStoredLayout:S&&!ct?G:()=>{},setGroupActiveTabIds:N,setFocusedGroup:x,setSearchParams:i,historyModalOpen:A,activeConv:Ae,isRefreshingHistory:Oc,ides:f,handleRefreshHistory:Hc});const _a=o.useCallback(async(be,_e)=>{const Le=_e||ce||Ae;if(!Le||!tt(Le)&&!Je(Le))return;const me=$t(Le),Fe=Le.routeId||Le.daemonId||"";try{await e(Fe,"stop_cli",{cliType:me,targetSessionId:Le.sessionId,mode:be})}catch(st){console.error("Stop CLI failed:",st)}},[Ae,ce,e]),Yc=o.useCallback(async be=>{const _e=be||Ae;!_e||!tt(_e)&&!Je(_e)||(Y(_e),U(!0))},[Ae]),Xc=o.useMemo(()=>!Ae||!tt(Ae)||Je(Ae)?null:Ps(Ae),[Ae]),Qc=o.useCallback(async be=>{if(!Ae||!tt(Ae)||Je(Ae))return;const _e=Ps(Ae);if(_e===be)return;const Le=Ae.sessionId;Le&&re(me=>({...me,[Le]:be}));try{await e(es(Ae)||Ae.routeId,"set_cli_view_mode",{targetSessionId:Ae.sessionId,cliType:$t(Ae),mode:be})}catch(me){Le&&re(Fe=>{const st={...Fe};return _e===lc(f,Le)?delete st[Le]:st[Le]=_e,st}),oh(me)?console.warn("Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[Ae,f,e]),{versionMismatchDaemons:Jc,hasRequiredVersionDaemons:Ra,appVersion:Zc,versionBannerDismissed:el,setVersionBannerDismissed:tl,upgradingDaemons:sl,handleBannerUpgrade:rl}=Ap({ides:f,sendDaemonCommand:e}),Pa=o.useCallback(be=>{xe(be.tabKey),i(_e=>{const Le=new URLSearchParams(_e),me=au(be);return me?Le.set("activeTab",me):Le.delete("activeTab"),Le},{replace:!0})},[i]),Da=o.useCallback(be=>{it(be.tabKey),Pa(be)},[Pa,it]),nl=o.useCallback(be=>{mt(be.tabKey)},[mt]);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(Fu,{wsStatus:h,showReconnected:g}),t.jsx(zu,{terminalBackend:Ze,isStandalone:$e,machineLabel:Ge,machineKey:Ye}),(!el||Ra)&&t.jsx(rh,{daemons:Jc,targetVersion:Zc,required:Ra,upgradingDaemons:sl,onUpgrade:rl,onDismiss:()=>tl(!0)}),t.jsx(Xf,{showMobileChatMode:ct,isMobile:S,activeConv:Ae,chatIdes:ht,wsStatus:h,isConnected:C,onOpenHistory:be=>{be&&X(be),K(!0)},onOpenRemote:de,onStopCli:Yc,activeCliViewMode:Xc,onSetActiveCliViewMode:Qc,mobileChatConversations:St,ides:f,actionLogs:ae,sendDaemonCommand:e,setLocalUserMessages:ee,setActionLogs:z,isStandalone:$e,initialDataLoaded:b,userName:m.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Oe,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:W,isSplitMode:se,numGroups:F,groupSizes:B,groupedConvs:Se,clearedTabs:ie,focusedGroup:w,setFocusedGroup:x,moveTabToGroup:Te,splitTabRelative:Ke,closeGroup:Ie,handleResizeStart:We,groupActiveTabIds:$,setGroupActiveTabIds:N,groupTabOrders:T,setGroupTabOrders:M,toggleHiddenTab:Ve,visibleConversations:Ue,hiddenConversations:qt,requestedDesktopTabKey:Z,onRequestedDesktopTabConsumed:Oe,onDesktopActiveTabChange:xe,onHideConversation:nl,onShowHiddenConversation:Da,onShowAllHiddenConversations:ft,scrollToBottomRequest:E,machineEntries:He,onBrowseMachineDirectory:pr,onSaveMachineWorkspace:Ec,onLaunchMachineIde:Kc,onLaunchMachineProvider:Bc,onListMachineSavedSessions:Wc,notifications:vt,notificationUnreadCount:Ot,notificationStateBySessionId:Bt,onMarkNotificationRead:Ct,onMarkNotificationUnread:It,onDeleteNotification:Ee,onMarkNotificationTargetRead:q}),t.jsx("style",{children:`
|
|
60
60
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(sh,{historyModalOpen:A,historyTargetConv:fe,ides:f,isHistoryCreatingChat:Uc,isHistoryRefreshingHistory:he?!1:Fc,savedHistorySessions:oe,isSavedHistoryLoading:te,isResumingSavedHistorySessionId:Ne,onCloseHistory:()=>K(!1),onNewHistoryChat:Vc,onSwitchHistorySession:zc,onRefreshHistory:he?dn:Gc,onResumeSavedHistorySession:qc,remoteDialogConv:De,remoteDialogIdeEntry:xt,connectionStates:P,actionLogs:ae,localUserMessages:ve,sendDaemonCommand:e,setLocalUserMessages:ee,setActionLogs:z,isStandalone:$e,userName:m.userName,onOpenRemoteHistory:be=>{be&&X(be),K(!0)},onRemoteConversationChange:X,onCloseRemoteDialog:Pe,cliStopDialogOpen:V,cliStopTargetConv:ce,onCancelCliStop:()=>{U(!1),Y(null)},onStopCliNow:async()=>{U(!1),await _a("hard",ce),Y(null)},onSaveCliAndStop:async()=>{U(!1),await _a("save",ce),Y(null)},toasts:v,onDismissToast:be=>
|
|
62
|
-
This will terminate the process.`))try{const U=await r(e,"stop_cli",{cliType:A,dir:K,targetSessionId:V});U!=null&&U.success?
|
|
63
|
-
This will disconnect CDP and optionally kill the process.`))try{const K=await r(A.daemonId,"stop_ide",{ideType:A.type,killProcess:!0});K!=null&&K.success?
|
|
64
|
-
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(k(x=>[...x,"✅ Agent started. Monitoring progress..."]),
|
|
65
|
-
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.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:w=>w.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:ph.map(w=>t.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.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:C,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:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Bo.map(w=>t.jsxs("button",{onClick:()=>h(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(w)?"☑ ":"☐ ",w]},w))})]}),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:w=>f(w.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:[y.map((w,x)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:g})]}),T&&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:T})]})]}),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:I,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:j,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"),k([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function hh({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var b;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((b=i[0])==null?void 0:b.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[y,k]=o.useState(!1),[T,d]=o.useState(""),[g,v]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===C(u))&&f(C(j))},C=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),P=async()=>{if(!(!u||!m||!c)){k(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(v(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}k(!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:I=>I.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:g?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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.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:I=>h(I.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:I=>f(I.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"})]}),T&&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:T})]})}),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:g?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:P,disabled:!u||!m||y,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||y?.4:1},children:y?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function xh({machineId:e,providers:s,sendDaemonCommand:r}){var N;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,y]=o.useState(null),[k,T]=o.useState(!1),[d,g]=o.useState(null),[v,h]=o.useState("normal"),[C,P]=o.useState(""),[b,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),M=Ko(L);M&&(g(M),h(M.sourceMode),P(M.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),M=dh(L);if(M){const B=uh(M,s);B.sort((_,S)=>_.category.localeCompare(S.category)||_.displayName.localeCompare(S.displayName)),a(B)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),d||j()},[]);const x=async(L,M,B)=>{u(`${L}.${M}`),a(_=>_.map(S=>S.type===L?{...S,values:{...S.values,[M]:B}}:S));try{const _=await r(e,"set_provider_setting",{providerType:L,key:M,value:B});_!=null&&_.success||w()}catch{w()}u(null)},$=async()=>{I(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:mh(C)}),M=Ko(L);M?(g(M),h(M.sourceMode),P(M.explicitProviderDir||"")):await j(),await w()}catch{await j()}I(!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(L=>t.jsx("button",{onClick:()=>m(L),className:`machine-btn text-[10px] px-2 py-0.5 ${p===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>T(!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:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:v,onChange:L=>h(L.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:C,onChange:L=>P(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:b,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:b?"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:"})," ",((N=d==null?void 0:d.providerRoots)==null?void 0:N.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(L=>L.category===p).length>1&&(()=>{const L=n.filter(S=>S.category===p),M=new Map;for(const S of L)for(const O of S.schema){if(O.type!=="boolean")continue;const G=M.get(O.key),A=!!(S.values[O.key]??O.default);G?(G.onCount+=A?1:0,G.total+=1):M.set(O.key,{label:O.label||O.key,onCount:A?1:0,total:1})}const B=[...M.entries()].filter(([,S])=>S.total===L.length);if(B.length===0)return null;const _=async(S,O)=>{for(const G of L)await x(G.type,S,O)};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 (",L.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:B.map(([S,O])=>{const G=O.onCount===O.total,A=O.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:O.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",O.onCount,"/",O.total,")"]}),t.jsx("button",{onClick:()=>void _(S,!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 _(S,!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"})]},S)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(L=>p==="all"||L.category===p).map(L=>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:L.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),L.category==="ide"&&t.jsx("button",{onClick:()=>y(s.find(M=>M.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.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:L.schema.map(M=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[M.label||M.key,l===`${L.type}.${M.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),M.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:M.description})]}),t.jsx("div",{className:"shrink-0",children:M.type==="boolean"?t.jsx("button",{onClick:()=>x(L.type,M.key,!(L.values[M.key]??M.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[M.key]??M.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:L.values[M.key]??M.default?21:3}})}):M.type==="number"?t.jsx("input",{type:"number",value:Number(L.values[M.key]??M.default??0)||0,min:M.min,max:M.max,onChange:B=>{const _=parseInt(B.target.value)||0;M.min!==void 0&&_<M.min||M.max!==void 0&&_>M.max||x(L.type,M.key,_)},className:"machine-input w-20 text-center text-[11px]"}):M.type==="select"&&M.options?t.jsx("select",{value:String(L.values[M.key]??M.default??""),onChange:B=>x(L.type,M.key,B.target.value),className:"machine-input text-[11px]",children:M.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(L.values[M.key]??M.default??""),onBlur:B=>x(L.type,M.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},M.key))})]},L.type))}),f&&t.jsx(fh,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>y(null)}),k&&t.jsx(hh,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>T(!1),onCreated:()=>{T(!1),w()}})]})}const bh=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function gh({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function yh(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Wo(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 vh({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),[y,k]=o.useState(!0),[T,d]=o.useState("debug"),[g,v]=o.useState("all"),h=o.useRef(null),C=o.useRef(!1),P=yh(a,g);return o.useEffect(()=>{if(!e||!y)return;const b=async()=>{try{const[j,w]=await Promise.all([s(e,"get_logs",{count:200,minLevel:T,since:u}),s(e,"get_debug_trace",gh({count:120,since:m,category:g}))]),x=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(L=>[...L,...x.logs.map(B=>({timestamp:B.ts,level:B.level,message:`[${B.category}] ${B.message}`}))].slice(-300));const N=Math.max(...x.logs.map(L=>L.ts));p(N)}const $=(w==null?void 0:w.result)||w;if(w!=null&&w.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const N=$.trace.reduce((L,M)=>Math.max(L,Number(M.ts||0)),m);N>m&&f(N)}}catch{}l(Ts.list({limit:120}))};b();const I=setInterval(b,3e3);return()=>clearInterval(I)},[e,y,u,m,T,g,s]),o.useEffect(()=>{if(y&&(r.length>0||a.length>0||c.length>0)){const b=C.current?"smooth":"instant";setTimeout(()=>{var I;(I=h.current)==null||I.scrollIntoView({behavior:b}),C.current=!0},50)}},[r.length,a.length,c.length,y]),o.useEffect(()=>{i([]),f(0)},[g]),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(b=>t.jsx("button",{onClick:()=>{d(b),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===b?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:b.toUpperCase()},b))]}),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=",P.length," web=",c.length]}),t.jsx("button",{onClick:()=>k(!y),className:`machine-btn ${y?"text-green-500 border-green-500/30":""}`,children:y?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),Ts.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((b,I)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:b.level==="error"?"#ef4444":b.level==="warn"?"var(--status-warning)":b.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(b.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:b.level==="error"?"ERR":b.level==="warn"?"WRN":b.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:b.message})]},`log-${I}`))]}),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",g==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:bh.map(b=>t.jsx("button",{onClick:()=>v(b.value),className:`machine-btn text-[10px] px-2 py-0.5 ${g===b.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:b.label},b.value))})]}),P.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:g==="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."}),P.map(b=>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(b.ts).toLocaleTimeString()}),t.jsx("span",{children:b.level.toUpperCase()}),t.jsxs("span",{children:[b.category,".",b.stage]}),b.interactionId&&t.jsxs("span",{children:["ix=",b.interactionId]})]}),t.jsx("div",{children:Wo(b.payload)})]},b.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(b=>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(b.ts).toLocaleTimeString()}),t.jsx("span",{children:b.kind}),b.topic&&t.jsxs("span",{children:["topic=",b.topic]}),b.interactionId&&t.jsxs("span",{children:["ix=",b.interactionId]})]}),t.jsx("div",{children:Wo(b.payload)})]},b.id))]})]}),t.jsx("div",{ref:h})]})}function Pn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Dn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Oo(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 wh(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function jh(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 kh(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 Sh({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=oc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,y=p.applyDiagnostics,k=o.useMemo(()=>Wf({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),T=o.useMemo(()=>new Map(s.map(N=>[N.sessionId||N.id,N])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const N=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),L=Pn(N);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");y(L.diagnostics||L.result||null),a("")}catch(N){const L=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";a(L)}finally{u(!1)}}},[y,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const g=o.useCallback(async(N,L)=>{const M=`${N}:${L.sessionId}`;if(!(N==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
|
|
66
|
-
This will terminate the hosted runtime.`))){c(M);try{const B=await r(e,N,{sessionId:
|
|
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 L=await r(e,"session_host_prune_duplicate_sessions",{}),M=Pn(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const B=M.result||{},_=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,S=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;lt.showToast(`Pruned ${_} duplicate runtime(s) across ${S} group(s)`,"success"),await d()}catch(L){const M=L instanceof Error?L.message:"Duplicate prune failed";lt.showToast(M,"warning"),a(M)}finally{c(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((N,L)=>(L.lastActivityAt||0)-(N.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=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)||[]}:Rc(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),P=C.liveRuntimes,b=C.recoverySnapshots,I=C.inactiveRecords,j=o.useMemo(()=>kh(P),[P]),w=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(N=>N.level==="warn"||N.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(N,L)=>{var V;const M=i===`session_host_resume_session:${N.sessionId}`,B=i===`session_host_restart_session:${N.sessionId}`,_=i===`session_host_stop_session:${N.sessionId}`,S=La(N.meta),O=T.get(N.sessionId),G=N.attachedClients.length===1?"1 client":`${N.attachedClients.length} clients`,A=L==="recovery"?"Recover":"Resume",K=Pc(L);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:N.displayName||(O==null?void 0:O.cliName)||N.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${jh(N.lifecycle)}`,children:N.lifecycle}),S&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:N.workspaceLabel||(O==null?void 0:O.runtimeWorkspaceLabel)||N.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:N.runtimeKey}),N.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",N.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((V=N.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:wh(N.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(na,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Oo(N.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",K]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_resume_session",N)},children:M?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",N)},children:B?"Restarting…":"Restart"}),L==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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:()=>{g("session_host_stop_session",N)},children:_?"Stopping…":"Stop"})]})]})},N.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(zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ju()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Ws,{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(xs,{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:b.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:Oo(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Dn(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(xs,{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:[Dn(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(Jr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ms("live")}),P.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:P.map(N=>$(N,"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(zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ms("recovery")}),b.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:b.map(N=>$(N,"recovery"))})]}),I.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:Ms("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(N=>$(N,"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"}),w.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:w.map(N=>{var M;const L=h.find(B=>B.sessionId===N.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:(L==null?void 0:L.displayName)||((M=T.get(N.sessionId))==null?void 0:M.cliName)||N.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Dn(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.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 Nh({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 $n({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 En({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 Ch({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=er(e,"0.8.74");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($n,{icon:t.jsx(Vt,{size:13}),children:"Current Chats"}),t.jsx(En,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const y=Fn(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:dt(f)}),y>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:en(y)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:gs(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(ni,{size:13}),children:"Recent Launches"}),t.jsx(En,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:y,updatedLabel:k}=gc(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}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:y})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(xs,{size:13}),children:"Daemon Update"}),t.jsx(En,{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(Ws,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ih(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Ah={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 Tr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mh(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 Kn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Bs(),{handleLaunchIde:f,handleStopCli:y,handleRestartIde:k,handleStopIde:T,handleDetectIdes:d,launchingIde:g,launchingAgentType:v,addLog:h}=c,[C,P]=o.useState(null),b=o.useCallback(D=>{D&&m(Jt(D))},[m]),I=Ah[e],j=e==="ide",w=e==="acp",x=o.useMemo(()=>n.filter(D=>D.category===e&&(e==="ide"||D.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(D=>[D.type,D.displayName||D.type])),[x]),[N,L]=o.useState(""),[M,B]=o.useState(""),[_,S]=o.useState([]),[O,G]=o.useState(""),[A,K]=o.useState(""),[V,U]=o.useState([]),[ce,Y]=o.useState(!1),[oe,Q]=o.useState(!1),[te,ue]=o.useState(""),[Ne,le]=o.useState(!1),[pe,ae]=o.useState(()=>yt()),[z,ve]=o.useState(null),[ee,we]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[re,ie]=o.useState(p||""),[ne,je]=o.useState([]),[xe,E]=o.useState(!1),[ke,ge]=o.useState(""),[Ce,J]=o.useState([]),[Me,He]=o.useState(!1),[$e,Ze]=o.useState(""),Ge=o.useRef(null),[Ye,ot]=o.useState(null),et=o.useRef("__home__"),[mt,Ve]=o.useState("__home__"),[it,ft]=o.useState(!1),ht=o.useRef(0),ye=ne.filter(D=>!a.some(X=>X.type===D&&jt(X.status)!=="stopped")),Ue=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ee&&we(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){we("__custom__"),ie(p);return}u&&(we(u),ie(""))},[u,p]),o.useEffect(()=>{j||N&&(x.some(D=>D.type===N)||(L(""),K("")))},[x,j,N]);const ze=(()=>{if(ee==="__custom__")return re.trim();if(!ee)return"";const D=(s.workspaces||[]).find(X=>X.id===ee);return(D==null?void 0:D.path)||""})(),Xe=o.useCallback(D=>{const X=Ue.current[D];X&&(clearTimeout(X),delete Ue.current[D]),je(de=>de.includes(D)?de.filter(Pe=>Pe!==D):de)},[]),pt=o.useRef(new Set),gt=o.useCallback(async D=>{if(l){He(!0),Ze("");try{const X=await on(l,r,D);ge(X.path),ie(X.path),J(X.directories)}catch(X){Ze(X instanceof Error?X.message:"Could not load folder")}finally{He(!1)}}},[r,l]),vt=o.useCallback(()=>{if(!l)return;we("__custom__"),E(!0);const D=a.map(de=>de.workspace),X=an(s.platform,nn(re.trim(),ze,p,D,s.defaultWorkspacePath,(s.workspaces||[]).map(de=>de.path)));gt(X)},[re,p,gt,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,l]),Ot=o.useCallback(D=>{const X=String(D.workspace||"").trim();if(!X)return;const de=(s.workspaces||[]).find(Pe=>Tr(Pe.path)===Tr(X));if(de){we(de.id),ie("");return}we("__custom__"),ie(X)},[s.workspaces]),Bt=o.useCallback(D=>{const X=String(D.workspace||"").trim();if(!X)return{workspaceId:null,workspacePath:"",useHome:!0};const de=(s.workspaces||[]).find(Pe=>Tr(Pe.path)===Tr(X));return de?{workspaceId:de.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:X,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async D=>{if(!l||!D||e!=="cli"){U([]),Y(!1),Q(!1),ue("");return}const X=ht.current+1;ht.current=X,Y(!0),ue("");try{const de=await l(r,"list_saved_sessions",{providerType:D,kind:"cli",limit:30});if(ht.current!==X)return;const Pe=(de==null?void 0:de.result)??de;U(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(de){if(ht.current!==X)return;U([]),ue(de instanceof Error?de.message:"Could not load saved sessions")}finally{ht.current===X&&(Y(!1),Q(!0))}},[e,r,l]),It=o.useMemo(()=>{if(e!=="cli"||!N)return null;const D=$.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:D,agentType:N,status:"idle",title:D,messages:[],ideType:N,workspaceName:ze,displayPrimary:D,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,$,ze,A,N]),q=o.useCallback(D=>{if(e==="ide"||!D){S([]);return}S(Lc(r,D))},[e,r]);o.useEffect(()=>{if(K(""),q(N),Q(!1),e!=="cli"||!N){U([]),ue(""),Y(!1);return}Ct(N)},[e,q,Ct,N]);const Ee=o.useMemo(()=>V.find(D=>D.providerSessionId===A)||null,[V,A]);o.useEffect(()=>{if(!A)return;const D=V.find(X=>X.providerSessionId===A);D!=null&&D.canResume||K("")},[V,A]);const R=o.useCallback((D,X)=>{Ge.current=X,et.current=D.selectedWorkspaceKey||"__home__",Ve(D.selectedWorkspaceKey||"__home__"),ot(D)},[]),W=o.useCallback(()=>{Ge.current&&(ft(!0),Ge.current().finally(()=>{Ge.current=null,ft(!1),ot(null)}))},[]),H=o.useCallback(D=>{if(!D)return;je(de=>de.includes(D)?de:[...de,D]);const X=Ue.current[D];X&&clearTimeout(X),Ue.current[D]=setTimeout(()=>{je(de=>de.includes(D)?de.filter(Pe=>Pe!==D):de),delete Ue.current[D]},2e4)},[]);o.useEffect(()=>{for(const X of a)jt(X.status)!=="stopped"&&(ne.includes(X.type)&&!pt.current.has(X.type)&&(pt.current.add(X.type),h("info",`${$.get(X.type)||X.type} launched`,!0)),Xe(X.type));const D=new Set(a.filter(X=>jt(X.status)!=="stopped").map(X=>X.type));pt.current.forEach(X=>{!ne.includes(X)&&!D.has(X)&&pt.current.delete(X)})},[h,Xe,a,ne,$]),o.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[F,se]=o.useState({}),[Se,Te]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const X=await l(r,"get_ide_extensions",{}),de=(X==null?void 0:X.result)||X;de!=null&&de.success&&(de!=null&&de.ideExtensions)&&se(de.ideExtensions)}catch{}})()},[j,r,l]);const Ie=D=>j?at(D.type):e==="cli"?D.cliName:D.acpName,We=j?s.detectedIdes||[]:[],Ke=o.useCallback(async D=>{const X=(D==null?void 0:D.type)||N,de=(D==null?void 0:D.workspacePath)??ze;if(j){await f(X,de?{workspace:de}:void 0)&&H(X);return}const Pe=await c.runLaunchCliCore({cliType:X,dir:D!=null&&D.workspaceId?void 0:de||void 0,workspaceId:(D==null?void 0:D.workspaceId)||void 0,useHome:(D==null?void 0:D.useHome)||!(D!=null&&D.workspaceId)&&!de,argsStr:(D==null?void 0:D.argsStr)??(M||void 0),model:(D==null?void 0:D.model)??(w&&O||void 0),resumeSessionId:(D==null?void 0:D.resumeSessionId)||!w&&e==="cli"&&X===N&&A||void 0});if(Pe.success||Pe.pending){const fe=(D==null?void 0:D.argsStr)??M;!j&&(fe!=null&&fe.trim())&&(_c(r,X,fe),q(X)),H(X),Pe.success&&Pe.sessionId&&b(Pe.sessionId)}},[c,f,w,j,M,O,q,H,r,b,ze,A,N]),Ae=Ui(j?"ide":w?"acp":"cli",!j&&!w&&!!A),Z=Fi(j?"ide":w?"acp":"cli",!j&&!w&&!!A),Re=()=>{var fe;const D=j?at(N):$.get(N)||N,X=!j&&!w&&!!A,{options:de,selectedKey:Pe}=fs({machine:s,currentWorkspaceId:ee&&ee!=="__custom__"?ee:null,currentWorkspacePath:ze});R({title:X?ya(D):ds("start-fresh",D),description:X?va():us("start-fresh"),confirmLabel:Ae,busyLabel:Z,workspaceOptions:de,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:I.label},{label:"Provider",value:D},...!j&&e==="cli"&&A?[{label:"Resume",value:((fe=V.find(he=>he.providerSessionId===A))==null?void 0:fe.title)||A}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...w&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const he=de.find(Qe=>Qe.key===et.current);he!=null&&he.workspaceId?(we(he.workspaceId),ie("")):he!=null&&he.workspacePath?(we("__custom__"),ie(he.workspacePath)):(we(""),ie("")),await Ke({workspaceId:(he==null?void 0:he.workspaceId)??null,workspacePath:(he==null?void 0:he.workspacePath)??"",useHome:!(he!=null&&he.workspaceId)&&!(he!=null&&he.workspacePath)})})},Oe=D=>{j?T(D):y(D.type,D.workspace,D.id)},De=o.useCallback(async(D,X,de=!1)=>{if(D.mode===X){de&&D.sessionId&&b(D.sessionId);return}if(!l||!D.sessionId){de&&D.sessionId&&b(D.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.type,mode:X}),de&&b(D.sessionId)}catch(Pe){Mh(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,b,l]),xt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ee,onChange:D=>{const X=D.target.value;if(we(X),X==="__custom__"&&l){vt();return}X!=="__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(D=>t.jsxs("option",{value:D.id,children:[D.id===s.defaultWorkspaceId?"⭐ ":"",sn(D.path,D.label)]},D.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…"})]})}),ee==="__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:vt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:re,onChange:D=>ie(D.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:ee==="__custom__"?ze?t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ze?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ee===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze})]}):"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 ${I.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 ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map(D=>{const X=a.find(Qe=>(Qe.type||"").toLowerCase()===(D.type||"").toLowerCase()&&jt(Qe.status)!=="stopped"),de=D.running||!!X,Pe=!!X&&X.cdpConnected,fe=ne.includes(D.type||D.id||""),he=N===(D.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&X){const Qe=X.sessionId;Qe?m(Jt(Qe),{state:{openRemoteForTabKey:Qe}}):m("/dashboard",{state:{openRemoteForTabKey:X.id}});return}fe||L(Qe=>Qe===(D.type||"")?"":D.type||"")},disabled:!!g||fe,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":he?"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:g&&g!==D.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(D.type)}),de&&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:D.name||at(D.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":fe?"text-orange-400":he?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":fe?"Starting...":he?"Configure":"Select"})]})]},D.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(Rl,{size:14})," Scan System"]})]}):x.length>0?x.map(D=>{const X=N===D.type,de=ne.includes(D.type),fe=!!a.find(he=>he.type===D.type&&jt(he.status)!=="stopped");return t.jsxs("button",{onClick:()=>L(he=>he===D.type?"":D.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"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:D.icon}),fe&&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:D.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${de?"text-orange-400":X?"text-accent-primary":"text-text-muted"}`,children:de?"Starting...":X?"Configure":"Select"})]})]},D.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."})]})}),N&&(j?We.find(D=>D.type===N):x.find(D=>D.type===N))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?at(N):$.get(N)||N})]}),xt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx($c,{busy:!!v||!!g||ne.includes(N),savedSessionsLoading:ce,savedSessionsError:te,selectedSession:Ee,onRefresh:()=>void Ct(N),onOpenHistory:()=>{N&&(le(!0),Dc({hasLoadedInitialResults:oe,isLoading:ce})&&Ct(N))},onClearSelection:()=>K("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:O,onChange:D=>G(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:M,onChange:D=>B(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),_.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(D=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B(D),title:D,children:D},D))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Re,disabled:!!v||!!g||ne.includes(N),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===N||g===N?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter(D=>!a.some(X=>X.type===D&&jt(X.status)!=="stopped")).length,")"]}),a.length===0&&ye.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 ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ye.map(D=>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(D)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?at(D):$.get(D)||D}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===D?"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:${D}`)),a.map(D=>{const X=j?D:null,de=!j&&!w?D:null,Pe=jt(D.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(D.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(D),(X==null?void 0:X.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",X.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:D.workspace||"—"}),(de==null?void 0:de.mode)&&t.jsx("span",{className:de.mode==="chat"?"text-violet-400":"text-text-secondary",children:de.mode==="chat"?"Chat view":"Terminal view"})]}),de&&(de.runtimeKey||de.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[de.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 ",de.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 fe;(fe=navigator.clipboard)==null||fe.writeText(`adhdev attach ${de.runtimeKey}`),P(de.runtimeKey||null),window.setTimeout(()=>{P(he=>he===de.runtimeKey?null:he)},1200)},children:C===de.runtimeKey?"Copied":"Copy"})]}),de.runtimeWriteOwner&&t.jsx("span",{style:{color:de.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:de.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ih(de.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}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const fe=D.sessionId;if(fe){m(Jt(fe),{state:{openRemoteForTabKey:fe}});return}m("/dashboard",{state:{openRemoteForTabKey:D.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(Tt,{size:13})}),t.jsx("button",{onClick:()=>{const fe=D.workspace||"",{options:he,selectedKey:Qe}=fs({machine:s,currentWorkspacePath:fe});R({title:ds("restart-ide",at(D.type)),description:us("restart-ide"),confirmLabel:Es("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:he,selectedWorkspaceKey:Qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(D.type)}]},async()=>{const St=he.find(qt=>qt.key===et.current),ct=(St==null?void 0:St.workspacePath)??"";if(ct&&ct!==fe){await Ke({type:D.type,workspacePath:ct});return}await k(D)})},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(Ws,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const fe=D.sessionId;fe&&b(fe)},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:!D.sessionId,children:t.jsx(Vt,{size:14})}),de&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[de.mode&&t.jsx(xa,{mode:de.mode,onChange:fe=>void De(de,fe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const fe=D.sessionId;fe&&b(fe)},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:!D.sessionId,children:de.mode==="chat"?t.jsx(Vt,{size:14}):t.jsx(Tt,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const fe=D.workspace||"",he=j?at(D.type):Ie(D),{options:Qe,selectedKey:St}=fs({machine:s,currentWorkspacePath:fe});R({title:ds("restart-stopped",he),description:us("restart-stopped"),confirmLabel:Es("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:Qe,selectedWorkspaceKey:St,details:[{label:"Mode",value:I.label},{label:"Provider",value:he}]},async()=>{const ct=Qe.find(qt=>qt.key===et.current);await Ke({type:D.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ne.includes(D.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:ne.includes(D.type)?"⏳":t.jsx(oa,{size:14})}):t.jsx("button",{onClick:()=>Oe(D),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(Nt,{size:14})})]})]}),X&&X.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:X.aiAgents.map(fe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${fi(fe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[fe.name," · ",jt(fe.status)]},fe.id))}),X&&(F[X.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[X.type]||[]).map(fe=>t.jsxs("button",{disabled:Se===`${X.type}.${fe.type}`,onClick:async()=>{const he=`${X.type}.${fe.type}`;Te(he);try{await l(r,"set_ide_extension",{ideType:X.type,extensionType:fe.type,enabled:!fe.enabled}),se(Qe=>({...Qe,[X.type]:(Qe[X.type]||[]).map(St=>St.type===fe.type?{...St,enabled:!St.enabled}:St)}))}catch(Qe){console.error("Extension toggle failed:",Qe)}finally{Te(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 ${fe.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 ${fe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),fe.name,t.jsx("span",{className:"text-[9px] font-normal",children:fe.enabled?"ON":"OFF"})]},fe.type))})]})]},D.id)})]}),xe&&l&&t.jsx(cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ke,directories:Ce,busy:Me,error:$e,confirmLabel:"Use this folder",onClose:()=>E(!1),onNavigate:D=>{gt(D)},onConfirm:D=>{ie(D),we("__custom__"),E(!1)}}),Ye&&t.jsx(Ma,{title:Ye.title,description:Ye.description,details:Ye.details,workspaceOptions:Ye.workspaceOptions,selectedWorkspaceKey:mt,onWorkspaceChange:D=>{et.current=D,Ve(D)},confirmLabel:Ye.confirmLabel,busyLabel:Ye.busyLabel,busy:it,onConfirm:W,onCancel:()=>{Ge.current=null,ot(null)}}),Ne&&It&&t.jsx(wa,{activeConv:It,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:V,isSavedSessionsLoading:ce,isResumingSavedSessionId:z,savedHistoryFilters:pe,onSavedHistoryFiltersChange:ae,onClose:()=>le(!1),onNewChat:()=>{K(""),le(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(N)},onResumeSavedSession:D=>{if(!D.canResume||z)return;const X=Bt(D);K(D.providerSessionId),Ot(D),ve(D.providerSessionId),le(!1),Ke({type:D.providerType,workspaceId:X.workspaceId,workspacePath:X.workspacePath,useHome:X.useHome,resumeSessionId:D.providerSessionId}).finally(()=>{ve(de=>de===D.providerSessionId?null:de)})}})]})}const Ho=[{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 Th({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[y,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const T=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:Ho.map(g=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===g.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(g.id),children:[t.jsx("span",{children:g.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===g.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T[g.id]})]},g.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Ho.find(g=>g.id===y))==null?void 0:d.helper})]}),y==="ide"&&t.jsx(Kn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),y==="cli"&&t.jsx(Kn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),y==="acp"&&t.jsx(Kn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Lh({onNicknameSynced:e}={}){var z,ve,ee,we,re,ie,ne,je,xe;const{id:s}=ul(),r=Bs(),n=sa(),{sendCommand:a}=Lt(),i=ur(),c=$i(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),m=l.some(E=>E.type==="adhdev-daemon"),[f,y]=o.useState("workspace"),[k,T]=o.useState("ide"),d=o.useRef(null),[g,v]=o.useState(null),h=o.useRef("__home__"),[C,P]=o.useState("__home__"),[b,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Um(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const w=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=ch({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>lt.onToast(ke=>{c.setToasts(Ce=>{if(Ce.some(He=>He.message===ke.message&&ke.timestamp-He.timestamp<3e3))return Ce;const Me={id:ke.id,message:ke.message,type:ke.type,timestamp:ke.timestamp,targetKey:ke.targetKey,actions:ke.actions};return[...Ce.slice(-4),Me]});const ge=ke.duration||5e3;setTimeout(()=>c.setToasts(Ce=>Ce.filter(J=>J.id!==ke.id)),ge)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],N={};for(const E of $)N[E.type]=E.icon;const L=E=>N[E]||"",M=p?{id:p.id,hostname:hi(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ve=p.machine)==null?void 0:ve.arch)||"",cpus:((ee=p.machine)==null?void 0:ee.cpus)||0,totalMem:((we=p.machine)==null?void 0:we.totalMem)||0,freeMem:(re=p.machine)==null?void 0:re.freeMem,availableMem:(ie=p.machine)==null?void 0:ie.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(je=p.machine)==null?void 0:je.uptime,release:((xe=p.machine)==null?void 0:xe.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,B=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!ar(E)&&!Is(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Cd(E.aiAgents||(E.agents||[]).map(ke=>({id:ke.name,name:ke.name,status:ke.status,version:ke.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),_=l.filter(E=>E.daemonId===s&&ar(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),S=l.filter(E=>E.daemonId===s&&Is(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),O=p?Mt(p,{fallbackId:s}):"",G="workspace",A=n.state,K=A==null?void 0:A.initialMachineTab,V=A==null?void 0:A.initialWorkspaceCategory,U=A==null?void 0:A.initialWorkspaceId,ce=A==null?void 0:A.initialWorkspacePath,Y=K==="ides"||K==="clis"||K==="acps"?"workspace":K||G,oe=K==="ides"?"ide":K==="clis"?"cli":K==="acps"?"acp":V,Q=[...B.map(E=>{var ke,ge,Ce,J,Me;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}}),..._.map(E=>{var ke,ge,Ce,J,Me;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}}),...S.map(E=>{var ke,ge,Ce,J,Me;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:bs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}})].sort((E,ke)=>(ke.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),te=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:bs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):Q,ue=o.useMemo(()=>{var ke;const E=((ke=c.connectionStates)==null?void 0:ke[s||""])||void 0;return l.filter(ge=>ge.daemonId===s&&ge.type!=="adhdev-daemon").flatMap(ge=>ja(ge,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,Ce)=>Fn(Ce)-Fn(ge))},[l,c.connectionStates,s]),Ne=o.useCallback(E=>{const ke=pa(E);ke&&r(Jt(ke))},[r]),le=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),v(null)}))},[]),pe=o.useCallback(E=>{if(!M)return;const{options:ke,selectedKey:ge}=fs({machine:M,currentWorkspacePath:E.workspace}),Ce=async()=>{T(E.kind),y("workspace")};d.current=async()=>{const J=ke.find($e=>$e.key===h.current),Me=(J==null?void 0:J.workspacePath)??null,He=(J==null?void 0:J.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,Me?{workspace:Me}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:He?void 0:Me||"",workspaceId:He||void 0,model:E.kind==="acp"&&bi(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Ce()},h.current=ge,P(ge),v({title:E.kind==="ide"?ds("restart-ide",E.label):E.providerSessionId?ya(E.label):ds("start-fresh",E.label),description:E.kind==="ide"?us("restart-ide"):E.providerSessionId?va():us("start-fresh"),confirmLabel:E.kind==="ide"?Es("restart-ide"):E.providerSessionId?zr(!0):Es("start-fresh"),busyLabel:E.kind==="ide"?Ks("restart-ide"):E.providerSessionId?ba(!0):Ks("start-fresh"),workspaceOptions:ke,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,M]);if(o.useEffect(()=>{y(Y)},[G,Y,s]),o.useEffect(()=>{oe&&T(oe)},[oe,s]),!M)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:w,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 ae=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:14})," Workspace"]}),count:B.length+_.length+S.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ll,{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:w,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:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.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(M.machineNickname||"")},title:"Click to set nickname",children:O}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ae.map(E=>t.jsxs("button",{onClick:()=>y(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.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(Ch,{machineEntry:p,providers:$,recentLaunches:te,currentConversations:ue,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:pe,onOpenConversation:Ne}),t.jsx(Th,{machine:M,machineId:s,providers:$,ideSessions:B,cliSessions:_,acpSessions:S,actions:x,getIcon:L,initialCategory:k,initialWorkspaceId:U,initialWorkspacePath:ce,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(xh,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(lh,{machineId:s,machine:M,ideSessions:B,cliSessions:_,acpSessions:S,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Sh,{machineId:s,cliSessions:_,sendDaemonCommand:a}),f==="logs"&&t.jsx(vh,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&M&&t.jsx(Nh,{machine:M,launchPick:x.launchPick,actions:x}),g&&t.jsx(Ma,{title:g.title,description:g.description,details:g.details,workspaceOptions:g.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:E=>{h.current=E,P(E)},confirmLabel:g.confirmLabel,busyLabel:g.busyLabel,busy:b,onConfirm:le,onCancel:()=>{d.current=null,v(null)}}),t.jsx(zi,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ke=>ke.filter(ge=>ge.id!==E)),onClickToast:E=>{E.targetKey&&r(Jt(E.targetKey))}}),t.jsx("style",{children:`
|
|
61
|
+
`}),t.jsx(sh,{historyModalOpen:A,historyTargetConv:fe,ides:f,isHistoryCreatingChat:Uc,isHistoryRefreshingHistory:he?!1:Fc,savedHistorySessions:oe,isSavedHistoryLoading:te,isResumingSavedHistorySessionId:Ne,onCloseHistory:()=>K(!1),onNewHistoryChat:Vc,onSwitchHistorySession:zc,onRefreshHistory:he?dn:Gc,onResumeSavedHistorySession:qc,remoteDialogConv:De,remoteDialogIdeEntry:xt,connectionStates:P,actionLogs:ae,localUserMessages:ve,sendDaemonCommand:e,setLocalUserMessages:ee,setActionLogs:z,isStandalone:$e,userName:m.userName,onOpenRemoteHistory:be=>{be&&X(be),K(!0)},onRemoteConversationChange:X,onCloseRemoteDialog:Pe,cliStopDialogOpen:V,cliStopTargetConv:ce,onCancelCliStop:()=>{U(!1),Y(null)},onStopCliNow:async()=>{U(!1),await _a("hard",ce),Y(null)},onSaveCliAndStop:async()=>{U(!1),await _a("save",ce),Y(null)},toasts:v,onDismissToast:be=>L(_e=>_e.filter(Le=>Le.id!==be)),onClickToast:be=>{if(be.targetKey){const _e=pt(be.targetKey);_e&&(x(H.get(_e.tabKey)??0),Da(_e),ke({tabKey:_e.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}})]})}function ch({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,b]=o.useState(!1),[k,L]=o.useState(null),[d,y]=o.useState(!1),[v,h]=o.useState(""),C=o.useRef(null),P=o.useCallback(A=>{C.current=A},[]),g=o.useCallback((A,K,V=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:A,message:K}]),setTimeout(()=>{var U;return(U=a.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),V&<.showToast(K,A==="error"||A==="warn"?"warning":"success")},[a]),I=o.useCallback(A=>{const K=A instanceof Error?A.message:String(A||"");return K.includes("P2P command timeout")||K.includes("P2P not connected")||K.includes("P2P not available")},[]),j=o.useCallback(async(A,K)=>{var V;if(!e||l)return!1;u(A),g("info",`Launching ${at(A)}${K!=null&&K.workspace?` in ${K.workspace}`:""}...`);try{const U={ideType:A,enableCdp:!0};(V=K==null?void 0:K.workspace)!=null&&V.trim()?U.workspace=K.workspace.trim():K!=null&&K.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const ce=await r(e,"launch_ide",U);return g(ce!=null&&ce.success?"info":"error",ce!=null&&ce.success?`${at(A)} launched`:`Failed: ${ce==null?void 0:ce.error}`,!0),!!(ce!=null&&ce.success)}catch(U){return g("error",`Launch error: ${U.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),w=o.useCallback(async A=>{if(!e)return{success:!1};const{cliType:K,dir:V,workspaceId:U,useDefaultWorkspace:ce,useHome:Y,argsStr:oe,model:Q,resumeSessionId:te}=A;if(!K)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const ue=oe?oe.split(/\s+/).filter(Boolean):void 0,Ne=(V==null?void 0:V.trim())||(U?"(saved id)":ce?"(default workspace)":Y?"(home)":"");g("info",`Launching ${K}${Ne?` in ${Ne}`:""}${Q?` (model: ${Q})`:""}...`),m(K);try{const le={cliType:K,cliArgs:ue,initialModel:Q||void 0};V!=null&&V.trim()?le.dir=V.trim():U?le.workspaceId=U:ce?le.useDefaultWorkspace=!0:Y&&(le.useHome=!0),te&&(le.resumeSessionId=te);const pe=await r(e,"launch_cli",le),ae=(pe==null?void 0:pe.result)||pe;return pe!=null&&pe.success?(g("info",`${K} launched`,!0),(ae==null?void 0:ae.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ae==null?void 0:ae.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ae==null?void 0:ae.sessionId}):(g("error",`Failed: ${(pe==null?void 0:pe.error)||(ae==null?void 0:ae.error)}`,!0),(pe==null?void 0:pe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&L({cliType:K,argsStr:oe,model:Q}),{success:!1,sessionId:ae==null?void 0:ae.sessionId})}catch(le){return I(le)?(g("warn",`${K} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${le.message}`,!0),{success:!1})}finally{m(null)}},[e,g,I,r]),x=o.useCallback(async(A,K,V,U)=>e?A?K.trim()?w({cliType:A,dir:K,argsStr:V,model:U}):(L({cliType:A,argsStr:V,model:U}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,w]),$=o.useCallback(async(A,K,V)=>{if(e&&window.confirm(`Stop ${A}?
|
|
62
|
+
This will terminate the process.`))try{const U=await r(e,"stop_cli",{cliType:A,dir:K,targetSessionId:V});U!=null&&U.success?g("info",`${A} stopped`,!0):g("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){g("error",`Stop failed: ${U.message}`,!0)}},[e,g,r]),N=o.useCallback(async A=>{try{await r(A.daemonId,"restart_ide",{ideType:A.type}),g("info",`${at(A.type)} restart initiated`,!0)}catch(K){g("error",`Restart failed: ${K.message}`,!0)}},[g,r]),T=o.useCallback(async A=>{if(window.confirm(`Stop ${at(A.type)}?
|
|
63
|
+
This will disconnect CDP and optionally kill the process.`))try{const K=await r(A.daemonId,"stop_ide",{ideType:A.type,killProcess:!0});K!=null&&K.success?g("info",`${at(A.type)} stopped`,!0):g("error",`Stop failed: ${(K==null?void 0:K.error)||"Unknown error"}`,!0)}catch(K){g("error",`Stop failed: ${K.message}`,!0)}},[g,r]),M=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]),B=o.useCallback(async A=>{if(!e||!A.trim())return!1;b(!0);try{const K=await r(e,"workspace_add",{path:A.trim()});return K!=null&&K.success?(g("info",`Workspace added: ${A.trim()}`),!0):(g("error",(K==null?void 0:K.error)||"workspace_add failed"),!1)}catch(K){return g("error",K.message),!1}finally{b(!1)}},[e,g,r]),_=o.useCallback(async A=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const K=await r(e,"workspace_remove",{id:A});K!=null&&K.success?g("info","Workspace removed",!0):g("error",(K==null?void 0:K.error)||"workspace_remove failed",!0)}catch(K){g("error",K.message,!0)}finally{b(!1)}}},[e,g,r]),S=o.useCallback(async A=>{var K;if(e){b(!0);try{const V=await r(e,"workspace_set_default",A===null?{clear:!0}:{id:A});if(V!=null&&V.success){g("info",A?"Default workspace updated":"Default workspace cleared",!0);const U=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";U&&((K=C.current)==null||K.call(C,U))}else g("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){g("error",V.message,!0)}finally{b(!1)}}},[e,g,r]),O=o.useCallback(async A=>{var V;if(!e||!A.trim())return;const K=A.trim();b(!0);try{const U=await r(e,"workspace_set_default",{path:K});U!=null&&U.success?(g("info","Default workspace set from history"),(V=C.current)==null||V.call(C,K)):g("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){g("error",U.message)}finally{b(!1)}},[e,g,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:v})}catch(A){g("warn",`Live nickname updated, but account sync failed: ${A.message}`)}g("info",`Nickname set to "${v||"(cleared)"}"`),y(!1)}catch(A){g("error",`Failed: ${A.message}`)}},[e,v,s,g,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:k,setLaunchPick:L,editingNickname:d,setEditingNickname:y,nicknameInput:v,setNicknameInput:h,addLog:g,handleLaunchIde:j,runLaunchCliCore:w,handleLaunchCli:x,handleStopCli:$,handleRestartIde:N,handleStopIde:T,handleDetectIdes:M,handleWorkspaceAdd:B,handleWorkspaceRemove:_,handleWorkspaceSetDefault:S,handleWorkspaceResumePath:O,handleSaveNickname:G,setOnDefaultWorkspaceChanged:P}}function lh({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var N;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,b]=o.useState(!1),[k,L]=o.useState(""),[d,y]=o.useState([]),[v,h]=o.useState(!1),[C,P]=o.useState(""),g=o.useCallback(async T=>{h(!0),P("");try{const M=await on(c,e,T);L(M.path),y(M.directories)}catch(M){P(M instanceof Error?M.message:"Could not load folder")}finally{h(!1)}},[e,c]),I=o.useCallback(()=>{b(!0);const T=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...a.map(B=>B.workspace)],M=an(s.platform,nn(T,s.defaultWorkspacePath,(s.workspaces||[]).map(B=>B.path)));g(M)},[a,n,r,g,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,x=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,$=((N=s.loadavg)==null?void 0:N[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(br,{icon:t.jsx(ni,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?yd(s.uptime):"Waiting…"}),t.jsx(br,{icon:t.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(br,{icon:t.jsx(Jr,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(br,{icon:t.jsx(Kl,{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(Xa,{value:j?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Xa,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:j?`${hn(s.totalMem-w)} / ${hn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${hn(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(Ls,{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:T=>void m(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.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:I,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(T=>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:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:sn(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(T.id),children:"Remove"})]},T.id))})]}),f&&t.jsx(cn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:d,busy:v,error:C,confirmLabel:"Add workspace",onClose:()=>b(!1),onNavigate:T=>{g(T)},onConfirm:T=>{(async()=>{if(!T)return;await u(T)&&b(!1)})()}})]})}function dh(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 uh(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 Rn(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 Ko(e){if(!e||typeof e!="object")return null;if(Rn(e))return e;const s=e,r=s.result;return Rn(r)?r:Rn(s.sourceConfig)?s.sourceConfig:null}function mh(e){const s=e.trim();return s||null}const Bo=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],ph=[{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 fh({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(""),[b,k]=o.useState([]),[L,d]=o.useState(""),y=o.useRef(null),v=o.useRef(null),h=w=>{p(x=>x.includes(w)?x.filter($=>$!==w):[...x,w])},C=()=>p([...Bo]),P=()=>p([]);o.useEffect(()=>{var w;(w=y.current)==null||w.scrollIntoView({behavior:"smooth"})},[b]),o.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const g=o.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),k(x=>[...x,`
|
|
64
|
+
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(k(x=>[...x,"✅ Agent started. Monitoring progress..."]),g()):(i("error"),d((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),d((w==null?void 0:w.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(w=>[...w,`
|
|
65
|
+
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.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:w=>w.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:ph.map(w=>t.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.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:C,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:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Bo.map(w=>t.jsxs("button",{onClick:()=>h(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(w)?"☑ ":"☐ ",w]},w))})]}),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:w=>f(w.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:[b.map((w,x)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:y})]}),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:I,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:j,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"),k([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function hh({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((g=i[0])==null?void 0:g.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[b,k]=o.useState(!1),[L,d]=o.useState(""),[y,v]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===C(u))&&f(C(j))},C=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),P=async()=>{if(!(!u||!m||!c)){k(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(v(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}k(!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:I=>I.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:y?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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.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:I=>h(I.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:I=>f(I.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:y?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:P,disabled:!u||!m||b,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||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function xh({machineId:e,providers:s,sendDaemonCommand:r}){var N;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,b]=o.useState(null),[k,L]=o.useState(!1),[d,y]=o.useState(null),[v,h]=o.useState("normal"),[C,P]=o.useState(""),[g,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const T=await r(e,"get_provider_source_config",{}),M=Ko(T);M&&(y(M),h(M.sourceMode),P(M.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const T=await r(e,"get_provider_settings",{}),M=dh(T);if(M){const B=uh(M,s);B.sort((_,S)=>_.category.localeCompare(S.category)||_.displayName.localeCompare(S.displayName)),a(B)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),d||j()},[]);const x=async(T,M,B)=>{u(`${T}.${M}`),a(_=>_.map(S=>S.type===T?{...S,values:{...S.values,[M]:B}}:S));try{const _=await r(e,"set_provider_setting",{providerType:T,key:M,value:B});_!=null&&_.success||w()}catch{w()}u(null)},$=async()=>{I(!0);try{const T=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:mh(C)}),M=Ko(T);M?(y(M),h(M.sourceMode),P(M.explicitProviderDir||"")):await j(),await w()}catch{await j()}I(!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(T=>t.jsx("button",{onClick:()=>m(T),className:`machine-btn text-[10px] px-2 py-0.5 ${p===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T))]}),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:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:v,onChange:T=>h(T.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:C,onChange:T=>P(T.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),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:"})," ",((N=d==null?void 0:d.providerRoots)==null?void 0:N.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(T=>T.category===p).length>1&&(()=>{const T=n.filter(S=>S.category===p),M=new Map;for(const S of T)for(const O of S.schema){if(O.type!=="boolean")continue;const G=M.get(O.key),A=!!(S.values[O.key]??O.default);G?(G.onCount+=A?1:0,G.total+=1):M.set(O.key,{label:O.label||O.key,onCount:A?1:0,total:1})}const B=[...M.entries()].filter(([,S])=>S.total===T.length);if(B.length===0)return null;const _=async(S,O)=>{for(const G of T)await x(G.type,S,O)};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 (",T.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:B.map(([S,O])=>{const G=O.onCount===O.total,A=O.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:O.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",O.onCount,"/",O.total,")"]}),t.jsx("button",{onClick:()=>void _(S,!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 _(S,!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"})]},S)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(T=>p==="all"||T.category===p).map(T=>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:T.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:T.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:T.category==="acp"?"rgba(139,92,246,0.08)":T.category==="cli"?"rgba(59,130,246,0.08)":T.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:T.category==="acp"?"#a78bfa":T.category==="cli"?"#60a5fa":T.category==="ide"?"#86efac":"var(--status-warning)"},children:T.category}),T.category==="ide"&&t.jsx("button",{onClick:()=>b(s.find(M=>M.type===T.type)||{type:T.type,name:T.displayName,displayName:T.displayName,icon:T.icon,category:T.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:T.schema.map(M=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[M.label||M.key,l===`${T.type}.${M.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),M.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:M.description})]}),t.jsx("div",{className:"shrink-0",children:M.type==="boolean"?t.jsx("button",{onClick:()=>x(T.type,M.key,!(T.values[M.key]??M.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:T.values[M.key]??M.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:T.values[M.key]??M.default?21:3}})}):M.type==="number"?t.jsx("input",{type:"number",value:Number(T.values[M.key]??M.default??0)||0,min:M.min,max:M.max,onChange:B=>{const _=parseInt(B.target.value)||0;M.min!==void 0&&_<M.min||M.max!==void 0&&_>M.max||x(T.type,M.key,_)},className:"machine-input w-20 text-center text-[11px]"}):M.type==="select"&&M.options?t.jsx("select",{value:String(T.values[M.key]??M.default??""),onChange:B=>x(T.type,M.key,B.target.value),className:"machine-input text-[11px]",children:M.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(T.values[M.key]??M.default??""),onBlur:B=>x(T.type,M.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},M.key))})]},T.type))}),f&&t.jsx(fh,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>b(null)}),k&&t.jsx(hh,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>L(!1),onCreated:()=>{L(!1),w()}})]})}const bh=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function gh({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function yh(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Wo(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 vh({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),[b,k]=o.useState(!0),[L,d]=o.useState("debug"),[y,v]=o.useState("all"),h=o.useRef(null),C=o.useRef(!1),P=yh(a,y);return o.useEffect(()=>{if(!e||!b)return;const g=async()=>{try{const[j,w]=await Promise.all([s(e,"get_logs",{count:200,minLevel:L,since:u}),s(e,"get_debug_trace",gh({count:120,since:m,category:y}))]),x=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(T=>[...T,...x.logs.map(B=>({timestamp:B.ts,level:B.level,message:`[${B.category}] ${B.message}`}))].slice(-300));const N=Math.max(...x.logs.map(T=>T.ts));p(N)}const $=(w==null?void 0:w.result)||w;if(w!=null&&w.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const N=$.trace.reduce((T,M)=>Math.max(T,Number(M.ts||0)),m);N>m&&f(N)}}catch{}l(Ts.list({limit:120}))};g();const I=setInterval(g,3e3);return()=>clearInterval(I)},[e,b,u,m,L,y,s]),o.useEffect(()=>{if(b&&(r.length>0||a.length>0||c.length>0)){const g=C.current?"smooth":"instant";setTimeout(()=>{var I;(I=h.current)==null||I.scrollIntoView({behavior:g}),C.current=!0},50)}},[r.length,a.length,c.length,b]),o.useEffect(()=>{i([]),f(0)},[y]),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=",P.length," web=",c.length]}),t.jsx("button",{onClick:()=>k(!b),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),Ts.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,I)=>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-${I}`))]}),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",y==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:bh.map(g=>t.jsx("button",{onClick:()=>v(g.value),className:`machine-btn text-[10px] px-2 py-0.5 ${y===g.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:g.label},g.value))})]}),P.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:y==="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."}),P.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:Wo(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:Wo(g.payload)})]},g.id))]})]}),t.jsx("div",{ref:h})]})}function Pn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Dn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Oo(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 wh(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function jh(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 kh(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 Sh({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=oc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,b=p.applyDiagnostics,k=o.useMemo(()=>Wf({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),L=o.useMemo(()=>new Map(s.map(N=>[N.sessionId||N.id,N])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const N=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),T=Pn(N);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");b(T.diagnostics||T.result||null),a("")}catch(N){const T=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";a(T)}finally{u(!1)}}},[b,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const y=o.useCallback(async(N,T)=>{const M=`${N}:${T.sessionId}`;if(!(N==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
66
|
+
This will terminate the hosted runtime.`))){c(M);try{const B=await r(e,N,{sessionId:T.sessionId}),_=Pn(B);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Session host action failed");const S=N==="session_host_resume_session"?"resumed":N==="session_host_restart_session"?"restarted":"stopped";lt.showToast(`Session host ${S}: ${T.displayName}`,"success"),await d()}catch(B){const _=B instanceof Error?B.message:"Session host action failed";lt.showToast(_,"warning"),a(_)}finally{c(B=>B===M?null:B)}}},[e,d,r]),v=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 T=await r(e,"session_host_prune_duplicate_sessions",{}),M=Pn(T);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const B=M.result||{},_=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,S=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;lt.showToast(`Pruned ${_} duplicate runtime(s) across ${S} group(s)`,"success"),await d()}catch(T){const M=T instanceof Error?T.message:"Duplicate prune failed";lt.showToast(M,"warning"),a(M)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((N,T)=>(T.lastActivityAt||0)-(N.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=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)||[]}:Rc(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),P=C.liveRuntimes,g=C.recoverySnapshots,I=C.inactiveRecords,j=o.useMemo(()=>kh(P),[P]),w=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(N=>N.level==="warn"||N.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(N,T)=>{var V;const M=i===`session_host_resume_session:${N.sessionId}`,B=i===`session_host_restart_session:${N.sessionId}`,_=i===`session_host_stop_session:${N.sessionId}`,S=La(N.meta),O=L.get(N.sessionId),G=N.attachedClients.length===1?"1 client":`${N.attachedClients.length} clients`,A=T==="recovery"?"Recover":"Resume",K=Pc(T);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:N.displayName||(O==null?void 0:O.cliName)||N.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${jh(N.lifecycle)}`,children:N.lifecycle}),S&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:N.workspaceLabel||(O==null?void 0:O.runtimeWorkspaceLabel)||N.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:N.runtimeKey}),N.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",N.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((V=N.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:wh(N.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(na,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Oo(N.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",K]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{y("session_host_resume_session",N)},children:M?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{y("session_host_restart_session",N)},children:B?"Restarting…":"Restart"}),T==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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:()=>{y("session_host_stop_session",N)},children:_?"Stopping…":"Stop"})]})]})},N.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(zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Ju()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Ws,{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(xs,{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:Oo(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Dn(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(xs,{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:[Dn(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(Jr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ms("live")}),P.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:P.map(N=>$(N,"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(zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ms("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(N=>$(N,"recovery"))})]}),I.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:Ms("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(N=>$(N,"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"}),w.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:w.map(N=>{var M;const T=h.find(B=>B.sessionId===N.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:(T==null?void 0:T.displayName)||((M=L.get(N.sessionId))==null?void 0:M.cliName)||N.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Dn(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.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 Nh({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 $n({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 En({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 Ch({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=er(e,"0.8.75");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($n,{icon:t.jsx(Vt,{size:13}),children:"Current Chats"}),t.jsx(En,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const b=Fn(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:dt(f)}),b>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:en(b)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:gs(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(ni,{size:13}),children:"Recent Launches"}),t.jsx(En,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:b,updatedLabel:k}=gc(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}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:b})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(xs,{size:13}),children:"Daemon Update"}),t.jsx(En,{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(Ws,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ih(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Ah={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 Tr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mh(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 Kn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Bs(),{handleLaunchIde:f,handleStopCli:b,handleRestartIde:k,handleStopIde:L,handleDetectIdes:d,launchingIde:y,launchingAgentType:v,addLog:h}=c,[C,P]=o.useState(null),g=o.useCallback(D=>{D&&m(Jt(D))},[m]),I=Ah[e],j=e==="ide",w=e==="acp",x=o.useMemo(()=>n.filter(D=>D.category===e&&(e==="ide"||D.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(D=>[D.type,D.displayName||D.type])),[x]),[N,T]=o.useState(""),[M,B]=o.useState(""),[_,S]=o.useState([]),[O,G]=o.useState(""),[A,K]=o.useState(""),[V,U]=o.useState([]),[ce,Y]=o.useState(!1),[oe,Q]=o.useState(!1),[te,ue]=o.useState(""),[Ne,le]=o.useState(!1),[pe,ae]=o.useState(()=>yt()),[z,ve]=o.useState(null),[ee,we]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[re,ie]=o.useState(p||""),[ne,je]=o.useState([]),[xe,E]=o.useState(!1),[ke,ge]=o.useState(""),[Ce,J]=o.useState([]),[Me,He]=o.useState(!1),[$e,Ze]=o.useState(""),Ge=o.useRef(null),[Ye,ot]=o.useState(null),et=o.useRef("__home__"),[mt,Ve]=o.useState("__home__"),[it,ft]=o.useState(!1),ht=o.useRef(0),ye=ne.filter(D=>!a.some(X=>X.type===D&&jt(X.status)!=="stopped")),Ue=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ee&&we(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){we("__custom__"),ie(p);return}u&&(we(u),ie(""))},[u,p]),o.useEffect(()=>{j||N&&(x.some(D=>D.type===N)||(T(""),K("")))},[x,j,N]);const ze=(()=>{if(ee==="__custom__")return re.trim();if(!ee)return"";const D=(s.workspaces||[]).find(X=>X.id===ee);return(D==null?void 0:D.path)||""})(),Xe=o.useCallback(D=>{const X=Ue.current[D];X&&(clearTimeout(X),delete Ue.current[D]),je(de=>de.includes(D)?de.filter(Pe=>Pe!==D):de)},[]),pt=o.useRef(new Set),gt=o.useCallback(async D=>{if(l){He(!0),Ze("");try{const X=await on(l,r,D);ge(X.path),ie(X.path),J(X.directories)}catch(X){Ze(X instanceof Error?X.message:"Could not load folder")}finally{He(!1)}}},[r,l]),vt=o.useCallback(()=>{if(!l)return;we("__custom__"),E(!0);const D=a.map(de=>de.workspace),X=an(s.platform,nn(re.trim(),ze,p,D,s.defaultWorkspacePath,(s.workspaces||[]).map(de=>de.path)));gt(X)},[re,p,gt,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,l]),Ot=o.useCallback(D=>{const X=String(D.workspace||"").trim();if(!X)return;const de=(s.workspaces||[]).find(Pe=>Tr(Pe.path)===Tr(X));if(de){we(de.id),ie("");return}we("__custom__"),ie(X)},[s.workspaces]),Bt=o.useCallback(D=>{const X=String(D.workspace||"").trim();if(!X)return{workspaceId:null,workspacePath:"",useHome:!0};const de=(s.workspaces||[]).find(Pe=>Tr(Pe.path)===Tr(X));return de?{workspaceId:de.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:X,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async D=>{if(!l||!D||e!=="cli"){U([]),Y(!1),Q(!1),ue("");return}const X=ht.current+1;ht.current=X,Y(!0),ue("");try{const de=await l(r,"list_saved_sessions",{providerType:D,kind:"cli",limit:30});if(ht.current!==X)return;const Pe=(de==null?void 0:de.result)??de;U(Array.isArray(Pe==null?void 0:Pe.sessions)?Pe.sessions:[])}catch(de){if(ht.current!==X)return;U([]),ue(de instanceof Error?de.message:"Could not load saved sessions")}finally{ht.current===X&&(Y(!1),Q(!0))}},[e,r,l]),It=o.useMemo(()=>{if(e!=="cli"||!N)return null;const D=$.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:D,agentType:N,status:"idle",title:D,messages:[],ideType:N,workspaceName:ze,displayPrimary:D,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,$,ze,A,N]),q=o.useCallback(D=>{if(e==="ide"||!D){S([]);return}S(Lc(r,D))},[e,r]);o.useEffect(()=>{if(K(""),q(N),Q(!1),e!=="cli"||!N){U([]),ue(""),Y(!1);return}Ct(N)},[e,q,Ct,N]);const Ee=o.useMemo(()=>V.find(D=>D.providerSessionId===A)||null,[V,A]);o.useEffect(()=>{if(!A)return;const D=V.find(X=>X.providerSessionId===A);D!=null&&D.canResume||K("")},[V,A]);const R=o.useCallback((D,X)=>{Ge.current=X,et.current=D.selectedWorkspaceKey||"__home__",Ve(D.selectedWorkspaceKey||"__home__"),ot(D)},[]),W=o.useCallback(()=>{Ge.current&&(ft(!0),Ge.current().finally(()=>{Ge.current=null,ft(!1),ot(null)}))},[]),H=o.useCallback(D=>{if(!D)return;je(de=>de.includes(D)?de:[...de,D]);const X=Ue.current[D];X&&clearTimeout(X),Ue.current[D]=setTimeout(()=>{je(de=>de.includes(D)?de.filter(Pe=>Pe!==D):de),delete Ue.current[D]},2e4)},[]);o.useEffect(()=>{for(const X of a)jt(X.status)!=="stopped"&&(ne.includes(X.type)&&!pt.current.has(X.type)&&(pt.current.add(X.type),h("info",`${$.get(X.type)||X.type} launched`,!0)),Xe(X.type));const D=new Set(a.filter(X=>jt(X.status)!=="stopped").map(X=>X.type));pt.current.forEach(X=>{!ne.includes(X)&&!D.has(X)&&pt.current.delete(X)})},[h,Xe,a,ne,$]),o.useEffect(()=>()=>{Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const[F,se]=o.useState({}),[Se,Te]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const X=await l(r,"get_ide_extensions",{}),de=(X==null?void 0:X.result)||X;de!=null&&de.success&&(de!=null&&de.ideExtensions)&&se(de.ideExtensions)}catch{}})()},[j,r,l]);const Ie=D=>j?at(D.type):e==="cli"?D.cliName:D.acpName,We=j?s.detectedIdes||[]:[],Ke=o.useCallback(async D=>{const X=(D==null?void 0:D.type)||N,de=(D==null?void 0:D.workspacePath)??ze;if(j){await f(X,de?{workspace:de}:void 0)&&H(X);return}const Pe=await c.runLaunchCliCore({cliType:X,dir:D!=null&&D.workspaceId?void 0:de||void 0,workspaceId:(D==null?void 0:D.workspaceId)||void 0,useHome:(D==null?void 0:D.useHome)||!(D!=null&&D.workspaceId)&&!de,argsStr:(D==null?void 0:D.argsStr)??(M||void 0),model:(D==null?void 0:D.model)??(w&&O||void 0),resumeSessionId:(D==null?void 0:D.resumeSessionId)||!w&&e==="cli"&&X===N&&A||void 0});if(Pe.success||Pe.pending){const fe=(D==null?void 0:D.argsStr)??M;!j&&(fe!=null&&fe.trim())&&(_c(r,X,fe),q(X)),H(X),Pe.success&&Pe.sessionId&&g(Pe.sessionId)}},[c,f,w,j,M,O,q,H,r,g,ze,A,N]),Ae=Ui(j?"ide":w?"acp":"cli",!j&&!w&&!!A),Z=Fi(j?"ide":w?"acp":"cli",!j&&!w&&!!A),Re=()=>{var fe;const D=j?at(N):$.get(N)||N,X=!j&&!w&&!!A,{options:de,selectedKey:Pe}=fs({machine:s,currentWorkspaceId:ee&&ee!=="__custom__"?ee:null,currentWorkspacePath:ze});R({title:X?ya(D):ds("start-fresh",D),description:X?va():us("start-fresh"),confirmLabel:Ae,busyLabel:Z,workspaceOptions:de,selectedWorkspaceKey:Pe,details:[{label:"Mode",value:I.label},{label:"Provider",value:D},...!j&&e==="cli"&&A?[{label:"Resume",value:((fe=V.find(he=>he.providerSessionId===A))==null?void 0:fe.title)||A}]:[],...!j&&M.trim()?[{label:"Arguments",value:M.trim()}]:[],...w&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const he=de.find(Qe=>Qe.key===et.current);he!=null&&he.workspaceId?(we(he.workspaceId),ie("")):he!=null&&he.workspacePath?(we("__custom__"),ie(he.workspacePath)):(we(""),ie("")),await Ke({workspaceId:(he==null?void 0:he.workspaceId)??null,workspacePath:(he==null?void 0:he.workspacePath)??"",useHome:!(he!=null&&he.workspaceId)&&!(he!=null&&he.workspacePath)})})},Oe=D=>{j?L(D):b(D.type,D.workspace,D.id)},De=o.useCallback(async(D,X,de=!1)=>{if(D.mode===X){de&&D.sessionId&&g(D.sessionId);return}if(!l||!D.sessionId){de&&D.sessionId&&g(D.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.type,mode:X}),de&&g(D.sessionId)}catch(Pe){Mh(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]),xt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ee,onChange:D=>{const X=D.target.value;if(we(X),X==="__custom__"&&l){vt();return}X!=="__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(D=>t.jsxs("option",{value:D.id,children:[D.id===s.defaultWorkspaceId?"⭐ ":"",sn(D.path,D.label)]},D.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…"})]})}),ee==="__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:vt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:re,onChange:D=>ie(D.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:ee==="__custom__"?ze?t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ze?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ee===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ze,children:ze})]}):"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 ${I.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 ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map(D=>{const X=a.find(Qe=>(Qe.type||"").toLowerCase()===(D.type||"").toLowerCase()&&jt(Qe.status)!=="stopped"),de=D.running||!!X,Pe=!!X&&X.cdpConnected,fe=ne.includes(D.type||D.id||""),he=N===(D.type||"");return t.jsxs("button",{onClick:()=>{if(Pe&&X){const Qe=X.sessionId;Qe?m(Jt(Qe),{state:{openRemoteForTabKey:Qe}}):m("/dashboard",{state:{openRemoteForTabKey:X.id}});return}fe||T(Qe=>Qe===(D.type||"")?"":D.type||"")},disabled:!!y||fe,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":he?"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:y&&y!==D.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(D.type)}),de&&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:D.name||at(D.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Pe?"text-green-400":fe?"text-orange-400":he?"text-accent-primary":"text-text-muted"}`,children:Pe?"Open Session":fe?"Starting...":he?"Configure":"Select"})]})]},D.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(Rl,{size:14})," Scan System"]})]}):x.length>0?x.map(D=>{const X=N===D.type,de=ne.includes(D.type),fe=!!a.find(he=>he.type===D.type&&jt(he.status)!=="stopped");return t.jsxs("button",{onClick:()=>T(he=>he===D.type?"":D.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${X?"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:D.icon}),fe&&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:D.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${de?"text-orange-400":X?"text-accent-primary":"text-text-muted"}`,children:de?"Starting...":X?"Configure":"Select"})]})]},D.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."})]})}),N&&(j?We.find(D=>D.type===N):x.find(D=>D.type===N))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?at(N):$.get(N)||N})]}),xt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx($c,{busy:!!v||!!y||ne.includes(N),savedSessionsLoading:ce,savedSessionsError:te,selectedSession:Ee,onRefresh:()=>void Ct(N),onOpenHistory:()=>{N&&(le(!0),Dc({hasLoadedInitialResults:oe,isLoading:ce})&&Ct(N))},onClearSelection:()=>K("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:O,onChange:D=>G(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:M,onChange:D=>B(D.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),_.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:_.map(D=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B(D),title:D,children:D},D))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Re,disabled:!!v||!!y||ne.includes(N),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:v===N||y===N?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter(D=>!a.some(X=>X.type===D&&jt(X.status)!=="stopped")).length,")"]}),a.length===0&&ye.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 ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ye.map(D=>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(D)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?at(D):$.get(D)||D}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===D?"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:${D}`)),a.map(D=>{const X=j?D:null,de=!j&&!w?D:null,Pe=jt(D.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(D.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(D),(X==null?void 0:X.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",X.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:D.workspace||"—"}),(de==null?void 0:de.mode)&&t.jsx("span",{className:de.mode==="chat"?"text-violet-400":"text-text-secondary",children:de.mode==="chat"?"Chat view":"Terminal view"})]}),de&&(de.runtimeKey||de.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[de.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 ",de.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 fe;(fe=navigator.clipboard)==null||fe.writeText(`adhdev attach ${de.runtimeKey}`),P(de.runtimeKey||null),window.setTimeout(()=>{P(he=>he===de.runtimeKey?null:he)},1200)},children:C===de.runtimeKey?"Copied":"Copy"})]}),de.runtimeWriteOwner&&t.jsx("span",{style:{color:de.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:de.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ih(de.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}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const fe=D.sessionId;if(fe){m(Jt(fe),{state:{openRemoteForTabKey:fe}});return}m("/dashboard",{state:{openRemoteForTabKey:D.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(Tt,{size:13})}),t.jsx("button",{onClick:()=>{const fe=D.workspace||"",{options:he,selectedKey:Qe}=fs({machine:s,currentWorkspacePath:fe});R({title:ds("restart-ide",at(D.type)),description:us("restart-ide"),confirmLabel:Es("restart-ide"),busyLabel:Ks("restart-ide"),workspaceOptions:he,selectedWorkspaceKey:Qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(D.type)}]},async()=>{const St=he.find(qt=>qt.key===et.current),ct=(St==null?void 0:St.workspacePath)??"";if(ct&&ct!==fe){await Ke({type:D.type,workspacePath:ct});return}await k(D)})},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(Ws,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const fe=D.sessionId;fe&&g(fe)},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:!D.sessionId,children:t.jsx(Vt,{size:14})}),de&&Pe!=="stopped"&&t.jsxs(t.Fragment,{children:[de.mode&&t.jsx(xa,{mode:de.mode,onChange:fe=>void De(de,fe,!1),compact:!0}),t.jsx("button",{onClick:()=>{const fe=D.sessionId;fe&&g(fe)},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:!D.sessionId,children:de.mode==="chat"?t.jsx(Vt,{size:14}):t.jsx(Tt,{size:13})})]}),Pe==="stopped"?t.jsx("button",{onClick:()=>{const fe=D.workspace||"",he=j?at(D.type):Ie(D),{options:Qe,selectedKey:St}=fs({machine:s,currentWorkspacePath:fe});R({title:ds("restart-stopped",he),description:us("restart-stopped"),confirmLabel:Es("restart-stopped"),busyLabel:Ks("restart-stopped"),workspaceOptions:Qe,selectedWorkspaceKey:St,details:[{label:"Mode",value:I.label},{label:"Provider",value:he}]},async()=>{const ct=Qe.find(qt=>qt.key===et.current);await Ke({type:D.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:ne.includes(D.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:ne.includes(D.type)?"⏳":t.jsx(oa,{size:14})}):t.jsx("button",{onClick:()=>Oe(D),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(Nt,{size:14})})]})]}),X&&X.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:X.aiAgents.map(fe=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${fi(fe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[fe.name," · ",jt(fe.status)]},fe.id))}),X&&(F[X.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[X.type]||[]).map(fe=>t.jsxs("button",{disabled:Se===`${X.type}.${fe.type}`,onClick:async()=>{const he=`${X.type}.${fe.type}`;Te(he);try{await l(r,"set_ide_extension",{ideType:X.type,extensionType:fe.type,enabled:!fe.enabled}),se(Qe=>({...Qe,[X.type]:(Qe[X.type]||[]).map(St=>St.type===fe.type?{...St,enabled:!St.enabled}:St)}))}catch(Qe){console.error("Extension toggle failed:",Qe)}finally{Te(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 ${fe.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 ${fe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),fe.name,t.jsx("span",{className:"text-[9px] font-normal",children:fe.enabled?"ON":"OFF"})]},fe.type))})]})]},D.id)})]}),xe&&l&&t.jsx(cn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:ke,directories:Ce,busy:Me,error:$e,confirmLabel:"Use this folder",onClose:()=>E(!1),onNavigate:D=>{gt(D)},onConfirm:D=>{ie(D),we("__custom__"),E(!1)}}),Ye&&t.jsx(Ma,{title:Ye.title,description:Ye.description,details:Ye.details,workspaceOptions:Ye.workspaceOptions,selectedWorkspaceKey:mt,onWorkspaceChange:D=>{et.current=D,Ve(D)},confirmLabel:Ye.confirmLabel,busyLabel:Ye.busyLabel,busy:it,onConfirm:W,onCancel:()=>{Ge.current=null,ot(null)}}),Ne&&It&&t.jsx(wa,{activeConv:It,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:V,isSavedSessionsLoading:ce,isResumingSavedSessionId:z,savedHistoryFilters:pe,onSavedHistoryFiltersChange:ae,onClose:()=>le(!1),onNewChat:()=>{K(""),le(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(N)},onResumeSavedSession:D=>{if(!D.canResume||z)return;const X=Bt(D);K(D.providerSessionId),Ot(D),ve(D.providerSessionId),le(!1),Ke({type:D.providerType,workspaceId:X.workspaceId,workspacePath:X.workspacePath,useHome:X.useHome,resumeSessionId:D.providerSessionId}).finally(()=>{ve(de=>de===D.providerSessionId?null:de)})}})]})}const Ho=[{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 Th({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[b,k]=o.useState(u);o.useEffect(()=>{k(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:Ho.map(y=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${b===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(y.id),children:[t.jsx("span",{children:y.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${b===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L[y.id]})]},y.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Ho.find(y=>y.id===b))==null?void 0:d.helper})]}),b==="ide"&&t.jsx(Kn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),b==="cli"&&t.jsx(Kn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),b==="acp"&&t.jsx(Kn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Lh({onNicknameSynced:e}={}){var z,ve,ee,we,re,ie,ne,je,xe;const{id:s}=ul(),r=Bs(),n=sa(),{sendCommand:a}=Lt(),i=ur(),c=$i(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),m=l.some(E=>E.type==="adhdev-daemon"),[f,b]=o.useState("workspace"),[k,L]=o.useState("ide"),d=o.useRef(null),[y,v]=o.useState(null),h=o.useRef("__home__"),[C,P]=o.useState("__home__"),[g,I]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),Um(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const w=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=ch({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>lt.onToast(ke=>{c.setToasts(Ce=>{if(Ce.some(He=>He.message===ke.message&&ke.timestamp-He.timestamp<3e3))return Ce;const Me={id:ke.id,message:ke.message,type:ke.type,timestamp:ke.timestamp,targetKey:ke.targetKey,actions:ke.actions};return[...Ce.slice(-4),Me]});const ge=ke.duration||5e3;setTimeout(()=>c.setToasts(Ce=>Ce.filter(J=>J.id!==ke.id)),ge)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],N={};for(const E of $)N[E.type]=E.icon;const T=E=>N[E]||"",M=p?{id:p.id,hostname:hi(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ve=p.machine)==null?void 0:ve.arch)||"",cpus:((ee=p.machine)==null?void 0:ee.cpus)||0,totalMem:((we=p.machine)==null?void 0:we.totalMem)||0,freeMem:(re=p.machine)==null?void 0:re.freeMem,availableMem:(ie=p.machine)==null?void 0:ie.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(je=p.machine)==null?void 0:je.uptime,release:((xe=p.machine)==null?void 0:xe.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,B=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!ar(E)&&!Is(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Cd(E.aiAgents||(E.agents||[]).map(ke=>({id:ke.name,name:ke.name,status:ke.status,version:ke.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),_=l.filter(E=>E.daemonId===s&&ar(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),S=l.filter(E=>E.daemonId===s&&Is(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),O=p?Mt(p,{fallbackId:s}):"",G="workspace",A=n.state,K=A==null?void 0:A.initialMachineTab,V=A==null?void 0:A.initialWorkspaceCategory,U=A==null?void 0:A.initialWorkspaceId,ce=A==null?void 0:A.initialWorkspacePath,Y=K==="ides"||K==="clis"||K==="acps"?"workspace":K||G,oe=K==="ides"?"ide":K==="clis"?"cli":K==="acps"?"acp":V,Q=[...B.map(E=>{var ke,ge,Ce,J,Me;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}}),..._.map(E=>{var ke,ge,Ce,J,Me;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}}),...S.map(E=>{var ke,ge,Ce,J,Me;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ke=E.activeChat)==null?void 0:ke.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:bs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Me=(J=(Ce=(ge=E.activeChat)==null?void 0:ge.messages)==null?void 0:Ce.at)==null?void 0:J.call(Ce,-1))==null?void 0:Me.timestamp)||0}})].sort((E,ke)=>(ke.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),te=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:bs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):Q,ue=o.useMemo(()=>{var ke;const E=((ke=c.connectionStates)==null?void 0:ke[s||""])||void 0;return l.filter(ge=>ge.daemonId===s&&ge.type!=="adhdev-daemon").flatMap(ge=>ja(ge,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,Ce)=>Fn(Ce)-Fn(ge))},[l,c.connectionStates,s]),Ne=o.useCallback(E=>{const ke=pa(E);ke&&r(Jt(ke))},[r]),le=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),v(null)}))},[]),pe=o.useCallback(E=>{if(!M)return;const{options:ke,selectedKey:ge}=fs({machine:M,currentWorkspacePath:E.workspace}),Ce=async()=>{L(E.kind),b("workspace")};d.current=async()=>{const J=ke.find($e=>$e.key===h.current),Me=(J==null?void 0:J.workspacePath)??null,He=(J==null?void 0:J.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,Me?{workspace:Me}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:He?void 0:Me||"",workspaceId:He||void 0,model:E.kind==="acp"&&bi(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await Ce()},h.current=ge,P(ge),v({title:E.kind==="ide"?ds("restart-ide",E.label):E.providerSessionId?ya(E.label):ds("start-fresh",E.label),description:E.kind==="ide"?us("restart-ide"):E.providerSessionId?va():us("start-fresh"),confirmLabel:E.kind==="ide"?Es("restart-ide"):E.providerSessionId?zr(!0):Es("start-fresh"),busyLabel:E.kind==="ide"?Ks("restart-ide"):E.providerSessionId?ba(!0):Ks("start-fresh"),workspaceOptions:ke,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,M]);if(o.useEffect(()=>{b(Y)},[G,Y,s]),o.useEffect(()=>{oe&&L(oe)},[oe,s]),!M)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:w,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 ae=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:14})," Workspace"]}),count:B.length+_.length+S.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ll,{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:w,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:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.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(M.machineNickname||"")},title:"Click to set nickname",children:O}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),t.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),M.p2p.available&&t.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ae.map(E=>t.jsxs("button",{onClick:()=>b(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.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(Ch,{machineEntry:p,providers:$,recentLaunches:te,currentConversations:ue,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:pe,onOpenConversation:Ne}),t.jsx(Th,{machine:M,machineId:s,providers:$,ideSessions:B,cliSessions:_,acpSessions:S,actions:x,getIcon:T,initialCategory:k,initialWorkspaceId:U,initialWorkspacePath:ce,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(xh,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(lh,{machineId:s,machine:M,ideSessions:B,cliSessions:_,acpSessions:S,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Sh,{machineId:s,cliSessions:_,sendDaemonCommand:a}),f==="logs"&&t.jsx(vh,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&M&&t.jsx(Nh,{machine:M,launchPick:x.launchPick,actions:x}),y&&t.jsx(Ma,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:E=>{h.current=E,P(E)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:g,onConfirm:le,onCancel:()=>{d.current=null,v(null)}}),t.jsx(zi,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ke=>ke.filter(ge=>ge.id!==E)),onClickToast:E=>{E.targetKey&&r(Jt(E.targetKey))}}),t.jsx("style",{children:`
|
|
68
68
|
@keyframes toast-in {
|
|
69
69
|
from { opacity: 0; transform: translateX(40px); }
|
|
70
70
|
to { opacity: 1; transform: translateX(0); }
|
|
71
71
|
}
|
|
72
|
-
`})]})}class _h{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,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 Ht=new _h;function Rh(){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 Lr=Rh(),Uo=3e3,Ph=3e4;let Wt=null,Dh=0;const Xr=new Map;let ns=null,sr=null;function Fo(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Ys(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function $h(e){return e==="connected"?"connected":e}async function Kr(e,s,r){const n=dm(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Dh}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Xr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Xr.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 Zn(e,s){const r=Wt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Eh{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN}get connectionState(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Kr(this.daemonId,s,r)}async sendInput(s,r){return Kr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ns&&(clearInterval(ns),ns=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Kr(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());Ht.emitScreenshot(this.daemonId,a)}}catch{}};r(),ns=setInterval(r,2e3)}stopScreenshots(s){ns&&(clearInterval(ns),ns=null)}}let Pt=null;function Kh(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Eh(e)),Pt}function Bh({children:e}){const s=o.useRef(Wr()),r=Wr();s.current=r;const{setUserName:n}=hs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,g)=>{l(d),sr==null||sr(d,g)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Uo),y=o.useRef(!0),k=o.useRef(!1),T=o.useRef("initial_connect");return o.useEffect(()=>{y.current=!0,k.current=!1;function d(){var h,C;if(!y.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Lr}...`),Ys("connect_attempt",{url:Lr,reason:T.current,delayMs:f.current});let v;try{v=new WebSocket(Lr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),g();return}p.current=v,v.onopen=()=>{if(!y.current){v.close();return}u("connected"),f.current=Uo,Ys("open",{url:Lr,reason:T.current}),Zt.resubscribeAll({sendData:Zn}),console.log("[Standalone WS] Connected")},Wt=v,v.onmessage=P=>{var b,I;try{const j=JSON.parse(P.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const w=Xr.get(j.requestId);w&&(Xr.delete(j.requestId),j.type==="error"?w.reject(new Error(((b=j.data)==null?void 0:b.message)||"Command failed")):w.resolve(j.data));return}if(j.type==="session_output"){const w=j.sessionId||j.cliId||j.cliType;w&&Ht.emitSessionOutput(w,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ht.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const w=j.update;w&&Zt.publish(w);return}if(j.type==="status"||j.type==="initial_state"){const w=j.data;if(!w)return;const{injectEntries:x,markLoaded:$,getIdes:N}=s.current,L=w.instanceId||"standalone",M=N().find(S=>S.id===L),B=Kh(L);Ht.register(L,B),Ht.setState(L,"connected"),u("connected",L),Ht.emitStatus(L,w);const _=Fr(w,{daemonId:L,existingDaemon:M,existingEntries:N()});Fo("ws_status",{type:j.type,daemonId:L,sessions:(w.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(w.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),Fo("entries",{daemonId:L,entries:_.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),_.length>0&&x(_,{authoritativeDaemonIds:[L]}),$(),c.current!==L&&((I=i.current)==null||I.call(i),c.current=L,i.current=Zt.subscribe({sendData:Zn},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const O=s.current.getIdes(),G=O.find(K=>K.id===L),A=Fr(S.status,{daemonId:L,existingDaemon:G,existingEntries:O,timestamp:S.timestamp});A.length>0&&s.current.injectEntries(A),S.userName&&a.current&&a.current(S.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=P=>{y.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Ht.setState(Pt.daemonId,"disconnected"),u("disconnected"),p.current=null,T.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,Ys("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),g())},v.onerror=P=>{k.current||!y.current||(T.current="error",Ys("error",{message:P instanceof Event?"event":String(P),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function g(){if(!y.current)return;clearTimeout(m.current);const v=f.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Ys("schedule_reconnect",{reason:T.current,delayMs:v}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Ph),d()},v)}return d(),()=>{var v;y.current=!1,k.current=!0,(v=i.current)==null||v.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,Wt=null),Pt&&(Pt.stopScreenshots(),Ht.unregister(Pt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Wh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(sr=(c,l)=>{r(c),l&&a(l)},()=>{sr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=$h(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(wl,{connectionOverrides:i,children:t.jsx(Bh,{children:e})})}const Oh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Zo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Qr,{}),label:"Settings"}];function Hh({children:e}){const s=Bs(),r=sa(),[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(Nt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Oh.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(ei,{})}),!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(ti,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.74"]}),t.jsx(km,{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 Uh=[{icon:t.jsx(zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Vt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(si,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(nr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ei,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Fh=[{icon:t.jsx(El,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Zo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Zr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Tl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(na,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(_l,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],zh=[{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 Vh(){return t.jsxs(Qi,{icon:t.jsx(ti,{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.74"]}),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:Uh.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:qi.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Xi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Yi.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:Fh.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:zh.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(Ji,{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(Gl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Gh(){const{ides:e}=hs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Lt(),{userName:a}=hs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const y=f.target.value.trim();s!=null&&s.id&&y!==a&&n(s.id,"set_user_name",{userName:y}).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(Qi,{icon:t.jsx(Qr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(bm,{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.74"]}),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(Im,{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(Lm,{})]}),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(Bm,{})]}),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(Om,{})]})]})}),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(Sm,{}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vl,{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(Ml,{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()}})]})})})]})}jm();Em();const qh=Xo({baseUrl:""});function zo(){const{ides:e,initialLoaded:s}=hs();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(On,{to:`/machines/${r.id}`,replace:!0}):t.jsx(On,{to:"/dashboard",replace:!0})}function Yh(){const e=o.useMemo(()=>({sendCommand:Kr,sendData:Zn}),[]);return t.jsx(ml,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Sl,{client:qh,children:t.jsx(Wh,{children:t.jsx(Cl,{value:e,children:t.jsx(Hh,{children:t.jsxs(pl,{children:[t.jsx(ss,{path:"/dashboard",element:t.jsx(ih,{})}),t.jsx(ss,{path:"/machine",element:t.jsx(zo,{})}),t.jsx(ss,{path:"/machines/:id",element:t.jsx(Lh,{})}),t.jsx(ss,{path:"/machines",element:t.jsx(zo,{})}),t.jsx(ss,{path:"/about",element:t.jsx(Vh,{})}),t.jsx(ss,{path:"/settings",element:t.jsx(Gh,{})}),t.jsx(ss,{path:"*",element:t.jsx(On,{to:"/dashboard",replace:!0})})]})})})})})})}Ku({connectionManager:Ht});fl(document.getElementById("root")).render(t.jsx(Yh,{}));
|
|
72
|
+
`})]})}class _h{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}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 Ht=new _h;function Rh(){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 Lr=Rh(),Uo=3e3,Ph=3e4;let Wt=null,Dh=0;const Xr=new Map;let ns=null,sr=null;function Fo(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Ys(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function $h(e){return e==="connected"?"connected":e}async function Kr(e,s,r){const n=dm(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Dh}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Xr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Xr.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 Zn(e,s){const r=Wt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Eh{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN}get connectionState(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Kr(this.daemonId,s,r)}async sendInput(s,r){return Kr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ns&&(clearInterval(ns),ns=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Kr(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());Ht.emitScreenshot(this.daemonId,a)}}catch{}};r(),ns=setInterval(r,2e3)}stopScreenshots(s){ns&&(clearInterval(ns),ns=null)}}let Pt=null;function Kh(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Eh(e)),Pt}function Bh({children:e}){const s=o.useRef(Wr()),r=Wr();s.current=r;const{setUserName:n}=hs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,y)=>{l(d),sr==null||sr(d,y)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Uo),b=o.useRef(!0),k=o.useRef(!1),L=o.useRef("initial_connect");return o.useEffect(()=>{b.current=!0,k.current=!1;function d(){var h,C;if(!b.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Lr}...`),Ys("connect_attempt",{url:Lr,reason:L.current,delayMs:f.current});let v;try{v=new WebSocket(Lr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),y();return}p.current=v,v.onopen=()=>{if(!b.current){v.close();return}u("connected"),f.current=Uo,Ys("open",{url:Lr,reason:L.current}),Zt.resubscribeAll({sendData:Zn}),console.log("[Standalone WS] Connected")},Wt=v,v.onmessage=P=>{var g,I;try{const j=JSON.parse(P.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const w=Xr.get(j.requestId);w&&(Xr.delete(j.requestId),j.type==="error"?w.reject(new Error(((g=j.data)==null?void 0:g.message)||"Command failed")):w.resolve(j.data));return}if(j.type==="session_output"){const w=j.sessionId||j.cliId||j.cliType;w&&Ht.emitSessionOutput(w,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ht.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const w=j.update;w&&Zt.publish(w);return}if(j.type==="status"||j.type==="initial_state"){const w=j.data;if(!w)return;const{injectEntries:x,markLoaded:$,getIdes:N}=s.current,T=w.instanceId||"standalone",M=N().find(S=>S.id===T),B=Kh(T);Ht.register(T,B),Ht.setState(T,"connected"),u("connected",T),Ht.emitStatus(T,w);const _=Fr(w,{daemonId:T,existingDaemon:M,existingEntries:N()});Fo("ws_status",{type:j.type,daemonId:T,sessions:(w.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(w.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),Fo("entries",{daemonId:T,entries:_.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),_.length>0&&x(_,{authoritativeDaemonIds:[T]}),$(),c.current!==T&&((I=i.current)==null||I.call(i),c.current=T,i.current=Zt.subscribe({sendData:Zn},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const O=s.current.getIdes(),G=O.find(K=>K.id===T),A=Fr(S.status,{daemonId:T,existingDaemon:G,existingEntries:O,timestamp:S.timestamp});A.length>0&&s.current.injectEntries(A),S.userName&&a.current&&a.current(S.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=P=>{b.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Ht.setState(Pt.daemonId,"disconnected"),u("disconnected"),p.current=null,L.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,Ys("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),y())},v.onerror=P=>{k.current||!b.current||(L.current="error",Ys("error",{message:P instanceof Event?"event":String(P),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function y(){if(!b.current)return;clearTimeout(m.current);const v=f.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),Ys("schedule_reconnect",{reason:L.current,delayMs:v}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Ph),d()},v)}return d(),()=>{var v;b.current=!1,k.current=!0,(v=i.current)==null||v.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,Wt=null),Pt&&(Pt.stopScreenshots(),Ht.unregister(Pt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Wh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(sr=(c,l)=>{r(c),l&&a(l)},()=>{sr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=$h(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(wl,{connectionOverrides:i,children:t.jsx(Bh,{children:e})})}const Oh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Zo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Qr,{}),label:"Settings"}];function Hh({children:e}){const s=Bs(),r=sa(),[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(Nt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Oh.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(ei,{})}),!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(ti,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.75"]}),t.jsx(km,{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 Uh=[{icon:t.jsx(zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Vt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(si,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(nr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ei,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Fh=[{icon:t.jsx(El,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Zo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Zr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Tl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(na,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(_l,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],zh=[{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 Vh(){return t.jsxs(Qi,{icon:t.jsx(ti,{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.75"]}),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:Uh.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:qi.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Xi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Yi.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:Fh.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:zh.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(Ji,{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(Gl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Gh(){const{ides:e}=hs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Lt(),{userName:a}=hs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const b=f.target.value.trim();s!=null&&s.id&&b!==a&&n(s.id,"set_user_name",{userName:b}).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(Qi,{icon:t.jsx(Qr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(bm,{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.75"]}),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(Im,{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(Lm,{})]}),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(Bm,{})]}),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(Om,{})]})]})}),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(Sm,{}),t.jsx(as,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vl,{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(Ml,{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()}})]})})})]})}jm();Em();const qh=Xo({baseUrl:""});function zo(){const{ides:e,initialLoaded:s}=hs();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(On,{to:`/machines/${r.id}`,replace:!0}):t.jsx(On,{to:"/dashboard",replace:!0})}function Yh(){const e=o.useMemo(()=>({sendCommand:Kr,sendData:Zn}),[]);return t.jsx(ml,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Sl,{client:qh,children:t.jsx(Wh,{children:t.jsx(Cl,{value:e,children:t.jsx(Hh,{children:t.jsxs(pl,{children:[t.jsx(ss,{path:"/dashboard",element:t.jsx(ih,{})}),t.jsx(ss,{path:"/machine",element:t.jsx(zo,{})}),t.jsx(ss,{path:"/machines/:id",element:t.jsx(Lh,{})}),t.jsx(ss,{path:"/machines",element:t.jsx(zo,{})}),t.jsx(ss,{path:"/about",element:t.jsx(Vh,{})}),t.jsx(ss,{path:"/settings",element:t.jsx(Gh,{})}),t.jsx(ss,{path:"*",element:t.jsx(On,{to:"/dashboard",replace:!0})})]})})})})})})}Ku({connectionManager:Ht});fl(document.getElementById("root")).render(t.jsx(Yh,{}));
|