@adhdev/daemon-standalone 0.8.98 → 0.8.100

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,79 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-NRPEa5lD.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var ud=Object.defineProperty;var md=(e,s,r)=>s in e?ud(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>md(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ia,a as Aa,b as Pi,c as Di,u as Hs,R as lt,d as cr,t as pd,e as fd,D as hd,f as ia,g as ca,h as Ma,i as xd,k as bd,B as gd,l as yd,m as cs,N as la,n as vd}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 wd(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 Ds=wd();function Co(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 jd(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function da(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)?e.messages:[],n=Array.isArray(s.messages)?s.messages:[],a=r.length>0?r:n,i=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:a,activeModal:i,inputContent:e.inputContent??s.inputContent}}function tr(e,s){const r=jd(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:da(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),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),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 Io(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?tr(n,a):n})}const Ei=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}),$i=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ao(e){var r,n;let s=0;return e.activeChat!==void 0&&(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 Tn(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 sn(e){return Array.isArray(e)?e.map(sn):!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,sn(r)]))}function kd(e,s){try{return JSON.stringify(sn(e))===JSON.stringify(sn(s))}catch{return!1}}function Cr(e,s,r){return kd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Sd(e,s,r){var f,d,g,y,w,A,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(p=>({...p,_lastUpdate:n}));const i=new Map;for(const p of s)i.set(p.id,p);for(const p of e){const x=i.get(p.id);if(!x){i.set(p.id,{...p,_lastUpdate:n});continue}const h=Ao(p),S=Ao(x);if(h>S){const _=(f=p.chats)!=null&&f.length?p.chats:x.chats,j=Io(x.childSessions,p.childSessions),I=da(p.activeChat,x.activeChat),k=Tn(x,p,{...x,...p,chats:_,childSessions:j,activeChat:I,_lastUpdate:n});i.set(p.id,Cr(x,k,n))}else if(h<S){const _={};if(p.status&&p.status!==x.status&&(_.status=p.status),p.cdpConnected!==void 0&&(_.cdpConnected=p.cdpConnected),(d=p.chats)!=null&&d.length&&!((g=x.chats)!=null&&g.length)&&(_.chats=p.chats),p.title!==void 0&&(_.title=p.title),p.workspace!==void 0&&(_.workspace=p.workspace),p.providerSessionId!==void 0&&(_.providerSessionId=p.providerSessionId),p.parentSessionId!==void 0&&(_.parentSessionId=p.parentSessionId),p.sessionKind!==void 0&&(_.sessionKind=p.sessionKind),p.sessionCapabilities!==void 0&&(_.sessionCapabilities=p.sessionCapabilities),p.controlValues!==void 0&&(_.controlValues=p.controlValues),p.providerControls!==void 0&&(_.providerControls=p.providerControls),p.summaryMetadata!==void 0&&(_.summaryMetadata=p.summaryMetadata),p.lastMessagePreview!==void 0&&(_.lastMessagePreview=p.lastMessagePreview),p.lastMessageRole!==void 0&&(_.lastMessageRole=p.lastMessageRole),p.lastMessageAt!==void 0&&(_.lastMessageAt=p.lastMessageAt),p.lastMessageHash!==void 0&&(_.lastMessageHash=p.lastMessageHash),p.lastUpdated!==void 0&&(_.lastUpdated=p.lastUpdated),p.unread!==void 0&&(_.unread=p.unread),p.lastSeenAt!==void 0&&(_.lastSeenAt=p.lastSeenAt),p.inboxBucket!==void 0&&(_.inboxBucket=p.inboxBucket),p.completionMarker!==void 0&&(_.completionMarker=p.completionMarker),p.seenCompletionMarker!==void 0&&(_.seenCompletionMarker=p.seenCompletionMarker),p.surfaceHidden!==void 0&&(_.surfaceHidden=p.surfaceHidden),p.runtimeKey!==void 0&&(_.runtimeKey=p.runtimeKey),p.runtimeDisplayName!==void 0&&(_.runtimeDisplayName=p.runtimeDisplayName),p.runtimeWorkspaceLabel!==void 0&&(_.runtimeWorkspaceLabel=p.runtimeWorkspaceLabel),p.runtimeWriteOwner!==void 0&&(_.runtimeWriteOwner=p.runtimeWriteOwner),p.runtimeAttachedClients!==void 0&&(_.runtimeAttachedClients=p.runtimeAttachedClients),p.machineNickname!==void 0&&p.machineNickname!==x.machineNickname&&(_.machineNickname=p.machineNickname),p.version!==void 0&&(_.version=p.version),p.serverVersion!==void 0&&(_.serverVersion=p.serverVersion),p.versionMismatch===!0&&(_.versionMismatch=!0),Object.keys(_).length>0){const j=Tn(x,p,{...x,..._,_lastUpdate:n});i.set(p.id,Cr(x,j,n))}else Cr(x,{...x,_lastUpdate:n},n)}else{const _=p.timestamp||n,j=x._lastUpdate||x.timestamp||0;if(_>=j){const I=(y=p.chats)!=null&&y.length?p.chats:x.chats,k=Io(x.childSessions,p.childSessions),v=da(p.activeChat,x.activeChat),b=Tn(x,p,{...x,...p,chats:I,childSessions:k,activeChat:v,_lastUpdate:n});i.set(p.id,Cr(x,b,n))}else(w=p.chats)!=null&&w.length&&!((A=x.chats)!=null&&A.length)&&i.set(p.id,{...x,chats:p.chats})}}const c=new Set(e.map(p=>p.id)),l=new Set,u=new Set;for(const p of e){const x=p.daemonId||((m=p.id)==null?void 0:m.split(":")[0]);x&&l.add(x),x&&p.type!=="adhdev-daemon"&&u.add(x)}for(const[p,x]of i){const h=x.daemonId||p.split(":")[0];if(!l.has(h))continue;if(a.has(h)&&!c.has(p)){i.delete(p);continue}const S=n-(x._lastUpdate||x.timestamp||0);(x.transport==="pty"&&u.has(h)&&!c.has(p)&&S>1e4||x.transport==="acp"&&u.has(h)&&!c.has(p)&&S>1e4||x.transport==="cdp-page"&&u.has(h)&&!c.has(p)&&S>3e4)&&i.delete(p)}for(const[p,x]of i){const h=x.daemonId||p.split(":")[0];if(l.has(h)&&x.transport&&!u.has(h))continue;n-(x._lastUpdate||x.timestamp||0)>3e5&&x.status!=="online"&&i.delete(p)}return Array.from(i.values())}function Nd(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 Cd({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,f]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const g=o.useCallback((x,h)=>{n(S=>{let _=!1;const j=S.map(I=>I.id!==x||I.chats===h?I:(_=!0,{...I,chats:h}));return _?j:S})},[]),y=o.useCallback((x,h)=>{n(S=>{const _=S.length===0?x:Sd(x,S,h),j=!Nd(S,_);return j&&Ds.record({kind:"dashboard.entries_applied",payload:{incoming:Co(x),next:Co(_)}}),j?_:S})},[]),w=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:y,markLoaded:w,getIdes:()=>d.current}),[y,w]),m=s,p=o.useMemo(()=>({ides:r,updateRouteChats:g,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(m==null?void 0:m.wsStatus)??"connected",isConnected:(m==null?void 0:m.isConnected)??!0,connectionStates:(m==null?void 0:m.connectionStates)??{},connectionTransports:(m==null?void 0:m.connectionTransports)??{},showReconnected:(m==null?void 0:m.showReconnected)??!1,retryConnection:m==null?void 0:m.retryConnection,isP2PActive:(m==null?void 0:m.isP2PActive)??!1,p2pStates:(m==null?void 0:m.p2pStates)??{},userRole:m==null?void 0:m.userRole,userName:u,setUserName:f}),[r,g,a,c,m==null?void 0:m.wsStatus,m==null?void 0:m.isConnected,m==null?void 0:m.connectionStates,m==null?void 0:m.connectionTransports,m==null?void 0:m.showReconnected,m==null?void 0:m.retryConnection,m==null?void 0:m.isP2PActive,m==null?void 0:m.p2pStates,m==null?void 0:m.userRole,u]);return t.jsx($i.Provider,{value:A,children:t.jsx(Ei.Provider,{value:p,children:e})})}function ws(){return o.useContext(Ei)}function lr(){return o.useContext($i)}function Ki(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(),f=a(l),d=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const f={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(f.Authorization=`Bearer ${d}`);const g=a(l),y=new AbortController,w=setTimeout(()=>y.abort(),15e3);try{const A=await fetch(g,{...u,headers:f,signal:y.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const m=await A.json().catch(()=>({error:A.statusText}));throw new Error(m.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),execTerminal:(l,u,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:f})}),sendAgentMessage:(l,u,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Id=Ki({baseUrl:"http://localhost:3847"}),Ad=o.createContext(Id);function Md({client:e,children:s}){return t.jsx(Ad.Provider,{value:e,children:s})}const Td={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Bi=o.createContext(Td);function Ld({value:e,children:s}){return t.jsx(Bi.Provider,{value:e,children:s})}function Tt(){return o.useContext(Bi)}function Rd(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 _d(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Oi(e){return e?Rd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),_d(e.content)]):""}const Fe={size:18};function Wi({size:e=Fe.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 Ta({size:e=Fe.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 es({size:e=Fe.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 La({size:e=Fe.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 Pd({size:e=Fe.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 Dd({size:e=Fe.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 Hi({size:e=Fe.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 Ed({size:e=Fe.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 pn({size:e=Fe.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 Fi({size:e=Fe.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 $d({size:e=Fe.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 ts({size:e=Fe.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 Pt({size:e=Fe.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 Ra({size:e=Fe.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 Kd({size:e=Fe.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 Es({size:e=Fe.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 Fs({size:e=Fe.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 js({size:e=Fe.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 dr({size:e=Fe.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 Ui({size:e=Fe.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 zi({size:e=Fe.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 Vi({size:e=Fe.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 Bd({size:e=Fe.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 fn({size:e=Fe.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 Od({size:e=Fe.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 _a({size:e=Fe.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 Gi({size:e=Fe.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 At({size:e=Fe.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 Wd({size:e=Fe.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 Hd({size:e=Fe.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 Fd({size:e=Fe.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 Ud({size:e=Fe.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 hn({size:e=Fe.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 zd({size:e=Fe.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 Vd({size:e=Fe.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 Gd({size:e=Fe.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 qd({size:e=Fe.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 Yd({size:e=Fe.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 Xd({size:e=Fe.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 Jd({size:e=Fe.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 Qd({size:e=Fe.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 Zd({size:e=Fe.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 eu({size:e=Fe.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 tu({size:e=Fe.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 su({size:e=Fe.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 Mo(e){return!!e&&typeof e=="object"&&"text"in e}function Pa(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:Mo(i)?String(i.text||""):"").join(r):Mo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Da(e){return Pa(e,{normalizeWhitespace:!0})}const Ln=new Map;function To(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function ru(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Oi(s)}`}function Lo(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function qi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function nu(e,s,r){return Number(e.receivedAt||r[rn(e,s)]||0)||0}function Yi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function au(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Ir(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 Rn(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 Ro(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Yi(e)?t.jsx(Ia,{remarkPlugins:[Aa,Pi,Di],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Ar({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:Ro(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=Rn(r);return a?t.jsx("img",{src:a,alt:Ir(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Rn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Rn(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:Ir(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||Ir(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=Ir(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}),Ro(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 rn(e,s){const r=e,n=Pa(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 ou=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ia,{remarkPlugins:[Aa],children:s.text}),t.jsx("span",{className:"action-time",children:qi(s.timestamp)})]})},(e,s)=>e.log===s.log),iu=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,k,v;const u=(s.role||"").toLowerCase(),f=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),g=au(s.content)?s.content:null,y=!!(g!=null&&g.some(b=>b.type!=="text")),w=Pa(s.content,{joiner:`
4
- `});if(d==="thought"){const b=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(Fd,{size:13}),t.jsx("span",{children:b})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),y&&g?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Ar,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const b=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",$=typeof((v=s.meta)==null?void 0:v.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:b}),t.jsx("span",{children:$})]}),y&&g?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Ar,{parts:g,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:y&&g?t.jsx(Ar,{parts:g,renderAsPreformatted:!1}):w.slice(0,100)});const A=s.meta,p=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",x=w,h=!1,S=x,_=p,j=!_&&Yi(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(x||y||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||y?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:qi(r)})]}),(x||y)&&t.jsx("div",{className:"chat-markdown",children:y&&g?t.jsx(Ar,{parts:g,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:S}):j?t.jsx(Ia,{remarkPlugins:[Aa,Pi,Di],children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),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),cu=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:f,onLoadMore:d,isLoadingMore:g,hasMoreHistory:y,hiddenLiveCount:w=0,loadError:A,scrollToBottomRequestNonce:m},p){const x=o.useRef(null),h=o.useRef(null),S=o.useRef(null),_=o.useRef(0),j=o.useRef(""),I=o.useRef(!1),k=o.useRef(null),v=o.useRef(!1),b=o.useRef(null),$=o.useRef(!1),[L,T]=o.useState(new Set),P=o.useRef(!1),K=o.useRef(!1),G=()=>{const V=x.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<200:!0},N=o.useCallback((V="auto")=>{const pe=x.current;pe&&pe.scrollTo({top:pe.scrollHeight,behavior:V})},[]),R=o.useCallback(()=>{var oe;const V=x.current,pe=(oe=window.getSelection)==null?void 0:oe.call(window);if(!V||!pe||pe.rangeCount===0||pe.isCollapsed){$.current=!1;return}const W=pe.anchorNode,J=pe.focusNode;$.current=!!(W&&J&&V.contains(W)&&V.contains(J))},[]),z=ru(s),C=o.useCallback(()=>{const V=x.current;!V||!l||Ln.set(l,{top:V.scrollTop,fromBottom:Math.max(0,V.scrollHeight-V.scrollTop-V.clientHeight),messageFingerprint:z})},[l,z]),D=o.useCallback((V="auto")=>{k.current!=null&&cancelAnimationFrame(k.current),k.current=requestAnimationFrame(()=>{k.current=null,N(V)})},[N]);o.useEffect(()=>{const V=!I.current,pe=j.current!==l;if(j.current=l,V||pe){if(I.current=!0,P.current=!1,v.current=!0,!$.current){const J=l?Ln.get(l):null;J&&To(J,z)?requestAnimationFrame(()=>{const oe=x.current;oe&&(Lo(oe,J),K.current=!0)}):D("auto")}_.current=s.length;return}s.length>_.current?!P.current&&!$.current&&D("auto"):G()&&!P.current&&!$.current&&D("auto"),_.current=s.length},[z,l,c,s.length,D]),o.useEffect(()=>{m&&(P.current=!1,v.current=!0,K.current=!0,b.current!=null&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{v.current=!1,b.current=null},180),$.current||D("auto"))},[D,m]),o.useEffect(()=>()=>{C(),k.current!=null&&cancelAnimationFrame(k.current),b.current!=null&&window.clearTimeout(b.current)},[C]),o.useEffect(()=>{const V=h.current;if(!V)return;const pe=()=>{b.current!=null&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{v.current=!1,b.current=null},180)},W=new ResizeObserver(()=>{v.current&&($.current||(D("auto"),pe()))});return W.observe(V),()=>{W.disconnect(),b.current!=null&&(window.clearTimeout(b.current),b.current=null)}},[D,l]),o.useImperativeHandle(p,()=>({scrollToBottom:(V="smooth")=>{N(V)}}),[N]),o.useEffect(()=>{const V=x.current;if(!V)return;let pe;const W=()=>{clearTimeout(pe),pe=setTimeout(()=>{P.current=!G(),C()},50)};return V.addEventListener("scroll",W,{passive:!0}),()=>{V.removeEventListener("scroll",W),clearTimeout(pe)}},[C]),o.useEffect(()=>(document.addEventListener("selectionchange",R),()=>document.removeEventListener("selectionchange",R)),[R]);const O=o.useRef(0),F=o.useRef(!1);o.useEffect(()=>{const V=x.current;if(!V||!F.current||O.current===0)return;const pe=V.scrollHeight-O.current;pe>0&&(V.scrollTop=pe),C(),O.current=0,F.current=!1},[s.length,C]),o.useEffect(()=>{if(K.current||!l)return;const V=Ln.get(l),pe=x.current;if(!(!V||!pe)){if(!To(V,z)){N("auto"),K.current=!0;return}Lo(pe,V),K.current=!0}},[l,z,s.length,N]);const X=()=>{const V=x.current;V&&(O.current=V.scrollHeight),F.current=!0,d==null||d()},ne=o.useMemo(()=>{const V=s.map((oe,le)=>({type:"message",data:oe,index:le,ts:nu(oe,le,u)}));if(!r||r.length===0)return V;const pe=[...r].sort((oe,le)=>oe.timestamp-le.timestamp).map((oe,le)=>({type:"action",data:oe,index:le,ts:oe.timestamp})),W=[];let J=0;for(const oe of V){for(;J<pe.length&&oe.ts>0&&pe[J].ts<oe.ts;)W.push(pe[J++]);W.push(oe)}for(;J<pe.length;)W.push(pe[J++]);return W},[s,r,u]),ke=w>0||!!y,ge=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:x,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[g&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ke&&!g&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:X,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&w===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:ge})}),ne.length===0&&!ke&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ne.map(V=>{if(V.type==="action"){const Ce=V.data;return t.jsx(ou,{log:Ce},`action-${V.index}`)}const pe=V.data,W=V.index,J=rn(pe,W),oe=pe.receivedAt||u[J],le=`${l}-${J}`,me=L.has(le);return t.jsx(iu,{message:pe,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:me,onToggleTextExpanded:()=>T(Ce=>{const ce=new Set(Ce);return me?ce.delete(le):ce.add(le),ce})},`msg-${J}`)}),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:S})]})})}),lu=o.memo(cu,(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),du="modulepreload",uu=function(e){return"/"+e},_o={},mu=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=uu(u),u in _o)return;_o[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const g=document.createElement("link");if(g.rel=f?"stylesheet":du,f||(g.as="script"),g.crossOrigin="",g.href=u,l&&g.setAttribute("nonce",l),document.head.appendChild(g),f)return new Promise((y,w)=>{g.addEventListener("load",y),g.addEventListener("error",()=>w(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 Po=!1;const Xi=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1,sizingMode:n="measured"},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),d=o.useRef(!1),g=o.useRef(!1),y=()=>{const w=i.current;if(w){f.current&&(w.clear(),f.current=!1);for(const A of u.current)w.write(A);u.current=[],d.current&&(w.fit(),d.current=!1),g.current&&(w.bumpResize(),g.current=!1)}};return o.useImperativeHandle(a,()=>({write:w=>{i.current?i.current.write(w):u.current.push(w)},clear:()=>{i.current?i.current.clear():(u.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],f.current=!0)},resize:(w,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(w,A)},fit:()=>{i.current?i.current.fit():d.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():g.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{y()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return mu(()=>import("./terminal-NRPEa5lD.js"),__vite__mapDeps([0,1,2])).then(A=>{Po||(Po=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||l(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{w=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,fontSize:s,readOnly:r,sizingMode: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"}})});Xi.displayName="CliTerminal";function Mr({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 Do({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 pu({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,f=a.width/a.height;let d,g,y,w;u>f?(d=a.width,g=a.width/u,y=0,w=(a.height-g)/2):(g=a.height,d=a.height*u,y=(a.width-d)/2,w=0);const A=a.left-i.left+y+d*e.nx,m=a.top-i.top+w+g*e.ny,p=Math.max(8,Math.min(i.width-8,A)),x=Math.max(8,Math.min(i.height-8,m));return t.jsxs("div",{style:{position:"absolute",left:p-8,top:x-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 fu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:g,mobileFillZoom:y,onZoomOut:w,onZoomReset:A,onZoomIn:m,transportType:p,screenshotUsage:x,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[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(S=>!S),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children: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:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{u(S)},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(S=>!S),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:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),p==="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"}),p==="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"}),x&&x.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.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:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[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: ",d<=(g?y:1)+.01?g?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:S=>{S.stopPropagation(),w()},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:S=>{S.stopPropagation(),A()},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:g?"FILL":"FIT"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),m()},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 hu({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 xu(){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 Eo(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 xr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!xu())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,Eo(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,Eo(s[c])]))}),r.current=s})}function bu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:g,lastWheelTimeRef:y,onAction:w,setLastActionStatus:A,spawnRippleFromNormalized:m,clampPan:p,isMobile:x,mobileFillZoom:h}){const[S,_]=o.useState(null),j=o.useRef(null),I=o.useRef(null),k=o.useRef(null),v=o.useRef(!1),b=o.useRef(null),$=o.useRef(0),L=o.useRef(null),T=o.useRef(1),P=o.useRef({x:0,y:0}),K=o.useRef(!1),G=o.useRef(n),N=o.useRef(w),R=30,z=550,C=18,D=60,O=400,F=12,X=()=>{if(j.current)return;const ge={nx:.5,ny:.5};j.current=ge,_(ge)};return o.useEffect(()=>{G.current=n,n==="mouse"&&X()},[n]),o.useEffect(()=>{N.current=w},[w]),o.useEffect(()=>{const ge=e.current;if(!ge)return;const V=me=>{if(!r.current)return null;const Ce=r.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(me.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(me.clientY-Ce.top)/Ce.height))}},pe=(me,Ce)=>{if(!r.current)return{dnx:0,dny:0};const ce=r.current,xe=ce.getBoundingClientRect(),te=ce.naturalWidth||xe.width,ue=ce.naturalHeight||xe.height,se=te/ue,Se=xe.width/xe.height;let we,Re;return se>Se?(we=xe.width,Re=xe.width/se):(Re=xe.height,we=xe.height*se),{dnx:me/we,dny:Ce/Re}},W=(me,Ce,ce)=>{if(ce<=1.05)return;const xe=-(me-.5)*100,te=-(Ce-.5)*100,ue=p(xe,te,ce);(Math.abs(ue.x-l.current)>.1||Math.abs(ue.y-u.current)>.1)&&(f(ue.x),d(ue.y),l.current=ue.x,u.current=ue.y)},J=me=>{const Ce=s.current;if(Ce&&me.target instanceof Node&&Ce.contains(me.target))me.preventDefault();else return;if(me.touches.length===1){const ce=me.touches[0];I.current={x:ce.clientX,y:ce.clientY,time:Date.now()},k.current={x:ce.clientX,y:ce.clientY},K.current||(v.current=!1),b.current=setTimeout(()=>{if(!v.current&&!K.current)if(v.current=!0,G.current==="mouse"){const xe=j.current||{nx:.5,ny:.5};A("Right Click"),m(xe.nx,xe.ny,"right"),N.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=V(ce);xe&&(A("Right Click"),m(xe.nx,xe.ny,"right"),N.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(me.touches.length===2){b.current&&clearTimeout(b.current),v.current=!0,K.current=!0;const ce=me.touches[1].clientX-me.touches[0].clientX,xe=me.touches[1].clientY-me.touches[0].clientY;L.current=Math.sqrt(ce*ce+xe*xe),T.current=c.current,P.current={x:(me.touches[0].clientX+me.touches[1].clientX)/2,y:(me.touches[0].clientY+me.touches[1].clientY)/2}}},oe=me=>{const Ce=s.current;if(Ce&&me.target instanceof Node&&Ce.contains(me.target)&&me.preventDefault(),me.touches.length===1&&k.current){const ce=me.touches[0],xe=ce.clientX-k.current.x,te=ce.clientY-k.current.y;if(!v.current&&I.current){const ue=ce.clientX-I.current.x,se=ce.clientY-I.current.y;Math.sqrt(ue*ue+se*se)>8&&(v.current=!0,b.current&&clearTimeout(b.current))}if(v.current)if(G.current==="mouse"){const ue=pe(xe,te),se=j.current||{nx:.5,ny:.5},Se=Math.max(0,Math.min(1,se.nx+ue.dnx)),we=Math.max(0,Math.min(1,se.ny+ue.dny));j.current={nx:Se,ny:we},_({nx:Se,ny:we}),A(`Cursor: ${Math.round(Se*100)}%, ${Math.round(we*100)}%`),W(Se,we,c.current);const Re=Date.now();Re-y.current>=30&&(y.current=Re,N.current("input_mouseMoved",{nx:Se,ny:we}).catch(()=>{}))}else if(c.current>1){const ue=s.current;if(ue){const se=ue.clientWidth,Se=ue.clientHeight,we=l.current+xe/se*100,Re=u.current+te/Se*100,M=p(we,Re,c.current);f(M.x),d(M.y),l.current=M.x,u.current=M.y}}else{const ue=V(ce);if(ue){const se=Date.now();se-y.current>=40&&(y.current=se,A("Scroll"),N.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-te*2.5)}).catch(()=>{}))}}k.current={x:ce.clientX,y:ce.clientY};return}if(me.touches.length===2&&L.current!==null){const ce=me.touches[1].clientX-me.touches[0].clientX,xe=me.touches[1].clientY-me.touches[0].clientY,ue=Math.sqrt(ce*ce+xe*xe)/L.current,se=(me.touches[0].clientX+me.touches[1].clientX)/2,Se=(me.touches[0].clientY+me.touches[1].clientY)/2,we=se-P.current.x,Re=Se-P.current.y,M=Math.abs(ue-1)>.03;if(G.current==="mouse"){if(M){const he=Math.max(i,Math.min(5,T.current*ue));g(he),c.current=he}else if(Math.abs(we)>2||Math.abs(Re)>2){const he=j.current||{nx:.5,ny:.5},ye=Date.now();ye-y.current>=30&&(y.current=ye,A("Scroll"),N.current("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(-we*3),deltaY:Math.round(-Re*3)}).catch(()=>{}))}}else{const he=Math.max(i,Math.min(5,T.current*ue));g(he),c.current=he;const ye=s.current;if(ye&&he>1){const ee=ye.clientWidth,je=ye.clientHeight,Te=l.current+we/ee*100,Oe=u.current+Re/je*100,Pe=p(Te,Oe,he);f(Pe.x),d(Pe.y),l.current=Pe.x,u.current=Pe.y}}P.current={x:se,y:Se}}},le=me=>{var Ce;if(b.current&&clearTimeout(b.current),L.current=null,me.touches.length===1&&K.current){const ce=me.touches[0];I.current={x:ce.clientX,y:ce.clientY,time:Date.now()},k.current={x:ce.clientX,y:ce.clientY},v.current=!0;return}if(me.touches.length===0){if(K.current){K.current=!1,v.current=!1;return}if(me.changedTouches.length===1){const ce=me.changedTouches[0],xe=Date.now(),te=xe-(((Ce=I.current)==null?void 0:Ce.time)||0),ue=I.current?ce.clientX-I.current.x:0,se=I.current?ce.clientY-I.current.y:0,Se=Math.sqrt(ue*ue+se*se);if(G.current==="mouse"){if(te<R||te>z||Se>C){v.current=!1;return}const we=j.current||V(ce);we&&(A(`Click: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),m(we.nx,we.ny,"left"),N.current("input_click",{...we}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(te<D||te>O||Se>F){v.current=!1;return}const we=V(ce);if(!we)return;xe-$.current<300?(A("Double tap"),m(we.nx,we.ny,"double"),N.current("input_click",{...we,clickCount:2}).catch(()=>{}),$.current=0):(A(`Tap: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),m(we.nx,we.ny,"left"),N.current("input_click",{...we}).catch(()=>{}),$.current=xe)}}v.current=!1}};return ge.addEventListener("touchstart",J,{passive:!1}),ge.addEventListener("touchmove",oe,{passive:!1}),ge.addEventListener("touchend",le,{passive:!1}),()=>{ge.removeEventListener("touchstart",J),ge.removeEventListener("touchmove",oe),ge.removeEventListener("touchend",le),b.current&&clearTimeout(b.current)}},[e,s,r,i,c,l,u,f,d,g,y,A,m,p]),{cursorPos:S,cursorPosRef:j,handleToggleInputMode:()=>{a(ge=>{const V=ge==="touch"?"mouse":"touch";return V==="mouse"&&X(),V})},handleZoomReset:()=>{const ge=x?h:1;g(ge),c.current=ge,f(0),d(0),l.current=0,u.current=0}}}function Ji({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),[f,d]=o.useState(null),[g,y]=o.useState(""),[,w]=o.useState(!1),[A,m]=o.useState([]),p=o.useRef(0),[x,h]=o.useState(!1),[S,_]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,k]=o.useState(j?"mouse":"touch"),[v,b]=o.useState(1),$=o.useRef(!1),[L,T]=o.useState(1),[P,K]=o.useState(0),[G,N]=o.useState(0);xr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:L,panX:P,panY:G,isMenuOpen:x,isImeOpen:S});const R=o.useRef(0),z=o.useRef(L),C=o.useRef(P),D=o.useRef(G);o.useEffect(()=>{z.current=L},[L]),o.useEffect(()=>{C.current=P},[P]),o.useEffect(()=>{D.current=G},[G]),o.useEffect(()=>{var te;(te=c.current)==null||te.focus()},[]);const O=r==="connected",F=n,X=O?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ne=O?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!j||$.current||!F)return;const te=u.current,ue=l.current;if(!te||!ue)return;const se=()=>{const Se=ue.clientWidth,we=ue.clientHeight,Re=te.naturalWidth,M=te.naturalHeight;if(!Re||!M||!Se||!we)return;const he=Math.min(Se/Re,we/M),ee=Math.max(Se/Re,we/M)/he;ee>1.01&&(b(ee),T(ee),z.current=ee),$.current=!0};te.complete&&te.naturalWidth?se():te.addEventListener("load",se,{once:!0})},[F,j]);const ke=.5;o.useEffect(()=>{L<=ke&&(K(0),N(0))},[L,ke]);const ge=(te,ue,se)=>{if(se<=ke)return{x:0,y:0};const Se=(se-1)/(2*se)*100,we=(se-1)/(2*se)*100;return{x:Math.max(-Se,Math.min(Se,te)),y:Math.max(-we,Math.min(we,ue))}},V=(te,ue)=>{if(!u.current)return null;const se=u.current.getBoundingClientRect();return!se.width||!se.height?null:{nx:Math.max(0,Math.min(1,(te-se.left)/se.width)),ny:Math.max(0,Math.min(1,(ue-se.top)/se.height))}},pe=(te,ue,se)=>{const Se=l.current;if(!Se)return;const we=Se.getBoundingClientRect(),Re=++p.current;m(M=>[...M,{id:Re,x:te-we.left,y:ue-we.top,type:se}]),setTimeout(()=>m(M=>M.filter(he=>he.id!==Re)),600)},W=(te,ue,se)=>{const Se=u.current,we=l.current;if(!Se||!we)return;const Re=Se.getBoundingClientRect(),M=we.getBoundingClientRect(),he=Se.naturalWidth||Re.width,ye=Se.naturalHeight||Re.height,ee=he/ye,je=Re.width/Re.height;let Te,Oe,Pe,Ve;ee>je?(Te=Re.width,Oe=Re.width/ee,Pe=0,Ve=(Re.height-Oe)/2):(Oe=Re.height,Te=Re.height*ee,Pe=(Re.width-Te)/2,Ve=0);const Ge=Re.left-M.left+Pe+Te*te,ft=Re.top-M.top+Ve+Oe*ue,et=++p.current;m(it=>[...it,{id:et,x:Ge,y:ft,type:se}]),setTimeout(()=>m(it=>it.filter(Qe=>Qe.id!==et)),600)},J=async te=>{var se;const ue=V(te.clientX,te.clientY);if(ue){d(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),pe(te.clientX,te.clientY,"left"),(se=c.current)==null||se.focus();try{const Se=await e("input_click",{nx:ue.nx,ny:ue.ny});Se!=null&&Se.success||s(`❌ Click failed: ${Se==null?void 0:Se.error}`)}catch(Se){s(`❌ Click error: ${Se.message||Se}`)}}},oe=async(te,ue,se,Se=0)=>{try{await e("input_key",{type:se?"char":"keyDown",key:te,code:ue,text:se?te:void 0,unmodifiedText:se?te:void 0,modifiers:Se})}catch(we){s(`❌ Key error: ${we.message||we}`)}},le=async te=>{if(te.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(te.key)&&te.preventDefault();let se=0;te.altKey&&(se|=1),te.ctrlKey&&(se|=2),te.metaKey&&(se|=4),te.shiftKey&&(se|=8),d(`Key: ${te.key}`),await oe(te.key,te.code,te.key.length===1,se)},me=async te=>{if(te.key==="Enter"){if(te.nativeEvent.isComposing)return;if(g){const ue=g;y(""),d(`IME Sent: ${ue}`);try{const se=await e("input_type",{text:ue});se!=null&&se.success||s(`❌ IME error: ${se==null?void 0:se.error}`)}catch(se){s(`❌ IME error: ${se.message}`)}}else d("Key: Enter"),await oe("Enter","Enter",!1)}};o.useEffect(()=>{const te=c.current;if(!te)return;const ue=se=>{var Se;if((Se=u.current)!=null&&Se.contains(se.target)){se.preventDefault();const we=Date.now();if(we-R.current<40)return;R.current=we;const Re=V(se.clientX,se.clientY);if(!Re)return;d(`Scroll: ${Math.round(se.deltaY)}`),e("input_wheel",{nx:Re.nx,ny:Re.ny,deltaX:Math.round(se.deltaX),deltaY:Math.round(se.deltaY)}).catch(()=>{})}};return te.addEventListener("wheel",ue,{passive:!1}),()=>te.removeEventListener("wheel",ue)},[e]);const{cursorPos:Ce,handleToggleInputMode:ce,handleZoomReset:xe}=bu({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:k,minZoom:ke,zoomRef:z,panXRef:C,panYRef:D,setPanX:K,setPanY:N,setZoom:T,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:W,clampPan:ge,isMobile:j,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:le,onContextMenu:te=>te.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?t.jsx("img",{ref:u,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${P}%, ${G}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:J,onContextMenu:te=>te.preventDefault(),onDragStart:te=>te.preventDefault()}):t.jsx(hu,{waitingLabel:X,waitingHint:ne,transportType:i}),I==="mouse"&&F&&t.jsx(pu,{cursorPos:Ce,viewportRef:l,imgRef:u}),A.map(te=>{const se={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[te.type];return t.jsxs("div",{style:{position:"absolute",left:te.x,top:te.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${se}, 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(${se}, 0.9)`,boxShadow:`0 0 12px rgba(${se}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},te.id)})]}),t.jsx(fu,{inputMode:I,onToggleInputMode:ce,isImeOpen:S,setIsImeOpen:_,isMenuOpen:x,setIsMenuOpen:h,imeText:g,setImeText:y,handleImeSubmit:me,isConnActive:O,zoom:L,isMobile:j,mobileFillZoom:v,onZoomOut:()=>T(te=>Math.max(.5,te-.25)),onZoomReset:xe,onZoomIn:()=>T(te=>Math.min(5,te+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),t.jsx("style",{children:`
5
- @keyframes slideUp {
6
- from { opacity: 0; transform: translateY(6px); }
7
- to { opacity: 1; transform: translateY(0); }
8
- }
9
- @keyframes slideUpSidebar {
10
- from { opacity: 0; transform: translateY(6px); }
11
- to { opacity: 1; transform: translateY(0); }
12
- }
13
- @keyframes click-ripple-ring {
14
- 0% { transform: scale(0.3); opacity: 1; }
15
- 100% { transform: scale(2.2); opacity: 0; }
16
- }
17
- @keyframes click-ripple-dot {
18
- 0% { transform: scale(1); opacity: 0.9; }
19
- 50% { transform: scale(1.8); opacity: 0.6; }
20
- 100% { transform: scale(0.5); opacity: 0; }
21
- }
22
- @keyframes remote-float {
23
- 0% { transform: translateY(0px); }
24
- 50% { transform: translateY(-7px); }
25
- 100% { transform: translateY(0px); }
26
- }
27
- `})]})}function Ct(e){return(typeof e=="string"?e.trim():"")||void 0}function Zt(e,s){const r=Ct(s);return r?`${e}:${r}`:void 0}function ss(e,s,r){const n=Zt(s,r),a=Ct(r);n&&e.push(n),a&&e.push(a)}function Ts(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Qi(e){return Ct(e.providerSessionId)||Ct(e.sessionId)||Ct(e.tabKey)||Ct(e.routeId)}function Ea(e){return Ts([Ct(e.providerSessionId),Ct(e.sessionId)])}function rs(e){const s=[];return ss(s,"provider",e.providerSessionId),ss(s,"session",e.sessionId),ss(s,"tab",e.tabKey),ss(s,"route",e.routeId),Ts(s)}function gu(e){const s=[];return Ct(e.providerSessionId)?(ss(s,"provider",e.providerSessionId),Ts(s)):Ct(e.sessionId)?(ss(s,"session",e.sessionId),Ts(s)):Ct(e.tabKey)?(ss(s,"tab",e.tabKey),Ts(s)):Ct(e.routeId)?(ss(s,"route",e.routeId),Ts(s)):[]}function $a(e){return Zt("provider",e.providerSessionId)||Zt("session",e.sessionId)||Zt("tab",e.tabKey)||Zt("route",e.routeId)||"unknown:"}function br(e){return Ea(e)[0]}function Zi(e){const s=Ct(e.providerSessionId),r=Ct(e.sessionId),n=Ct(e.tabKey),a=Ct(e.routeId),i=[Zt("provider",s),Zt("session",r),Zt("tab",n),Zt("route",a)].filter(u=>typeof u=="string"),c=rs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=$a({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Qi({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:br({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ur(e,s){const r=Zi(e);return gu(s).some(n=>r.lookupKeys.includes(n))}function xn(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 f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const ec=e=>xn(e);function yu(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Us(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 vu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...yu(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 nn(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,completionMarker:"",seenCompletionMarker:""}}function bn(e,s,r){const n=nn(e,s),a=Us(e),i=rs(e).map(A=>{var m;return(m=r==null?void 0:r.notificationStateBySessionId)==null?void 0:m.get(A)}).find(A=>!!A),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,f=a.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||f,g=n.inboxBucket==="working"||u,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:d,isWorking:g,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:f,inboxBucket:d?"needs_attention":g?"working":w?"task_complete":"idle"}}function wu(e,s,r){return bn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function tc({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Us(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(js,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const f=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(f),g=/^(reject|deny|delete|remove|abort)/.test(f),y=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":g?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!y?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:g?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)})})]})]})}const Ka="adhdev_controls_bar_visible",ua="adhdev:controlsbarvisibilitychange";function _n(e){if(!e)return!1;try{return e.getItem(Ka)==="1"}catch{return!1}}function $o(e,s){if(s)try{s.setItem(Ka,e?"1":"0")}catch{}}function Ko(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ua,{detail:{visible:e}}))}function sc(){const[e,s]=o.useState(()=>typeof window>"u"?!1:_n(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s(_n(window.localStorage))},i=c=>{c.key===Ka&&s(_n(window.localStorage))};return window.addEventListener(ua,a),window.addEventListener("storage",i),()=>{window.removeEventListener(ua,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&$o(a,window.localStorage),Ko(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&$o(i,window.localStorage),Ko(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var ju=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ku(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function Nt(e,s){if(ku(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":ju.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 rc(e){return Nt(e)==="generating"}function dt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Su(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 Pn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function gn(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 Nu(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 Cu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Iu(e){return Nu(e.trim().replace(/\.local$/i,""))}function Au(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function nc(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&&!Cu(c));if(r&&r!=="Unknown")return Iu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return Au(e)||nc(e,s)}function ac(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 oc(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 ks(e,s){return ac(e).join(" · ")}function mr(e){return e.transport==="pty"}function Ls(e){return e.transport==="acp"}function Mu(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:dt(e)}function Bo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=dt(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Tu(e){return Nt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Lu(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=Nt(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 Ru(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 _u(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&&Ru(s.receivedAt)||0}function Pu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ma(e){return Math.max(Pu(e),_u(e.activeChat))}function Du(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 Ba(e,s){return Du(ma(e),ma(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const ic="adhdev_notification_prefs",Oo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Eu(){try{const e=localStorage.getItem(ic);if(e){const s=JSON.parse(e);return{...Oo,...s}}}catch{}return{...Oo}}function $u(e){try{localStorage.setItem(ic,JSON.stringify(e))}catch{}}let Qt=Eu(),Gr=[];function Ku(){Gr.forEach(e=>e())}function Bu(e){Qt={...Qt,...e},$u(Qt),Ku()}function Ou(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Gr.push(r),()=>{Gr=Gr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Bu(r)},[]);return[{...Qt},s]}function rr(e){if(!Qt.globalEnabled)return!1;switch(e){case"disconnect":return Qt.disconnectAlert;case"completion":return Qt.completionAlert;case"approval":return Qt.approvalAlert;case"browser":return Qt.browserNotifications;default:return!0}}const Wu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function cc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function lc(){return"Notification"in window&&Notification.permission==="granted"}let ls=null;async function Hu(){if(ls!==null)return ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ls=!!await e.pushManager.getSubscription(),ls):(ls=!1,!1)}catch{return ls=!1,!1}}function pa(e,s,r){if(lc())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 Fu(e,s={}){const r={...Wu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Hu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,pa(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!lc())&&rr("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,Nt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const f=n.current.get(u.id),d=Nt(u.status,{activeModal:u.activeModal}),g=u.name||u.id;if(r.onApproval&&rr("approval")&&d==="waiting_approval"&&f!=="waiting_approval"){const y=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${g} — Approval needed`,y.slice(0,120),`approval-${u.id}`)}r.onComplete&&rr("completion")&&rc(f)&&d==="idle"&&c(`✅ ${g} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&f!=="error"&&c(`⚠️ ${g} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,d)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Uu=/^(run|approve|accept|yes|allow|always)/,zu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Vu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Oa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Gu(e){const s=Oa(e).toLowerCase();return Uu.test(s)?"primary":Vu.test(s)?"danger":"default"}function qu(e){return zu.test(Oa(e).toLowerCase())?"approve":"reject"}function Yu(e){return e.map((s,r)=>({label:Oa(s),variant:Gu(s),action:qu(s),button:s,buttonIndex:r}))}function Xu(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 Ju(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Qu(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 Zu{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(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 A,m;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,f=(u==null?void 0:u.type)||"";let d=dt(f);const g=this.resolveOwningDaemon(s);if(g){const p=_t(g,{fallbackId:g.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let y="",w="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";y=`✅ ${d} agent task completed${p}`,w="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(y=`⚡ ${d} approval needed`,w="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Xu(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(m=s.modalButtons)!=null&&m.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const x=this.resolveActionFn,h=Yu(s.modalButtons).map(j=>({label:j.label,variant:j.variant,onClick:()=>{x(p,"resolve_action",{action:j.action,button:j.button,buttonIndex:j.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Ju(d,s.modalMessage,y),_=Date.now();this.emitToast({id:_,message:S,type:w,timestamp:_,targetKey:n||p,actions:h,duration:15e3}),y=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";y=`⚠️ ${d} agent is taking a long time${p}`,w="warning",rr("browser")&&!document.hasFocus()&&pa(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",x=s.requestId,h=s.orgId;if(y=`👁️ ${p} wants to view your session`,w="warning",x&&h&&this.viewRequestRespondFn){const S=Date.now(),_=Qu(h,x,this.viewRequestRespondFn,(j,I)=>console.error(`[EventManager] ${j} view request failed:`,I));this.emitToast({id:S,message:y,type:w,timestamp:S,actions:_,duration:3e4}),y=""}rr("browser")&&!document.hasFocus()&&pa("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else s.event==="team:view_request_approved"?(y="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(y=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(y){const p=Date.now();this.emitToast({id:p,message:y,type:w,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new Zu,Wo=new Map;function $s(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function em(e){return!$s(e)||!$s(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Tr(e){return!$s(e)||!$s(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function qs(e){if(!(!$s(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Lr(e){return $s(e)&&e.success===!1}function tm(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";nt.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";nt.showToast(n.notification.body,a)}}}function sm(e,s){return e&&Rs(e.currentValue)?e.currentValue:s}function rm(e,s){return Rs(s)?Rs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function nm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Rs(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Rs(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Rs(a)?a:void 0}function qr(e,s){return e.options||s[e.id]||[]}const am={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function om(e,s,r){var n;return((n=am[s])==null?void 0:n.has(r.id))===!0}function Wa(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!om(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Dn(e,s){return{value:s}}function im(e,s,r){var a;return r?((a=qr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const cm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function lm({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Tt(),u=`${e}:${s||n}`,f=cm[n]||"#94a3b8",[d,g]=o.useState({}),y=o.useRef({}),w=o.useRef(c);y.current=d,w.current=c;const A=o.useRef(0),m={};for(const R of i||[])R.defaultValue!==void 0&&(m[R.id]=R.defaultValue);const p={...m,...c||{},...Date.now()<A.current?d:{}};o.useEffect(()=>{c&&Date.now()>A.current&&g({})},[c]);const[x,h]=o.useState(Wo.get(u)||{}),[S,_]=o.useState(null),[j,I]=o.useState(null),k=o.useCallback(async(R,z={})=>{const C={...z,...s&&{targetSessionId:s}};return await l(e,R,C)},[e,s,l]),v=o.useCallback(async(R,z={})=>{const C=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await k("invoke_provider_script",{...C,scriptName:R,...z})},[k,n,r,s]),b=o.useCallback((R,z,C)=>{const D=sm(C,z);g(O=>({...O,[R.id]:D})),tm(C==null?void 0:C.effects)},[]),$=o.useCallback((R,z)=>{g(C=>{const D={...C};return z===void 0?delete D[R.id]:D[R.id]=z,D}),A.current=0},[]);if(!i||i.length===0)return null;const L=Wa(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const T=async R=>{if(S===R.id){_(null);return}if(qr(R,x).length>0){_(R.id);return}if(R.dynamic&&R.listScript){I(R.id);try{const C=await v(R.listScript,{}),D=em(C);if(!D){const X=qs(C);X&&nt.showToast(X,"warning");return}const O=D.options;h(X=>{const ne={...X,[R.id]:O};return Wo.set(u,ne),ne});const F=nm(R.id,{localOverrideUntil:A.current,localValues:y.current,controlValues:w.current,defaultValues:m});if(rm(F,D.currentValue)){const X=D.currentValue;g(ne=>({...ne,[R.id]:X}))}_(R.id)}catch(C){const D=C instanceof Error?C.message:`Could not load ${R.label}`;nt.showToast(D,"warning")}finally{I(null)}}},P=async(R,z)=>{_(null);const C=(c==null?void 0:c[R.id])??m[R.id];g(D=>({...D,[R.id]:z})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const D=await v(R.setScript,Dn(R,z)),O=Tr(D);if(O&&!O.ok||Lr(D))throw new Error((O==null?void 0:O.error)||qs(D)||`Could not update ${R.label}`);b(R,z,O)}catch(D){$(R,C);const O=D instanceof Error?D.message:`Could not update ${R.label}`;nt.showToast(O,"warning")}},K=async R=>{const z=qr(R,x).map(ne=>ne.value);if(z.length===0)return;const C=String(p[R.id]||""),O=(z.indexOf(C)+1)%z.length,F=z[O];if(typeof F!="string")return;const X=(c==null?void 0:c[R.id])??m[R.id];g(ne=>({...ne,[R.id]:F})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const ne=await v(R.setScript,Dn(R,F)),ke=Tr(ne);if(ke&&!ke.ok||Lr(ne))throw new Error((ke==null?void 0:ke.error)||qs(ne)||`Could not update ${R.label}`);b(R,F,ke)}catch(ne){$(R,X);const ke=ne instanceof Error?ne.message:`Could not update ${R.label}`;nt.showToast(ke,"warning")}},G=async R=>{const C=!p[R.id],D=(c==null?void 0:c[R.id])??m[R.id];g(O=>({...O,[R.id]:C})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const O=await v(R.setScript,Dn(R,C)),F=Tr(O);if(F&&!F.ok||Lr(O))throw new Error((F==null?void 0:F.error)||qs(O)||`Could not update ${R.label}`);b(R,C,F)}catch(O){$(R,D);const F=O instanceof Error?O.message:`Could not update ${R.label}`;nt.showToast(F,"warning")}},N=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const C=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(O=>typeof O=="string"&&O.trim().length>0);if(!window.confirm(C.join(`
29
-
30
- `)))return}const z=(c==null?void 0:c[R.id])??m[R.id];try{const C=await v(R.invokeScript),D=Tr(C);if(D&&!D.ok||Lr(C))throw new Error((D==null?void 0:D.error)||qs(C)||`Could not run ${R.label}`);D&&b(R,z??!0,D)}catch(C){$(R,z);const D=C instanceof Error?C.message:`Could not run ${R.label}`;nt.showToast(D,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${f}33`,background:`${f}12`,color:f},children:a}),L.map(R=>{const z=String(p[R.id]||""),C=im(R,x,z),D=S===R.id,O=j===R.id,F=qr(R,x),X="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(R.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${X} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${f}55`:"var(--border-default)",background:D?`${f}10`:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(R),title:R.label,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?"Loading…":C||R.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&F.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:R.label}),F.map(ne=>t.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:ne.value===z?`${f}14`:"transparent",color:ne.value===z?"var(--text-primary)":"var(--text-secondary)",borderLeft:ne.value===z?`2px solid ${f}`:"2px solid transparent"},title:ne.description||ne.label,onMouseEnter:ke=>{ke.currentTarget.style.background=`${f}10`},onMouseLeave:ke=>{ke.currentTarget.style.background=ne.value===z?`${f}14`:"transparent"},onClick:()=>void P(R,ne.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ne.label}),ne.value===z&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:f},children:"✓"})]},ne.value))]})]})]},R.id);case"cycle":return t.jsxs("button",{type:"button",className:`${X} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(R),title:`Click to cycle: ${F.map(ne=>ne.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:C||R.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return t.jsxs("button",{type:"button",className:`${X} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:z?`${f}44`:"var(--border-default)",background:z?`${f}14`:"var(--surface-tertiary)",color:z?f:"var(--text-muted)"},onClick:()=>void G(R),"aria-pressed":!!z,children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("button",{type:"button",className:`${X} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(R),children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&z?`${R.label}: ${z}`:R.label})]},R.id);case"display":return t.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:z?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?`${R.label}: ${z}`:R.label})]},R.id);default:return null}})]})})}function dm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=sc(),d=Wa(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!f?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(lm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function um({hasDraft:e,isBusy:s=!1}){return!e||s}const dc=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const f=o.useRef(null),[d,g]=o.useState(""),{isVisible:y,toggleVisibility:w}=sc();o.useEffect(()=>{g("")},[s]),o.useEffect(()=>{var m;l&&((m=f.current)==null||m.focus())},[s,l]);const A=async()=>{const m=d.trim();if(!m||a)return;await c(m)!==!1&&g("")};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 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":y?"Hide controls":"Show controls","aria-pressed":y,title:y?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:f,type:"text",placeholder:i||`Send message to ${r}...`,value:d,onChange:m=>g(m.target.value),onPaste:m=>{const p=m.clipboardData.getData("text");p&&g(x=>x+p),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),A()}},onBlur:m=>{if(window.innerWidth<768){const p=m.relatedTarget;if((p==null?void 0:p.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:()=>{A()},disabled:um({hasDraft:!!d.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.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:d.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})]})}),rt=e=>e.transport==="pty",Ks=(e,s)=>rt(e)?e.mode||"terminal":"chat",uc=(e,s)=>rt(e)&&Ks(e)==="terminal",Ze=e=>e.transport==="acp";function ns(e){return e.streamSource!=="agent-stream"}function is(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function mc(e){return e.machineName||""}function gr(e){return is(e)}function Wt(e){return e.agentType||""}function an(e){return e.hostIdeType||""}function Ha(e){return e.displayPrimary||e.agentName||"Agent"}function pc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function mm(e){return e.lastMessagePreview||e.displaySecondary||""}function fc(e){return[e.displaySecondary,mc(e)].filter(Boolean)}function Bs(e){return e.agentName||dt(Wt(e))}function pm(e){var s,r;if(!ns(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return dt(an(e)||Wt(e))}function hc(e){return ns(e)?e.sessionId:e.nativeSessionId}function Ho(e){return ns(e)?"native":e.tabKey}function fm(e){return e.sessionId}function hm(e,s){if(s)return ns(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function xm(e,s){const r=Wt(e),n=ns(e),a=rt(e)||Ze(e),i=n?a?Bs(e)||(s==null?void 0:s.cliName)||dt(an(e)||r):s!=null&&s.type?dt(s.type):dt(an(e)||r):Bs(e);return{isNativeConversation:n,isCli:rt(e),isAcp:Ze(e),isCliTerminal:uc(e),providerType:r,displayLabel:i,targetEntry:hm(e,s)}}function bm(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 ps(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||bm(s==null?void 0:s.receivedAt)||0}function fa(e,s=0){return ps(e)||e.lastUpdated||s||0}function xc(e){return ps(e)||e.lastUpdated||0}function bc(e,s,r=xc){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 ha(e){var r;const s=Nt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function gm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ha(e)&&!e.title.trim()}function ym(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ha(r))-Number(ha(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:bc(s,r)})[0]||null}function Ft(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=ym(a);return n?i&&gm(n)?i:n:i||r[0]||null}function as(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Fa(e){return br(e)||e.tabKey||e.routeId||null}function gc(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=Ft(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Fa(a):null}function yc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Hs(),c=is(e),l=mc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),g=Bs(e),y=pm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const m=Fa(e);m&&i(as(m))},[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:A,title:y,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:y})]}):t.jsxs("span",{className:"conversation-meta-chip",title:y,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:y})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(dr,{size:12}),t.jsx("span",{children:g})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(dr,{size:12}),t.jsx("span",{children:g})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(es,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(es,{size:12}),t.jsx("span",{children:l})]}))]})}function En(e,s){return`${e}:${s}`}function vm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Rr(e,s){vm()&&console.debug(`[subscription-manager] ${e}`,s)}class wm{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var f;const i=En(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 d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),Rr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const u=()=>{var y;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const g={type:"unsubscribe",topic:n.topic,key:n.key};Rr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=s.sendData)==null||y.call(s,r,g)};return u.initialSendAccepted=l,u}publish(s){const r=En(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ds.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),Ds.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=En(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Rr("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);Rr("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 os=new wm;function jm(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,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});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 km(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 on(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=km(u),g=jm(i,n),y=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=f.filter(p=>p.kind==="workspace"&&p.transport==="cdp-page"),A=f.filter(p=>p.kind==="agent"&&p.transport==="pty"),m=f.filter(p=>p.kind==="agent"&&p.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:w.some(p=>!!p.cdpConnected)});for(const p of w){const x=g.get(p.id),h=tr(p,x),S=(d.get(p.id)||[]).map(_=>tr(_,g.get(_.id)));r.push({id:`${n}:ide:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:p.id,workspace:h.workspace,terminals:0,childSessions:S,agents:S.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,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 p of A){const x=g.get(p.id),h=tr(p,x);r.push({id:`${n}:cli:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.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:p.id,cliName:h.providerName||h.providerType,mode:h.mode||(x==null?void 0:x.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,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,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 p of m){const x=g.get(p.id),h=tr(p,x);r.push({id:`${n}:acp:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.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:p.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,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,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 Sm=15e3,Nm=15e3,Cm=6e4,Im=1200,Fo=12,Am=8e3,Mm=4e3,$n=new Map,Kn=new Map,_r=new Set,nr=new Map;function Tm(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 Uo(e,s){const r=nr.get(e);!r||r.size===0||(nr.delete(e),r.forEach(n=>n(s)))}function Lm(e,s){return new Promise(r=>{const n=nr.get(e)||new Set;nr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&nr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function yr(){const{sendCommand:e,sendData:s}=Tt(),{injectEntries:r,getIdes:n}=lr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Cm,l=Kn.get(a)||0;if(!(i!=null&&i.force)&&_r.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=$n.get(a);if(u)return u;const f=(async()=>{if(s&&!_r.has(a)){const m=os.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},p=>{const x=n(),h=x.find(_=>_.id===a),S=on(p.status,{daemonId:a,existingDaemon:h,existingEntries:x,timestamp:p.timestamp});S.length>0&&r(S),Kn.set(a,Date.now()),Uo(a,!0)});if(m.initialSendAccepted?_r.add(a):_r.delete(a),!(i!=null&&i.force)&&m.initialSendAccepted&&await Lm(a,Im))return}const d=await e(a,"get_status_metadata"),g=Tm(d);if(!g)return;const y=n(),w=y.find(m=>m.id===a),A=on(g,{daemonId:a,existingDaemon:w,existingEntries:y,timestamp:g.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Kn.set(a,Date.now()),Uo(a,!0)})().finally(()=>{$n.delete(a)});return $n.set(a,f),f},[n,r,e,s])}function Rm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function _s(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:rt(e)||Ze(e)?{agentType:Wt(e)}:e.streamSource==="agent-stream"?{agentType:Wt(e)}:s}function pr(e){return e?gr(e):""}function Ys(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ua(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 _m(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 Pm=60,Dm=1e3;function vc(e={}){return e.isCliLike?Dm:Pm}function Em(e={}){return vc(e)}const vr=60,$m=1e3,za=12e4,Km=new Set(["generating","waiting_approval","starting","streaming","working"]),zo=new Map;function wc(e,s){return`${e}::${s}`}function xa(e=vr){return{liveMessages:[],cursor:kc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function jc(e){return Oi(e)}function kc(e,s=vr){return{knownMessageCount:e.length,lastMessageSignature:jc(e[e.length-1]),tailLimit:s}}function Pr(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 Bm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Om{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);Ye(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||os,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=xa(Math.max(0,s.tailLimit??vr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=r,a=kc(n,this.snapshot.cursor.tailLimit);Pr(this.snapshot.liveMessages)===Pr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}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}buildSubscribeRequest(){return{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}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},$m))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var s;this.clearPendingSubscribeRetry(),(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){this.clearPendingSubscribeRetry();const r=Bm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:jc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Pr(this.snapshot.liveMessages)===Pr(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 Sc(e){const s=wc(e.daemonId,e.sessionId),r=zo.get(s);if(r)return r.updateOptions(e),r;const n=new Om(e);return zo.set(s,n),n}function Wm(e,s){return{...e,loadHistoryPage:s}}function Hm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Fm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Km.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??za)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Um(e=za){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function zm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Fm(a,s))continue;const i=gr(a),c=a.sessionId||"";if(!i||!c)continue;const l=wc(i,c);if(r.has(l))continue;r.add(l);const u=br(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Hm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Vm(e,s){const{sendData:r,sendCommand:n}=Tt(),a=(s==null?void 0:s.enabled)!==!1,i=gr(e),c=e.sessionId||"",l=br(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(s==null?void 0:s.tailLimit)??vr),d=o.useMemo(()=>!a||!i||!c?null:Sc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[g,y]=o.useState(()=>(d==null?void 0:d.getSnapshot())||xa(f));o.useEffect(()=>{if(!d){y(xa(f));return}d.retain(),y(d.getSnapshot());const A=d.subscribe(m=>{y(m)});return()=>{A(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),y(d.getSnapshot()))},[e.messages,d]);const w=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const A=e.agentType,m=await n(i,"chat_history",{agentType:A,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),p=m&&typeof m=="object"&&"result"in m?m.result||{}:m||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Wm(g,w),[w,g])}function Gm(e,s){const{sendData:r}=Tt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??vr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??za)),c=Um(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(g=>g+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>zm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(g=>Sc({...g,sendData:r,tailLimit:a}));return d.forEach(g=>g.retain()),()=>{d.forEach(g=>g.release())}},[f.signature,n,r,a])}function qm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Ym(e){return qm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Xm=60;function ba({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:g=!0}){var ke,ge,V,pe,W;const y=o.useRef(new Map),w=yr();xr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=lt.useMemo(()=>Us(e),[e.status,e.connectionState]),m=o.useMemo(()=>xm(e,s),[e,s]),p=o.useMemo(()=>{var J;return Wa((J=m.targetEntry)==null?void 0:J.providerControls,{hostIdeType:e.hostIdeType,providerType:m.providerType})},[e.hostIdeType,m.providerType,(ke=m.targetEntry)==null?void 0:ke.providerControls]),x=vc({isCliLike:m.isCli||m.isAcp}),h=Em({isCliLike:m.isCli||m.isAcp}),S=Vm(e,{enabled:!!e.sessionId,tailLimit:h}),[_,j]=o.useState(x),I=e.tabKey,k=S.historyMessages,v=S.hasMoreHistory,b=S.historyError,$=S.liveMessages.length>0?S.liveMessages:e.messages;o.useEffect(()=>{j(x)},[x,I]);const L=Math.max(0,$.length-_),T=Ha(e),P=gr(e),K=Ym(e),G=Ua(e),N=a||G,R=!!G,[z,C]=o.useState(!1);o.useEffect(()=>{const J=m.targetEntry;P&&(!J||J.providerControls===void 0||J.controlValues===void 0)&&w(P,{minFreshMs:3e4}).catch(()=>{})},[P,m.isAcp,(ge=m.targetEntry)==null?void 0:ge.providerControls,(V=m.targetEntry)==null?void 0:V.controlValues,w]);const D=o.useCallback(async()=>{if(!z){if($.length>_){j(J=>Math.min($.length,J+Xm));return}C(!0);try{await S.loadHistoryPage()}finally{C(!1)}}},[S,z,$.length,_]),{allMessages:O,receivedAtMap:F}=o.useMemo(()=>{const J=L>0?$.slice(-_):$,oe=k.length===0?J:[...k,...J],le={};return oe.forEach((me,Ce)=>{const ce=`${e.tabKey}:${rn(me,Ce)}`;let xe=Rm(me)||y.current.get(ce)||0;xe||(xe=Date.now(),y.current.set(ce,xe)),le[rn(me,Ce)]=xe}),{allMessages:oe,receivedAtMap:le}},[e.tabKey,L,k,$,_]),X=o.useMemo(()=>l.filter(J=>J.routeId===e.tabKey).sort((J,oe)=>J.timestamp-oe.timestamp),[l,e.tabKey]),ne=o.useMemo(()=>{if($.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((A.isGenerating||e.status==="streaming")&&C(!1),e.status==="not_monitored"&&K)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(dr,{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(Es,{size:14})," Open ",T," 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"&&K)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(Ui,{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(Es,{size:14})," Open ",T," 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"&&!z)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,K,i,c,z,$.length,T,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&t.jsx(yc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(lu,{messages:O,actionLogs:X,agentName:Bs(e)||T||"Agent",userName:u,isCliMode:m.isCli||m.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:F,onLoadMore:D,isLoadingMore:z,hasMoreHistory:v,hiddenLiveCount:L,loadError:b??void 0,emptyState:ne,scrollToBottomRequestNonce:d}),t.jsx(dm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:m.providerType,displayLabel:m.displayLabel,controls:(pe=m.targetEntry)==null?void 0:pe.providerControls,controlValues:(W=m.targetEntry)==null?void 0:W.controlValues,isActive:g,isCliTerminal:m.isCliTerminal}),!m.isCliTerminal&&t.jsx(dc,{contextKey:e.tabKey,panelLabel:T,isSending:n,isBusy:R,statusMessage:N,onSend:r,isActive:g,showControlsToggle:p.length>0})]})}let Nc=ws;function Cc(){return Nc()}class Jm{constructor(){Ye(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 Ic=new Jm;class Qm{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 st=new Qm;function Zm(e){e.dashboardWS&&(Ic=e.dashboardWS),e.connectionManager&&(st=e.connectionManager),e.useDaemonsHook&&(Nc=e.useDaemonsHook)}const Ac=.6,Mc=1.15;function Vo(e,s,r){return Math.min(r,Math.max(s,e))}function ep(e,s,r={}){const n=typeof r.minScale=="number"?r.minScale:Ac,a=typeof r.maxScale=="number"?r.maxScale:Mc;if(!Number.isFinite(e)||e<=0||!Number.isFinite(s)||s<=0)return 1;if(e<=480){const l=s/760;return Number(Vo(l,n,.82).toFixed(2))}const i=e/960,c=s/720;return Number(Vo(Math.min(i,c),n,a).toFixed(2))}function ut(e){return Ha(e)}function Ss(e){return fc(e).join(" · ")}function Tc(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=Da(s==null?void 0:s.content);return r||(e.title?e.title:Ss(e)||"No messages yet")}function Lc(e,s){const{isReconnecting:r,isConnecting:n}=Us(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function tp(e,s){const r=["Chat",...fc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function fs(e){return Lc(e)||Ss(e)}function sp(e){return`${ut(e)} · ${Tc(e)}`}function rp(e){const s=an(e),r=s?dt(s):Bs(e);return`${ut(e)} — ${r||"Agent"}`}function np(e){return Bs(e)||"CLI"}function Rc(e){return pc(e)}function _c(e){return e?`Remote · ${ut(e)||e.workspaceName||"Session"}`:"Remote"}function ap({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var D;ws();const{sendData:u}=Tt(),[f,d]=o.useState(!1),[g,y]=o.useState(1),[w,A]=o.useState({width:0,height:0}),m=o.useRef(null),p=o.useRef(!1),x=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),_=o.useRef(null),j=o.useRef(!1),I=o.useRef(null),k=e.tabKey,v=e.sessionId||"",b=e.daemonId||((D=e.routeId)==null?void 0:D.split(":")[0])||e.routeId||"",$=Ua(e),L=f?i||$:"Runtime terminal unavailable",T=Ac,P=Mc,K=()=>ep(w.width,w.height,{minScale:T,maxScale:P}),G=()=>{var O,F;x.current=0,h.current=!1,S.current="",_.current=null,j.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),d(!1),(F=(O=r.current)==null?void 0:O.reset)==null||F.call(O)},N=()=>{var O,F;x.current=0,h.current=!1,S.current="",_.current=null,j.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),d(!0),(F=(O=r.current)==null?void 0:O.reset)==null||F.call(O)},R=()=>{var F;if(I.current=null,!c)return;const O=S.current;O&&(S.current="",(F=r.current)==null||F.write(O))},z=O=>{O&&(S.current+=O,c&&I.current===null&&(I.current=requestAnimationFrame(R)))},C=(O,F=0,X,ne)=>{var ke,ge,V,pe,W;F>0&&x.current>=F||F===0&&h.current||(x.current=F,d(!0),typeof X=="number"&&typeof ne=="number"&&X>0&&ne>0&&((ge=(ke=r.current)==null?void 0:ke.resize)==null||ge.call(ke,X,ne)),(pe=(V=r.current)==null?void 0:V.reset)==null||pe.call(V),O&&((W=r.current)==null||W.write(O)))};return o.useEffect(()=>{G()},[v]),o.useEffect(()=>{var F;if(!v)return;const O=((F=st.onRuntimeEvent)==null?void 0:F.call(st,v,X=>{if(!(!X||X.sessionId!==v)){if(X.type==="runtime_snapshot"){if(!c){_.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}C(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){h.current=!0,typeof X.seq=="number"&&(x.current=Math.max(x.current,X.seq)),f||d(!0),typeof X.data=="string"&&z(X.data);return}if(X.type==="session_cleared"){if(!c){j.current=!0,S.current="",_.current=null;return}N()}}}))||(()=>{});return()=>{O()}},[b,v,r,c,f]),o.useEffect(()=>{var F,X,ne;if(!v)return;b&&((F=st.getState)==null?void 0:F.call(st,b))==="connected"&&(d(!0),(X=st.requestRuntimeSnapshot)==null||X.call(st,b,v).catch(()=>{}));const O=(ne=st.onStateChange)==null?void 0:ne.call(st,(ke,ge)=>{var V;ke!==b||ge!=="connected"||(d(!0),(V=st.requestRuntimeSnapshot)==null||V.call(st,b,v).catch(()=>{}))});return()=>{O==null||O()}},[b,v,r]),o.useEffect(()=>{s&&G()},[s,k,r]),o.useEffect(()=>{const O=m.current;if(!O||typeof ResizeObserver>"u")return;const F=new ResizeObserver(X=>{const ne=X[0];if(!ne)return;const{width:ke,height:ge}=ne.contentRect;A(V=>{const pe=Math.round(ke),W=Math.round(ge);return V.width===pe&&V.height===W?V:{width:pe,height:W}})});return F.observe(O),()=>F.disconnect()},[]),o.useEffect(()=>{(()=>{p.current||y(K())})()},[w.height,w.width]),o.useEffect(()=>{var F,X;if(!c)return;j.current&&(j.current=!1,N());const O=_.current;O&&(_.current=null,C(O.text,O.seq,O.cols,O.rows)),b&&v&&((F=st.getState)==null?void 0:F.call(st,b))==="connected"&&((X=st.requestRuntimeSnapshot)==null||X.call(st,b,v).catch(()=>{})),S.current&&I.current===null&&(I.current=requestAnimationFrame(R)),requestAnimationFrame(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[b,c,v]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const O=F=>{var ne;const X=F.detail;X!=null&&X.sessionId&&X.sessionId!==v||f&&((ne=r.current)==null||ne.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",O),()=>{window.removeEventListener("adhdev:fit-cli-terminal",O)}},[f,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:m,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:()=>{p.current=!0,y(O=>Math.max(T,Number((O-.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:()=>{p.current=!0,y(O=>Math.min(P,Number((O+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/g}%`,height:`${100/g}%`,transform:`scale(${g})`,transformOrigin:"top left"},children:t.jsx(Xi,{ref:r,readOnly:!f||!c,sizingMode:"measured",onInput:O=>{f&&(u==null||u(b,{type:"pty_input",sessionId:v,targetSessionId:v,data:O}))}})})}),!f&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx(dc,{contextKey:e.tabKey,panelLabel:ut(e),isSending:a,isBusy:!f||!!$,statusMessage:L,onSend:async O=>!f||$?!1:n(O),isActive:l&&c,showControlsToggle:!1})]})}function op({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 ip({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 Va({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(fn,{size:n}):t.jsx(ts,{size:n})})}const qt="New session",Pc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function cp({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),i=a.filter(l=>l==="connected").length,c=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&c>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Go({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function qo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=xn(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 lp({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:g,onShowAllHidden:y,onResetPanelsToMain:w,inboxOpen:A,onInboxOpenChange:m,hiddenOpen:p,onHiddenOpenChange:x,onOpenNewSession:h,actionShortcuts:S,notifications:_,notificationUnreadCount:j,onOpenNotification:I,onMarkNotificationRead:k,onMarkNotificationUnread:v,onDeleteNotification:b}){const{ides:$,p2pStates:L={}}=ws(),T=!!e&&rt(e)&&!Ze(e),P=!!e&&Ze(e),K=l||(e?uc(e)?"terminal":"chat":null),[G,N]=o.useState(!1),R=o.useRef(null),z=o.useRef(null),C=$.filter(W=>W.type==="adhdev-daemon"),D=cp({wsStatus:s,isConnected:r,daemonCount:C.length,p2pStates:L}),O=D.subtitle,F=D.tone==="connected"?"#22c55e":D.tone==="limited"?"#eab308":"#ef4444",X=D.tone==="connected"?"0 0 4px #22c55e80":D.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ne=o.useMemo(()=>_.filter(W=>!W.readAt),[_]),ke=o.useMemo(()=>_.filter(W=>!!W.readAt),[_]),ge=o.useMemo(()=>ne.slice(0,9),[ne]),V=j;o.useEffect(()=>{if(!A)return;const W=J=>{var oe;(oe=R.current)!=null&&oe.contains(J.target)||m(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[A,m]),o.useEffect(()=>{if(!p)return;const W=J=>{var oe;(oe=z.current)!=null&&oe.contains(J.target)||x(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[p,x]),o.useEffect(()=>{if(!p&&!A)return;const W=J=>{if(!J.altKey)return;const oe=J.code.match(/^Digit([1-9])$/);if(!oe)return;const le=Number(oe[1])-1,me=p?d[le]:void 0,Ce=A?ge[le]:void 0;if(!(!me&&!Ce)){if(J.preventDefault(),J.stopPropagation(),me){g==null||g(me),x(!1);return}Ce&&(I(Ce),m(!1))}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[d,p,A,ge,x,m,I,g]);const pe=W=>{if(!W)return;const J=n.find(oe=>oe.tabKey===W);J&&(f==null||f(J))};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(ts,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ut(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:F,boxShadow:X}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:D.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:F,boxShadow:X}}),O&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",O]}),h&&t.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:qt,"aria-label":qt,children:t.jsx(Gi,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||P||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Ss(e)||ut(e),children:ut(e)}),(T||P)&&c&&t.jsxs(t.Fragment,{children:[T&&u&&K&&t.jsx(Va,{mode:K,onChange:u,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:P?"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(At,{size:14})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Ra,{size:14})}),!T&&!Ze(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Pt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:R,children:[t.jsxs("div",{className:`dashboard-header-hidden${G?" is-drop-target":""}`,ref:z,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),N(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",N(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||N(!1)},onDrop:W=>{const J=W.dataTransfer.getData("text/tab-key");W.preventDefault(),N(!1),pe(J)},children:[t.jsxs("button",{type:"button",onClick:()=>x(!p),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${S!=null&&S.toggleHiddenTabs?` (${S.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(zi,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),p&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Go,{value:S==null?void 0:S.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&y&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{y(),x(!1)},children:"Restore all"})]})]}),e&&f&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(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(Go,{value:S==null?void 0:S.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ut(e)})]}),d.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(W=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(W),x(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ut(W)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(W)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(W)+1]}):null,Ss(W)]})]},W.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>m(!A),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(hn,{size:16}),V>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:V})]}),A&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ne.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ne.map(W=>t.jsx(qo,{notification:W,shortcutIndex:ge.indexOf(W)>=0?ge.indexOf(W)+1:void 0,onOpen:()=>I(W),onMarkRead:()=>k(W.id),onMarkUnread:()=>v(W.id),onDelete:()=>b(W.id)},W.id))]}),ke.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ke.map(W=>t.jsx(qo,{notification:W,onOpen:()=>I(W),onMarkRead:()=>k(W.id),onMarkUnread:()=>v(W.id),onDelete:()=>b(W.id)},W.id))]}),_.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function dp(e,s){return String(e||"")!==String(s||"")}function up(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
31
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!ac(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
- `).includes(a)))}function mp(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 Dc(e,s={}){return mp(up(e,s),s.sortMode||"recent")}function cn(e){return e?"Resume saved history":"Start fresh"}function Ga(e){return e?"Resuming saved history…":"Starting fresh…"}function pp(){return"Start fresh"}function Ec(e,s=!1){return e==="cli"?cn(s):e==="ide"?"Start IDE":"Start ACP session"}function $c(e,s=!1){return e==="cli"?Ga(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function fp(){return"Recover hosted runtime"}function hp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function xp(){return"Open saved history"}function bp(){return"Saved History"}function qa(){return"Use saved history when you want continuity in the same provider conversation."}function gp(){return"No saved history found yet."}function yp(){return"Refresh saved history"}function vp(){return"Refreshing saved history…"}function hs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function xs(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 Os(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ws(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ya(e){return`Resume saved history with ${e}?`}function Xa(){return"Review or change the target workspace before resuming saved history."}function wp(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 Ja({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:g,onRefreshHistory:y,onResumeSavedSession:w}){var v;const A=s.find(b=>b.id===e.routeId),m=(A==null?void 0:A.chats)||[],p=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,x=rt(e)&&!Ze(e),[h,S]=o.useState(()=>wt()),_=l||h,j=b=>{if(u){u(b);return}S(b)},I=o.useMemo(()=>Dc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),k=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:f,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:x?bp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:rp(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:qa()})]}),t.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:d,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"}),x?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:b=>j({..._,textQuery:b.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:_.workspaceQuery,onChange:b=>j({..._,workspaceQuery:b.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:_.modelQuery,onChange:b=>j({..._,modelQuery:b.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:_.sortMode,onChange:b=>j({..._,sortMode:b.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:_.resumableOnly,onChange:b=>j({..._,resumableOnly:b.target.checked})}),"Resume-ready only"]})]}),I.map(b=>{const $=e.providerSessionId===b.providerSessionId,L=$||!b.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(b)},disabled:L,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"} ${L?"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:b.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:b.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:wp(b.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:b.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:[b.workspace||"Workspace unknown",ks(b.summaryMetadata)?` · ${ks(b.summaryMetadata)}`:"",b.messageCount>0?` · ${b.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"ACTIVE":b.canResume?c===b.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},b.id)})]}):m.map(b=>t.jsxs("div",{onClick:()=>{g(e.routeId,b.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${p===b.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 ${p===b.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:b.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:[b.id.substring(0,12),"..."]}),p===b.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},b.id)),(x&&!i&&I.length===0||!x&&m.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(Ud,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":gp():"No recent chat sessions found."})]}),x&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:vp()})})]}),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(Fs,{size:13})," ",x?yp():"Refresh History"]})})})]})]});return typeof document>"u"?k:cr.createPortal(k,document.body)}const Yo={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 Kc({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=Yo[n.type]||Yo.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(At,{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 jp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function kp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Sp(e){return e.sessionId||e.instanceId||e.agentType}function Bn(e,s){return e||s}function Bc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Oc(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 Qa(e,s,r={}){return Np(e,s,Oc(e,r))}function Np(e,s,r={}){var g,y,w,A,m,p;const n=[],a=r.machineName,i=r.connectionState,c=kp(e),l=Mu(e.type,{agentName:e.cliName}),u=rt(e)||Ze(e)?l:dt(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var h,S;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||dt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((h=x.activeChat)==null?void 0:h.messages)||[],activeModal:((S=x.activeChat)==null?void 0:S.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],d=jp(e);if(d){const x=e.sessionId||e.instanceId,h=l,S=(g=e.activeChat)==null?void 0:g.activeModal,_=S&&Array.isArray(S.buttons)&&S.buttons.length>0,j=Nt((y=e.activeChat)==null?void 0:y.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||Nt((m=(A=e.agents)==null?void 0:A[0])==null?void 0:m.status)||"idle",I=e.activeChat||{title:"",messages:[]};let k=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(p=e.activeChat)==null?void 0:p.id,b=e.chats;if(v&&Array.isArray(b)&&b.length>0){const P=b.find(K=>K.id===v||K.id&&String(K.id)===String(v));P!=null&&P.title&&String(P.title).trim()&&(k=String(P.title).trim())}const $=(rt(e)||Ze(e),e.type),L=(rt(e)||Ze(e))&&Bo(k,h,$)?"":k,T=I.messages||[];n.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:rt(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:j,title:L,messages:T,resume:e.resume,hostIdeType:!rt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:L||c||(rt(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:_?S.buttons:void 0,modalMessage:_?S.message:void 0,streamSource:"native",tabKey:Bn(x,e.id),machineName:a,connectionState:i})}if(d&&(rt(e)||Ze(e)))return n;for(const x of f){const h=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,S=Tu(x),_=Sp(x),j=`${e.id}:${_}`,I=x.title&&String(x.title).trim()||"",k=Bo(I,x.agentName,x.agentType)?"":I,v=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||v.length>0||h||k||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:S,title:k,messages:v,hostIdeType:e.type,workspaceName:c,displayPrimary:k||c||x.agentName||u,displaySecondary:`${u} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:h?x.activeModal.buttons:void 0,modalMessage:h?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Bn(x.sessionId||x.instanceId,j),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:Bn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Cp(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 Ip(e,s){const r=Cp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Wc=[{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:"🏄"}],Hc=[{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:"🧩"}],Fc=[{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:"🟠"}],Ap=Wc,Mp=Hc,Tp=Fc;function Ns(...e){return pd(fd(e))}function Lp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Ns("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 Uc({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(Lp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ns("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Rt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Ns("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 zc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Ns("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 Rp={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"},_p={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ns("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Rp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:_p[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 Pp={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"},Dp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Ep({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ns("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Pp[e],r),children:[t.jsx("span",{className:Ns("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Dp[e])}),n]})}const ga="adhdev:themechange";function $p(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function As(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ms(e){return e==="system"?$p():e}function Vc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Yr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ga,{detail:{preference:e,theme:s}}))}function Kp(){const e=As(),s=Ms(e);Vc(s),Yr(e,s)}function Za(){const[e,s]=o.useState(As),[r,n]=o.useState(()=>Ms(As()));o.useEffect(()=>{Vc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),Yr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,g=f.theme;s(d==="dark"||d==="light"||d==="system"?d:As()),n(g==="dark"||g==="light"?g:Ms(As()))},l=u=>{if(u.key!=="theme")return;const f=As(),d=Ms(f);s(f),n(d)};return window.addEventListener(ga,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ga,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ms(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Yr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ms(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Yr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Xo={dark:"Dark",light:"Light",system:"System"};function Bp({collapsed:e}){const{preference:s,cycleTheme:r}=Za(),n=s==="dark"?t.jsx(Vd,{size:16}):s==="light"?t.jsx(zd,{size:16}):t.jsx(Gd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Xo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Xo[s]})]})}function us({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 Op({onPrefChange:e}){const[s,r]=Ou(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(hn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{cc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),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(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(qd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!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 ln(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Wp(e,s){const r=ln(e),n=ln(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 Gc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function ar(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Wp(r,s)>=0)return!1;const n=ln(r),a=ln(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Hp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function On(e,s){return e instanceof Error?e.message:s}function Fp({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(zc,{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(zp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Jo({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 cr.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 Up(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Ap,...Mp,...Tp].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 zp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,G;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[g,y]=o.useState("idle"),[w,A]=o.useState(""),m=e.version||null,p=((K=e.machine)==null?void 0:K.platform)||((G=e.system)==null?void 0:G.platform)||"",x=_t(e,{fallbackId:e.id}),h=p==="win32"?"🪟":p==="darwin"?"🍎":"🐧",S=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),_=s.filter(N=>N.daemonId===e.id&&N.transport==="pty"),j=s.filter(N=>N.daemonId===e.id&&N.transport==="acp"),I=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=Hp(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(On(N,"Connection lost during upgrade"))}}},v=async()=>{if(d(null),!!n){y("loading");try{await n(e.id),y("done"),A("Machine disconnected.")}catch(N){y("error"),A(On(N,"Failed to disconnect"))}}},b=async()=>{if(d(null),!!a){y("loading");try{await a(e.id),y("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){y("error"),A(On(N,"Failed to revoke token"))}}},$="0.8.98",L=Gc(e,$),T=ar(e,$),P=S.length+_.length+j.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:x}),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),"…"]}),m&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",m,!L&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&t.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,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:()=>d("disconnect"),disabled:g==="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:()=>d("revoke"),disabled:g==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Ep,{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&&P>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(N=>{const R=Up(N.type),z=N.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:R.icon}),t.jsx("span",{children:R.name}),z!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z?"bg-green-400":"animate-pulse"}`,style:z?void 0:{background:"var(--status-warning)"},title:z?"CDP connected":"CDP connecting..."})]},N.id)}),_.map(N=>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:N.cliName||"CLI"})]},N.id)),j.map(N=>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:N.cliName||"ACP"})]},N.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||g==="error"?"text-red-400":i==="done"||g==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),f==="disconnect"&&t.jsx(Jo,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
33
-
34
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
-
36
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>d(null)}),f==="revoke"&&t.jsx(Jo,{title:"⚠️ Remove Machine",message:`Remove "${x}" from your dashboard?
37
-
38
- This will:
39
- • Immediately disconnect the machine
40
- • Delete the machine registration
41
- • Require restarting ADHDev on that machine
42
-
43
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:b,onCancel:()=>d(null)})]})}const Vp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Gp(){const{preference:e,setPreference:s}=Za();return t.jsx("div",{className:"flex gap-2",children:Vp.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 qp(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 Yp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Wn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Qo(e){const{r:s,g:r,b:n}=Yp(e);return .2126*Wn(s)+.7152*Wn(r)+.0722*Wn(n)}function Zo(e,s){const r=Qo(e),n=Qo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function qc(e){const s=qp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Zo(s,r)>=Zo(s,n)?r:n}const ya={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},va={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},Xp=[{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"}}}],Yc="adhdev-chat-theme",Xc="adhdev-chat-theme-custom";function Xr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Yc)||"ember"}catch{return"ember"}}function Ht(e){try{const s=localStorage.getItem(Xc);if(s){const r=JSON.parse(s);return{...e==="dark"?ya:va,...r[e]}}}catch{}return e==="dark"?ya:va}function Er(e,s){try{localStorage.setItem(Xc,JSON.stringify({dark:e,light:s}))}catch{}}function Kt(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 dn(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 Jp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function or(e,s){var a;const r=(a=Jp[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",dn(r,24)),n.style.setProperty("--accent-on-primary",qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${dn(r,18)})`),n.style.setProperty("--border-accent",Kt(r,.35)),n.style.setProperty("--nav-active-bg",Kt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Kt(r,.06)}`)}function bs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Kt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Kt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Kt(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",Kt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Kt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",dn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",qc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${dn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Kt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Kt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Kt(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 ${Kt(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 eo(){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 Qp(e){try{localStorage.setItem(Yc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=gs()?"dark":"light";bs(Ht(s))}else eo(),or(e,gs()?"dark":"light")}function Zp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Xr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=gs()?"dark":"light";bs(Ht(s))}else eo(),or(e,gs()?"dark":"light")}function gs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function St({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 Xs({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 ef({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Ht(r));o.useEffect(()=>{a(Ht(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},g=Ht(r==="dark"?"light":"dark");return r==="dark"?Er(f,g):Er(g,f),bs(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Xs,{title:"App Background",children:[t.jsx(St,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(St,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(St,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Xs,{title:"App Text",children:[t.jsx(St,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(St,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(St,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Xs,{title:"Borders & Accent",children:[t.jsx(St,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(St,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(St,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Xs,{title:"Chat Bubbles",children:[t.jsx(St,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(St,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(St,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(St,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Xs,{title:"Chat Layout",children:[t.jsx(St,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(St,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(St,{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?ya:va,u=Ht(e?"light":"dark");e?Er(c,u):Er(u,c),a(c),bs(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 tf(){const[e,s]=o.useState(Xr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Ht("dark"));o.useEffect(()=>{n(gs());const u=new MutationObserver(()=>{const g=gs();n(g);const y=Xr();y==="custom"?bs(Ht(g?"dark":"light")):or(y,g?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const g=gs();n(g);const y=Xr();y==="custom"?bs(Ht(g?"dark":"light")):or(y,g?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?bs(Ht(r?"dark":"light")):(eo(),or(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Ht(r?"dark":"light"))},[r]);const c=u=>{s(u),Qp(u)},l=[...Xp,{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 f=e===u.id,d=r?u.preview.dark:u.preview.light,g=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:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.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:d.userBubble,color:g},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:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(ef,{dark:r,onColorsChange:u=>i(u)})]})}const to="adhdev_mobileDashboardMode_v1",wa="adhdev:mobile-dashboard-mode-change";function so(){try{return localStorage.getItem(to)==="workspace"?"workspace":"chat"}catch{return"chat"}}function sf(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??so())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==to||s()};return window.addEventListener(wa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(wa,r),window.removeEventListener("storage",n)}}function rf(e){try{localStorage.setItem(to,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(wa,{detail:e}))}function nf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(so()==="chat")},[]),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ts,{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),rf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Hn=new Map,ei=new Map;function af(e){if(!e||typeof e!="object")return null;const s=e,r=s.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function of(e,s,r,n){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Jc(){const{sendCommand:e}=Tt(),{injectEntries:s,getIdes:r}=lr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Nm,c=ei.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Hn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=af(f);if(!d)return;const g=r().find(w=>w.id===n),y=of(g,n,d.machine,d.timestamp||Date.now());s([y]),ei.set(n,Date.now())})().finally(()=>{Hn.delete(n)});return Hn.set(n,u),u},[r,s,e])}function cf(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 lf(e,s){const{sendData:r}=Tt(),{injectEntries:n,getIdes:a}=lr(),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=>os.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const g=a().find(w=>w.id===u),y=cf(g,u,d);n([y])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Qc(e,s){const{sendData:r}=Tt(),[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=os.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Mm):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 df(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Zc(e){const{sendData:s}=Tt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=df(e);if(!a||!e.sessionId||!s){n({});return}const i=os.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}),Ds.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.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const el="adhdev_hiddenTabs";function uf(){try{const e=localStorage.getItem(el);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Cs(e){try{localStorage.setItem(el,JSON.stringify([...e]))}catch{}}function $r(e){return $a(e)}function ro(e,s){return rs(s).some(r=>e.has(r))}function mf(){const[e,s]=o.useState(uf),r=o.useCallback(f=>{s(d=>{const g=new Set(d);return g.has(f)?g.delete(f):g.add(f),Cs(g),g})},[]),n=o.useCallback(f=>{s(d=>{if(d.has(f))return d;const g=new Set(d);return g.add(f),Cs(g),g})},[]),a=o.useCallback(f=>{s(d=>{if(!d.has(f))return d;const g=new Set(d);return g.delete(f),Cs(g),g})},[]),i=o.useCallback(()=>{s(f=>{if(f.size===0)return f;const d=new Set;return Cs(d),d})},[]),c=o.useCallback((f,d)=>{s(g=>{const y=new Set(g);for(const w of d)y.add(w);return Cs(y),y})},[]),l=o.useCallback((f,d)=>{s(g=>{const y=new Set(g);for(const w of d)y.delete(w);return Cs(y),y})},[]),u=o.useCallback(f=>ro(e,f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function tl(e){return e instanceof Error?e.message:String(e||"")}function no(e){const s=tl(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ao(e){const s=tl(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ti(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 pf(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=ti(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ti(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function sl(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 ff(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))sl(s,a)===i&&(delete n[a],r=!0);return r?n:e}function hf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{cc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Rc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Fu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,g]of Object.entries(l))u-g<5e3&&(f[d]=g);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function xf(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 Fn(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 bf(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 si(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?bf(Da(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 gf(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||""),si(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),si(r.activeChat)].join(":"))].join("|")}function yf(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 vf(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 wf(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 jf(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of rs({routeId:n.routeId}))r.set(i,a);for(const i of rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of rs({tabKey:n.tabKey}))r.set(i,n)}return r}function kf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Sf(e){const s=kf(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=Da(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Nf({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>xf(e),[e]),c=o.useMemo(()=>Bc(e),[e]),l=o.useRef([]),u=o.useRef([]),f=o.useRef([]),d=o.useRef(new Map),g=o.useRef(new Map),y=o.useMemo(()=>{const j=new Map,I=[];for(const $ of i){const{connectionState:L="new",machineName:T}=Oc($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P=vf($,r),K=gf($),G=d.current.get($.id);if(G&&G.ide===$&&G.sourceSignature===K&&G.connectionState===L&&G.machineName===T&&wf(G.localRefs,P)){j.set($.id,G),I.push(...G.conversations);continue}const N=Qa($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:$,sourceSignature:K,connectionState:L,machineName:T,localRefs:P,conversations:N};j.set($.id,R),I.push(...N)}d.current=j;const k=new Map,v=$=>{const L=Sf($),T=g.current.get($.tabKey);if(T&&T.signature===L)return k.set($.tabKey,T),T.timestamp;const P={signature:L,timestamp:xc($)||(T==null?void 0:T.timestamp)||0};return k.set($.tabKey,P),P.timestamp},b=[...I].sort(($,L)=>bc($,L,v));return g.current=k,b},[i,r,s,c]),w=o.useMemo(()=>{const j=yf(y,n);return Fn(l.current,j)?l.current:(l.current=j,j)},[y,n]),A=o.useMemo(()=>{const j=new Map,I=Array.from(new Set(w.map(k=>k.routeId)));for(const k of I){const v=Ft(w,k);v&&j.set(k,v)}return j},[w]),m=o.useMemo(()=>{const j=new Map;for(const I of w){const k=A.get(I.routeId),v=I.streamSource==="native"&&k?k:I;for(const b of rs({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))j.set(b,v)}return j},[w,A]),p=o.useMemo(()=>jf(w,A),[w,A]),x=o.useCallback(j=>{if(j)return m.get(j)},[m]),h=o.useCallback(j=>{if(j)return p.get(j)},[p]),S=o.useMemo(()=>{const j=w.filter(I=>!ro(a,I));return Fn(u.current,j)?u.current:(u.current=j,j)},[w,a]),_=o.useMemo(()=>{const j=S.map(I=>I.tabKey);return Fn(f.current,j)?f.current:(f.current=j,j)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:_,resolveConversationBySessionId:x,resolveConversationByTarget:h}}function Cf({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 If({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{nt.setIdes(e)},[e]),o.useEffect(()=>{nt.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=nt.onToast(u=>{r(d=>d.some(y=>y.message===u.message&&u.timestamp-y.timestamp<3e3)?d:[...d.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const f=u.duration||5e3;setTimeout(()=>r(d=>d.filter(g=>g.id!==u.id)),f)}),c=nt.onSystemMessage((u,f)=>{var w,A;const d=a(u),g=(w=f._localId)==null?void 0:w.startsWith("sys_approval_"),y=!!(d&&(d.status==="waiting_approval"||(A=d.modalButtons)!=null&&A.length||d.modalMessage));g&&y||n(m=>({...m,[u]:[...m[u]||[],f]}))}),l=nt.onClearSystemMessage((u,f)=>{n(d=>{var g;return(g=d[u])!=null&&g.length?{...d,[u]:d[u].filter(y=>{var w;return!(y.role==="system"&&((w=y._localId)!=null&&w.startsWith(f)))})}:d})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Ic.on("status_event",c=>{nt.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var p;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 f=u.targetSessionId||u.targetKey||u.daemonId,d=a(f),g=(d==null?void 0:d.routeId)||u.daemonId;if(!g)return;const y=Number(u.buttonIndex),w=u.button||((p=d==null?void 0:d.modalButtons)==null?void 0:p[y])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),m=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(g,"resolve_action",{action:m?"approve":"reject",button:w,...Number.isFinite(y)&&{buttonIndex:y},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};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 Af="adhdev_dashboardLayout_v1",Mf="adhdev_dashboardDockview_v1",Tf="adhdev_dashboardDockviewHiddenRestore_v1",Js={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function oo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function rl(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function nl(e){return`${Af}:${e}`}function Lf(e){const s=nl(e);return oo(s,null)}function Rf(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=nl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function al(e){return`${Mf}:${e}`}function _f(e){const s=al(e);return oo(s,null)}function Pf(e,s){try{const r=al(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function ol(e){return`${Tf}:${e}`}function Df(e){const s=ol(e);return oo(s,{})}function Ef(e,s){try{const r=ol(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function $f(){return{groupAssignments:[...Js.groupAssignments],focusedGroup:Js.focusedGroup,groupActiveTabIds:{...Js.groupActiveTabIds},groupTabOrders:{...Js.groupTabOrders},groupSizes:[...Js.groupSizes]}}function Kf(){const[e]=o.useState(()=>rl(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({}),[f,d]=o.useState([]),[g,y]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),m=o.useCallback(()=>{if(w)return;const p=Lf(e)??$f();r(new Map(p.groupAssignments)),a(p.focusedGroup),c(p.groupActiveTabIds),u(p.groupTabOrders),d(p.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&Rf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,s,n,i,l,f]),o.useEffect(()=>{const p=window.matchMedia("(max-width: 767px)"),x=h=>y(h.matches);return p.addEventListener("change",x),()=>p.removeEventListener("change",x)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:f,setGroupSizes:d,isMobile:g,hasHydratedStoredLayout:w,hydrateStoredLayout:m}}function Bf(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ea(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Of({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:f,activeConv:d,isRefreshingHistory:g,ides:y,handleRefreshHistory:w}){const A=o.useRef(!1),m=o.useRef(!1),p=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const S=n.get(h.tabKey)??0;c(_=>({..._,[S]:h.tabKey})),l(S),A.current=!0,m.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),u(_=>{const j=new URLSearchParams(_);return j.delete("activeTab"),j},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(m.current||a)&&s.length!==0){if(!e){i(),m.current=!0;return}if(A.current){m.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(m.current||a)&&(i(),m.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!f){x.current=!1;return}if(!d||x.current||g)return;const h=y.find(S=>S.id===d.routeId);h&&(!h.chats||h.chats.length===0||Bf(h.chats,d))&&(x.current=!0,w())},[f,d,g,y,w]),o.useEffect(()=>{if(!d)return;let h=null,S=0,_=-1,j=0;const I=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(b=>b.offsetParent!==null);if(k.length===0){S<18&&(S+=1,h=requestAnimationFrame(I));return}let v=0;for(const b of k)b.scrollTop=b.scrollHeight,v+=b.scrollHeight;v===_?j+=1:(j=0,_=v),S+=1,!(j>=2||S>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[d==null?void 0:d.tabKey])}function Wf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,g]=o.useState(null),y=o.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!rt(x)&&!Ze(x)?x:null},[e,n,l]),w=o.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)return null;const h=u!=null&&u.tabKey?i.find(S=>S.tabKey===u.tabKey):a?i.find(S=>S.tabKey===a):null;return(h==null?void 0:h.routeId)===x?h:Ft(i,x)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(x=>x.id===w.routeId)},[c,w]);o.useEffect(()=>{y&&(f({routeId:y.routeId,tabKey:Ho(y)}),g(y),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,y]);const m=o.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Ho(x)}),g(x))},[]),p=o.useCallback(()=>{f(null),g(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:d,setRemoteDialogActiveConv:g,openRemoteDialog:m,closeRemoteDialog:p}}function Un(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=Ea(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ri({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[f,d]=o.useState(!1),g=o.useCallback(async m=>{try{await e("standalone","launch_ide",{ideType:m,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),y=o.useCallback(async(m,p)=>{try{const x=m||(s==null?void 0:s.daemonId)||"",h=await e(x,"switch_chat",{id:p,sessionId:p,..._s(s)}),S=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?Ys(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?Ys(a,`⚠️ Switch error: ${S}`):Ys(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Ys(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const m=pr(s);await e(m,"new_chat",{..._s(s)}),c(p=>({...p,[s.tabKey]:Date.now()})),i(p=>({...p,[s.tabKey]:[]}))}catch(m){console.error("New chat failed",m)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var m,p;if(!(!s||f)){d(!0);try{const x=pr(s),h=async()=>e(x,"list_chats",{forceExpand:!0,..._s(s)});let S=await h(),_=(S==null?void 0:S.chats)||((m=S==null?void 0:S.result)==null?void 0:m.chats);Un(_,s)&&(await new Promise(j=>setTimeout(j,450)),S=await h(),_=(S==null?void 0:S.chats)||((p=S==null?void 0:S.result)==null?void 0:p.chats)),S!=null&&S.success&&Array.isArray(_)&&(n(s.routeId,_),Un(_,s)&&!Un(r,s)&&Ys(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{d(!1)}}},[s,r,f,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:f,handleLaunchIde:g,handleSwitchSession:y,handleNewChat:w,handleRefreshHistory:A}}function Hf(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 Ff(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ni(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 ai(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 Uf(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 zf(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 oi(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 ii(e){return Array(e).fill(100/e)}function Vf({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),g=o.useMemo(()=>Kr(e,f),[e,f]),y=g.assignments,w=o.useMemo(()=>l?1:g.groupCount,[g.groupCount,l]),A=w>1,m=o.useCallback((j,I)=>{s(k=>{const v=new Map(Kr(k,f).assignments);return I===0?v.delete(j):v.set(j,I),v}),n(k=>({...k,[I]:j})),r(I)},[s,f,n,r]),p=o.useCallback(j=>{s(I=>{const k=Kr(I,f).assignments,v=new Map;for(const[b,$]of k)$!==j&&($>j?v.set(b,$-1):v.set(b,$));return v}),c(I=>{if(I.length<=1)return[];const k=[...I];k.splice(j,1);const v=k.reduce((b,$)=>b+$,0);return v>0?k.map(b=>b/v*100):[]}),r(0)},[s,f,c,r]),x=o.useCallback((j,I)=>{I.preventDefault();const k=d.current;if(!k)return;const v=I.clientX,b=k.offsetWidth,$=i.length===w?[...i]:ii(w),L=P=>{const G=(P.clientX-v)/b*100,N=[...$];N[j]=Math.max(15,$[j]+G),N[j+1]=Math.max(15,$[j+1]-G),c(N)},T=()=>{document.removeEventListener("mousemove",L),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",L),document.addEventListener("mouseup",T)},[i,w,c]),h=o.useCallback((j,I,k)=>{if(w>=4)return;const v=k==="left"?I:I+1;s(b=>{const $=Kr(b,f).assignments,L=new Map;for(const T of u){const P=$.get(T.tabKey)??0,K=P>=v?P+1:P;K>0&&L.set(T.tabKey,K)}return v>0&&L.set(j,v),L}),c(b=>{const $=b.length===w?[...b]:ii(w),L=$[I]??100/w,T=Math.max(15,L/2),P=Math.max(15,L/2),K=[...$];K[I]=T,K.splice(v,0,P);const G=K.reduce((N,R)=>N+R,0);return K.map(N=>N/G*100)}),n(b=>{const $=oi(b,v);return $[v]=j,$}),a(b=>{const $=oi(b,v);return $[v]=[j],$}),r(v)},[w,s,f,u,c,n,a,r]);o.useEffect(()=>{Hf(e,y)||s(y)},[e,y,s]),o.useEffect(()=>{const{mapping:j,usedGroups:I}=g;n(k=>{const v=ai(k,j);return ni(k,v)?k:v}),a(k=>{const v=ai(k,j);return ni(k,v)?k:v}),r(k=>{const v=l?0:Uf(k,I,j);return k===v?k:v}),c(k=>{const v=l?[]:zf(k,I,g.groupCount);return Ff(k,v)?k:v})},[g,l,n,a,r,c]);const S=o.useMemo(()=>{const j=Array.from({length:w},()=>[]);for(const I of u){const k=y.get(I.tabKey)??0,v=Math.min(k,w-1);j[v].push(I)}return j},[u,y,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:y,numGroups:w,isSplitMode:A,groupedConvs:S,moveTabToGroup:m,closeGroup:p,handleResizeStart:x,splitTabRelative:h,clearAllSplits:_}}function Gf({ides:e,sendDaemonCommand:s}){const r="0.8.98",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Gc(d,r)).sort((d,g)=>Number(ar(g,r))-Number(ar(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>ar(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var g,y;u(w=>({...w,[d]:"upgrading"}));try{const w=await s(d,"daemon_upgrade",{});(g=w==null?void 0:w.result)!=null&&g.upgraded||(y=w==null?void 0:w.result)!=null&&y.success?u(A=>({...A,[d]:"done"})):u(A=>({...A,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const ja="adhdev_dashboard_notifications_v2",ka="adhdev_dashboard_notifications_v1",wr=80;function Jr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function io(e){return{...e,createdAt:Jr(e.createdAt),updatedAt:Jr(e.updatedAt,e.createdAt),lastEventAt:Jr(e.lastEventAt,e.updatedAt||e.createdAt)}}function qf(e){const s=$a(e);return s==="unknown:"?e.id:s}function ci(e){return[e.type,Qi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Yf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const f=ci({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),d=!!((c=n==null?void 0:n.get(f))!=null&&c.forceUnread),g=bn(l,s,{notificationStateBySessionId:r}),y=g.inboxBucket==="needs_attention"?"needs_attention":g.inboxBucket==="task_complete"&&g.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&d?"task_complete":null;if(!y)continue;const w=Jr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=y==="task_complete"?f:ci({type:y,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(io({id:A,dedupKey:A,type:y,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:pc(l),preview:mm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Xf(e,s=wr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=qf(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function Jf(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function Qf(e){return new Map(e.map(s=>[s.id,s]))}function il(e,s,r=wr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=io(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Xf(a,r)}function Zf(e,s,r=wr){const n=new Set(il(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function eh(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function th(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function sh(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!ur(c,r)});for(const i of s)ur(i,r)&&a.push({id:i.id,readAt:n});return a}function rh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function nh(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ah(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=rs(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 oh(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(ja),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(ka),r=s?JSON.parse(s):[];return Array.isArray(r)?Jf(r.map(n=>io(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function ih(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,wr);if(s.length===0){window.localStorage.removeItem(ja),window.localStorage.removeItem(ka);return}window.localStorage.setItem(ja,JSON.stringify(s)),window.localStorage.removeItem(ka)}catch{}}function ch(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.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function lh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=wr}=e,[a,i]=o.useState(()=>oh()),c=o.useMemo(()=>Qf(a),[a]),l=o.useMemo(()=>Yf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>il(l,a,n),[l,a,n]),f=o.useMemo(()=>ah(u),[u]);o.useEffect(()=>{i(m=>{const p=Zf(m,l,n);return ch(m,p)?m:p})},[l,n]),o.useEffect(()=>{ih(a)},[a]);const d=o.useMemo(()=>nh(u),[u]),g=o.useCallback((m,p)=>{i(x=>eh(x,m,p))},[]),y=o.useCallback(m=>{i(p=>th(p,m))},[]),w=o.useCallback((m,p)=>{i(x=>sh(x,u,m,p))},[u]),A=o.useCallback(m=>{i(p=>rh(p,m))},[]);return{notifications:u,unreadCount:d,notificationStateBySessionId:f,markRead:g,markUnread:y,markTargetRead:w,deleteNotification:A}}function cl(){return"select_session"}function dh(){return"open_panel"}function uh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function mh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function li(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function di(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function co(e){return e instanceof Error?e.message:String(e||"")}function ui(e){const s=co(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function mi(e,s){const r=co(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function yn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[f,d]=o.useState(null),g=o.useRef(!1),y=o.useRef(null);o.useEffect(()=>{d(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async x=>{if(!s)return!1;const h=x.trim(),S=Ua(s);if(uh({hasMessage:!!h,blockedMessage:S,sendInFlight:g.current}))return S&&d(S),!1;const _=Date.now(),j={tabKey:s.tabKey,message:h,timestamp:_};if(mh(y.current,j))return d(null),!0;g.current=!0,u(!0),d(null),y.current=j;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(b=>({...b,[j.tabKey]:[...b[j.tabKey]||[],k]}));try{const b=pr(s);if(!b)return y.current=li(y.current,j),v&&r(T=>({...T,[j.tabKey]:(T[j.tabKey]||[]).filter(P=>P._localId!==I)})),d("Unable to send message right now."),!1;const $=await e(b,"send_chat",{message:h,..._s(s)}),L=di($);if(v&&(L!=null&&L.deduplicated))return r(T=>({...T,[j.tabKey]:(T[j.tabKey]||[]).filter(P=>P._localId!==I)})),d(null),!0;if((L==null?void 0:L.sent)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");return setTimeout(()=>{const T=Date.now()-6e4;r(P=>{const K=P[j.tabKey];if(!K)return P;const G=K.filter(N=>N.timestamp>T);return G.length===K.length?P:{...P,[j.tabKey]:G}})},6e4),d(null),!0}catch(b){const $=co(b);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",b),y.current=li(y.current,j),r(L=>({...L,[j.tabKey]:(L[j.tabKey]||[]).filter(T=>T._localId!==I)})),d(_m(b)),!1}finally{g.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(x){console.error("Relaunch failed",x)}},[s,e]),m=o.useCallback(async x=>{if(s)try{const S=(s.modalButtons||[]).indexOf(x),_=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=pr(s);if(!I)return;const k=await e(I,"resolve_action",{button:x,action:j?"approve":"reject",...S>=0&&{buttonIndex:S},..._s(s)}),v=di(k);v.success||n(b=>[...b,{routeId:s.tabKey,text:mi(x,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){ui(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:ui(h)?mi(x,h):`❌ **${x}** error`,timestamp:Date.now()}])}},[s,e,n]),p=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,dh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:f,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:m,handleFocusAgent:p}}const lo=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:g,isFocusingAgent:y,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p=!0}){const x=Zc(s),h=x.status||x.modalMessage||x.modalButtons?{...s,...x.status?{status:x.status}:{},...x.modalMessage!==void 0?{modalMessage:x.modalMessage}:{},...x.modalButtons!==void 0?{modalButtons:x.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(tc,{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(js,{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(ap,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:n,isInputActive:p})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(ba,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:g,isFocusingAgent:y,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p})})]}):t.jsx(ba,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:g,isFocusingAgent:y,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p})]})},(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 ph({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:g,onOpenHistory:y,onOpenRemote:w,onHideConversation:A,onStopCli:m,cliViewMode:p,onSetCliViewMode:x,handleSendChat:h,handleFocusAgent:S,handleModalButton:_,handleRelaunch:j}){const I=o.useRef(null),k=rt(e)&&!s,v=k&&p==="terminal",b=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 ${b} 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(Ta,{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:ut(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(yc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>g(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&p&&t.jsx(Va,{mode:p,onChange:x,compact:!0}),k&&m&&t.jsx("button",{onClick:()=>{m(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(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:t.jsx(Ra,{size:14})}),!s&&!k&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Pt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(lo,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:j,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const zn={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 fh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ll(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(fh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(zn[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:zn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:zn[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 dl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Pt},{key:"chats",label:"Chats",icon:ts}];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 Br({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 Is({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 Or({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:f}=Us(e.conversation),d=ut(e.conversation),g=Ss(e.conversation),y=Lc(e.conversation,{requiresAction:s==="needs_attention"}),w=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",A=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",m=c?"text-text-secondary":"text-text-primary",p=c?"text-text-muted":"text-text-secondary",x=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",S="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] ${w}`,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 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),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 ${m}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:ec(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${p}`,children:[g,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${S} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):y==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:S,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,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 pi({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 hh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:g,onOpenMachine:y,onOpenSettings:w,onSectionChange:A,wsStatus:m="connected",isStandalone:p=!1}){const x=m==="disconnected"||m==="reconnecting"||m==="offline"||m==="auth_failed",h=c.length>0,S=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",j=p?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=p?"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 ${j}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(hn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,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(pn,{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:x?t.jsx(Qs,{icon:t.jsx(pi,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:m==="offline"?"Your device appears to be offline. Waiting for network…":m==="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:p?"Waiting for your daemon":"Connect your machines",subtitle:p?"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:!p&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(ll,{})})}):t.jsx(Is,{children:c.map((k,v)=>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] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(k.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Br,{title:"Needs attention",className:"mb-0"}),t.jsx(Is,{children:s.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Or,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Br,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Is,{children:r.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Or,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Br,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Is,{children:n.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Or,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Br,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Is,{children:a.map((k,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Or,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):S?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):x?t.jsx(Qs,{icon:t.jsx(pi,{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(ts,{size:20})}),title:"No conversations yet",subtitle:Pc,children:g&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":qt,title:qt,children:[t.jsxs("svg",{width:"16",height:"16",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("span",{children:qt})]})}):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:d,children:"Restore all"})]}),t.jsx(Is,{className:"bg-bg-secondary/25",children:i.map((k,v)=>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 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(ut(k))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:ut(k)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:Ss(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&g&&S&&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:g,"aria-label":qt,title:qt,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(dl,{section:e,onSectionChange:A})]})}function xh(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 ul(e){const s=[e.workspace||"Workspace unknown"],r=ks(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=xh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function vn(...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 bh(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 wn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=bh(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 gh(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 yh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function jn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=yh(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=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function kn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,g]=o.useState(r);o.useEffect(()=>{g(r)},[r]);const y=gh(r),w=d.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(At,{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(Ta,{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:d,onChange:A=>g(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.preventDefault(),u(w))},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:()=>{!w||a||u(w)},disabled:!w||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(A=>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(A.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(Es,{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:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.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:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function uo({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:g,showModelInput:y,modelValue:w,onModelChange:A,historyProviderNode:m,onConfirm:p,onCancel:x}){const h=n==null?void 0:n.find(S=>S.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:x,"aria-label":"Close launch confirmation",children:t.jsx(At,{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:S=>i(S.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(S=>t.jsx("option",{value:S.key,children:S.label},S.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),m,r.map(S=>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:S.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),y&&A&&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:w||"",onChange:S=>A(S.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})]}),f&&g&&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:d||"",onChange:S=>g(S.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:x,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:p,disabled:u,children:[t.jsx(_a,{size:14}),u?l:c]})]})]})})}function fi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ys(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?"⭐ ":""}${fi(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:fi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.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 vh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function wh(e){return[vh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function jh(e){return e.lastLaunchedAt?xn(e.lastLaunchedAt):""}function ml(e){return{metaText:wh(e),updatedLabel:jh(e)}}function Vn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function kh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Qe,It,ht,at;const c=yr(),[l,u]=o.useState(!1),f=(((Qe=e.detectedIdes)==null?void 0:Qe.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),g=e.defaultWorkspaceId||null,[y,w]=o.useState(g||((It=d[0])==null?void 0:It.id)||""),[A,m]=o.useState(""),[p,x]=o.useState(""),[h,S]=o.useState([]),[_,j]=o.useState(!1),[I,k]=o.useState(""),[v,b]=o.useState(!1),[$,L]=o.useState(Vn(f,s.length,r.length)),T=o.useRef(null),[P,K]=o.useState(null),G=o.useRef("__home__"),[N,R]=o.useState("__home__"),[z,C]=o.useState(""),[D,O]=o.useState(""),[F,X]=o.useState(""),[ne,ke]=o.useState([]),[ge,V]=o.useState(()=>wt().textQuery),[pe,W]=o.useState(()=>wt().workspaceQuery),[J,oe]=o.useState(()=>wt().modelQuery),[le,me]=o.useState(()=>wt().resumableOnly),[Ce,ce]=o.useState(()=>wt().sortMode),[xe,te]=o.useState(!1),[ue,se]=o.useState(!1),Se=o.useRef(null),we=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Re=y==="__custom__"?A.trim():((ht=d.find(Ae=>Ae.id===y))==null?void 0:ht.path)||"",M=y==="__custom__"&&!!Re&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=y!=="__custom__"&&((at=d.find(Ae=>Ae.id===y))==null?void 0:at.path)||"",ye=o.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),ee=o.useCallback(async Ae=>{j(!0),k("");try{const Xe=await a(Ae);x(Xe.path),m(Xe.path),S(Xe.directories)}catch(Xe){k(Xe instanceof Error?Xe.message:"Could not load folder")}finally{j(!1)}},[a]),je=o.useCallback(()=>{var Xe;w("__custom__"),b(!0);const Ae=wn(e.platform,vn(A.trim(),he,ye,e.defaultWorkspacePath,(Xe=d.find(He=>He.id===g))==null?void 0:Xe.path,d.map(He=>He.path)));ee(Ae)},[A,g,ee,ye,he,e.platform,d]),Te=o.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){w(Ae.workspaceId),m("");return}if(Ae!=null&&Ae.workspacePath){w("__custom__"),m(Ae.workspacePath);return}w(""),m("")},[]),Oe=o.useCallback(Ae=>{if(w(Ae),Ae==="__custom__"){je();return}m("")},[je]),Pe=o.useCallback(Ae=>{w("__custom__"),m(Ae)},[]),Ve=o.useCallback((Ae,Xe)=>{T.current=Xe,G.current=Ae.selectedWorkspaceKey||"__home__",R(Ae.selectedWorkspaceKey||"__home__"),C(Ae.initialArgs||""),O(Ae.initialModel||""),X(""),ke([]);const He=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(dp(we.current,He)){const ze=wt();V(ze.textQuery),W(ze.workspaceQuery),oe(ze.modelQuery),me(ze.resumableOnly),ce(ze.sortMode)}we.current=He,K(Ae),Ae.providerType&&i&&(te(!0),i(Ae.providerType).then(ze=>ke(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>te(!1)))},[i,e.id]),Ge=o.useMemo(()=>Dc(ne,{textQuery:ge,workspaceQuery:pe,modelQuery:J,resumableOnly:le,sortMode:Ce}),[J,le,ne,Ce,ge,pe]);o.useEffect(()=>{F&&(Ge.some(Ae=>Ae.providerSessionId===F)||X(""))},[Ge,F]);const ft=o.useCallback(()=>{T.current&&(se(!0),T.current().finally(()=>{T.current=null,se(!1),K(null)}))},[]),et=o.useCallback(()=>{T.current=null,K(null)},[]),it=o.useCallback(Ae=>{G.current=Ae,R(Ae)},[]);return o.useEffect(()=>{var Ae;Se.current!==e.id&&(Se.current=e.id,w(g||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"),m(""),x(""),S([]),k(""),b(!1),V(wt().textQuery),W(wt().workspaceQuery),oe(wt().modelQuery),me(wt().resumableOnly),ce(wt().sortMode),we.current=null,L(Vn(f,s.length,r.length)))},[r.length,s.length,g,f,e.id,d]),o.useEffect(()=>{var Ae;y!=="__custom__"&&(y&&d.some(Xe=>Xe.id===y)||w(g||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"))},[g,y,d]),o.useEffect(()=>{$==="ide"&&f||$==="cli"&&s.length>0||$==="acp"&&r.length>0||L(Vn(f,s.length,r.length))},[$,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:g,workspaceChoice:y,customWorkspacePath:A,browseCurrentPath:p,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:$,launchConfirm:P,launchConfirmWorkspaceKeyRef:G,launchConfirmWorkspaceKey:N,launchConfirmArgs:z,launchConfirmModel:D,launchConfirmResumeId:F,launchConfirmSavedSessions:ne,launchConfirmTextFilter:ge,launchConfirmWorkspaceFilter:pe,launchConfirmModelFilter:J,launchConfirmResumableOnly:le,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:xe,launchConfirmBusy:ue,resolvedWorkspacePath:Re,canCreateMissingWorkspace:M,openBrowseDialog:je,loadBrowsePath:ee,handleWorkspaceChoiceChange:Oe,chooseCustomWorkspacePath:Pe,setCustomWorkspacePath:m,setBrowseDialogOpen:b,setActiveLauncherKind:L,openLaunchConfirm:Ve,handleConfirmLaunch:ft,closeLaunchConfirm:et,setWorkspaceSelectionFromOption:Te,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:C,setLaunchConfirmModel:O,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:V,setLaunchConfirmWorkspaceFilter:W,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:me,setLaunchConfirmSortMode:ce}}function Sh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:g,onSectionChange:y,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:m,onMachineUpgrade:p,onLaunchDetectedIde:x,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:_,onListSavedSessions:j}){const I=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",k=r.slice(0,4),v=s.slice(0,3),b=kh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:j}),$=o.useMemo(()=>k.map(N=>{const{metaText:R,updatedLabel:z}=ml(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:R,updatedLabel:z,onClick:()=>{const{options:C,selectedKey:D}=ys({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspacePath:N.workspace});b.openLaunchConfirm({title:N.kind==="ide"?hs("restart-ide",N.label):N.providerSessionId?Ya(N.label):hs("start-fresh",N.label),description:N.kind==="ide"?xs("restart-ide"):N.providerSessionId?Xa():xs("start-fresh"),confirmLabel:N.kind==="ide"?Os("restart-ide"):N.providerSessionId?cn(!0):Os("start-fresh"),busyLabel:N.kind==="ide"?Ws("restart-ide"):N.providerSessionId?Ga(!0):Ws("start-fresh"),workspaceOptions:C,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const O=C.find(F=>F.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(O),await A({...N,workspace:(O==null?void 0:O.workspacePath)??null})})}}}),[b,A,k]),L=o.useMemo(()=>v.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:ut(N.conversation),secondary:tp(N.conversation,{timestampLabel:N.timestamp?ec(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,v]),T=b.showAllRecent?$:$.slice(0,4),P=$.length>0,K=L.length>0,G=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 ${G} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:g,type:"button","aria-label":"Back",children:t.jsx(Ta,{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:_t(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:[K&&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:L.map(N=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),P&&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(N=>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:N.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:N.primary}),N.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.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:()=>b.setShowAllRecent(N=>!N),children:b.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(b.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:b.workspaceChoice,onChange:N=>b.handleWorkspaceChoiceChange(N.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:b.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[b.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===b.defaultWorkspaceId?"⭐ ":"",gn(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),b.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(Es,{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:b.resolvedWorkspacePath||b.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:b.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:()=>{b.resolvedWorkspacePath&&h(b.resolvedWorkspacePath)},disabled:!b.resolvedWorkspacePath||b.browseBusy,children:"Save as workspace"})]})]}),b.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[b.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${b.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:()=>b.setActiveLauncherKind("acp"),children:"ACP"})]}),b.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:b.activeLauncherKind==="ide"?"Choose an IDE":b.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:b.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>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:R,selectedKey:z}=ys({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:z,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const C=R.find(D=>D.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(C),x(N.type,{workspacePath:(C==null?void 0:C.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(b.activeLauncherKind==="cli"?n:a).map(N=>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 R=b.activeLauncherKind==="cli"?"cli":"acp",{options:z,selectedKey:C}=ys({machine:{workspaces:b.workspaceRows,defaultWorkspaceId:b.defaultWorkspaceId},currentWorkspaceId:b.workspaceChoice!=="__custom__"?b.workspaceChoice:null,currentWorkspacePath:b.resolvedWorkspacePath});b.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:z,selectedWorkspaceKey:C,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const D=z.find(O=>O.key===b.launchConfirmWorkspaceKeyRef.current);b.setWorkspaceSelectionFromOption(D),_(R,N.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:b.launchConfirmArgs,model:b.launchConfirmModel,resumeSessionId:b.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:b.resolvedWorkspacePath||"Use selected workspace"})]},N.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,b.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(b.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:p,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:m,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"})]})]})]})]}),b.browseDialogOpen&&t.jsx(kn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:b.browseCurrentPath,directories:b.browseDirectories,busy:b.browseBusy,error:b.browseError,confirmLabel:"Use this folder",onClose:()=>b.setBrowseDialogOpen(!1),onNavigate:N=>{b.loadBrowsePath(N)},onConfirm:N=>{b.chooseCustomWorkspacePath(N),b.setBrowseDialogOpen(!1)}}),b.launchConfirm&&t.jsx(uo,{title:b.launchConfirm.title,description:b.launchConfirm.description,details:b.launchConfirm.details,workspaceOptions:b.launchConfirm.workspaceOptions,selectedWorkspaceKey:b.launchConfirmWorkspaceKey,onWorkspaceChange:b.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:b.launchConfirm.providerType?cn(!!b.launchConfirmResumeId):b.launchConfirm.confirmLabel,busyLabel:b.launchConfirm.providerType?void 0:b.launchConfirm.busyLabel,busy:b.launchConfirmBusy,showArgsInput:b.launchConfirm.showArgsInput,argsValue:b.launchConfirmArgs,onArgsChange:b.setLaunchConfirmArgs,showModelInput:b.launchConfirm.showModelInput,modelValue:b.launchConfirmModel,onModelChange:b.setLaunchConfirmModel,historyProviderNode:b.launchConfirm.providerType&&(b.launchConfirmSessionsLoading||b.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"}),b.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:qa()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:b.launchConfirmTextFilter,onChange:N=>b.setLaunchConfirmTextFilter(N.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:b.launchConfirmWorkspaceFilter,onChange:N=>b.setLaunchConfirmWorkspaceFilter(N.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:b.launchConfirmModelFilter,onChange:N=>b.setLaunchConfirmModelFilter(N.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:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),t.jsxs("select",{value:b.launchConfirmSortMode,onChange:N=>b.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.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:b.launchConfirmResumableOnly,onChange:N=>b.setLaunchConfirmResumableOnly(N.target.checked),disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:b.launchConfirmResumeId,onChange:N=>b.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:b.launchConfirmBusy||b.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:pp()}),b.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!b.launchConfirmSessionsLoading&&b.launchConfirmSavedSessions.length>0&&b.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),b.launchConfirmResumeId&&(()=>{const N=b.filteredLaunchConfirmSavedSessions.find(z=>z.providerSessionId===b.launchConfirmResumeId);if(!N)return null;const R=ul(N);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:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:b.handleConfirmLaunch,onCancel:b.closeLaunchConfirm}),d&&t.jsx(dl,{section:f,onSectionChange:y})]})}function pl(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 Nh(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:ks(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,f,d;const a=mr(n)?"cli":Ls(n)?"acp":"ide",i=ks(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(mr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Ch(e,s){const r=new Map;for(const n of s){const a=is(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((g,y)=>y.timestamp-g.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ma(n),u=a.filter(g=>g.unread||g.requiresAction).length,f=pl(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?sp(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 Wr(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 Ih({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:g,requestedMobileSection:y,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:m,setSelectedMachineId:p,setSection:x,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:_}){const j=o.useRef(null),I=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const v=nn(k,c),b=Math.max(Date.now(),ps(k),v.lastUpdated||0);Wr("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:ut(k),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ps(k),readAt:b}),_({sessionId:k.sessionId,providerSessionId:k.providerSessionId,tabKey:k.tabKey,routeId:k.routeId},b),l(is(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:b}).then($=>{Wr("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{Wr("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){m("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),j.current=null;return}if(i!=="chat"){j.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;j.current!==k&&(j.current=k,I(n))},[e,I,i,n,m,A]),o.useEffect(()=>{if(!u)return;const k=e.find(v=>v.tabKey===u);k&&(A(k.tabKey),m("chat"),f==null||f())},[e,f,u,m,A]),o.useEffect(()=>{if(!d)return;const k=s.find(v=>v.id===d);k&&(p(k.id),S(),x("machines"),h("inbox"),m("machine"),g==null||g())},[s,g,d,S,h,m,x,p]),o.useEffect(()=>{y&&(x(y),m("inbox"),w==null||w())},[w,y,m,x]),o.useEffect(()=>{const k=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);k.length!==0&&Wr("inbox_state",{screen:i,selectedTabKey:a,items:k.map(v=>{const b=nn(v.conversation,c);return{liveState:b,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:ut(v.conversation),serverBucket:b.inboxBucket,computedBucket:v.inboxBucket,serverUnread:b.unread,computedUnread:v.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,activityAt:ps(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Ah(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function hi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Th({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),g=o.useCallback(async(h,S,_)=>{var j;try{i("loading"),l(`Launching ${S}…`);const I={ideType:S,enableCdp:!0};(j=_==null?void 0:_.workspacePath)!=null&&j.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${S} 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,S,_)=>{if(S.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((j==null?void 0:j.error)||"Could not save workspace")}catch(j){i("error"),l(j instanceof Error?j.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var S,_,j,I,k,v;try{i("loading"),l("Starting daemon upgrade…");const b=await e(h,"daemon_upgrade",{});if((S=b==null?void 0:b.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((_=b==null?void 0:b.result)==null?void 0:_.version)||"latest"}.`);return}if((j=b==null?void 0:b.result)!=null&&j.upgraded||(I=b==null?void 0:b.result)!=null&&I.success){i("done"),l(`Upgrade to v${((k=b==null?void 0:b.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=b==null?void 0:b.result)==null?void 0:v.error)||"Upgrade failed")}catch(b){i("error"),l(b instanceof Error?b.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,S,_,j)=>{var v,b,$;const I=Date.now(),k={machineId:h,kind:S,providerType:_,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),f(k);const L={cliType:_};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?L.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(L.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(L.resumeSessionId=j.resumeSessionId),(b=j==null?void 0:j.args)!=null&&b.trim()&&(L.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),($=j==null?void 0:j.model)!=null&&$.trim()&&(L.initialModel=j.model.trim());const T=await e(h,"launch_cli",L),P=(T==null?void 0:T.result)||T,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(T!=null&&T.success&&K){f(null),i("done"),l(`${_} launched`),s(as(K));return}if(T!=null&&T.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}f(null),i("error"),l((T==null?void 0:T.error)||(P==null?void 0:P.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Mh(L)){i("loading"),l(`${_} launch requested — waiting for session…`);return}f(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,e]),m=o.useCallback(async(h,S)=>{try{const _=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),j=(_==null?void 0:_.result)??_;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),p=o.useCallback(async(h,S)=>jn(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=hi(u.workspacePath),S=r.find(j=>{var L,T,P,K;if(!j||j.type==="adhdev-daemon"||Ah(j.daemonId||j.id)!==u.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==u.kind||String(j.agentType||j.type||"")!==u.providerType)return!1;const b=String(j.providerSessionId||"");if(u.resumeSessionId&&b)return b===u.resumeSessionId;if(h){const G=hi(j.workspace||j.runtimeWorkspaceLabel);return G?G===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((K=(P=(T=(L=j.activeChat)==null?void 0:L.messages)==null?void 0:T.at)==null?void 0:P.call(T,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const _=gc({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});_&&(f(null),i("done"),l(`${u.providerType} launched`),s(as(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{f(S=>!S||S.startedAt!==u.startedAt?S:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const x=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await g(h,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await A(h,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[g,A]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:g,handleAddWorkspace:y,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:m,handleBrowseDirectory:p,handleOpenRecent:x}}function Lh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(x=>{i(x.tabKey),c("chat"),n(x)},[n,c,i]),g=o.useCallback(x=>{const h=e.find(S=>S.routeId===x.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),y=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((x,h="inbox")=>{l(x),a(),u("machines"),f(h),c("machine")},[a,f,c,u,l]),A=o.useCallback(x=>{const h=is(x);h&&w(h,"chat")},[w]),m=o.useCallback(()=>{a(),c(r)},[r,a,c]),p=o.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:g,backFromConversation:y,openMachine:w,openConversationMachine:A,backFromMachine:m,changeMachineSection:p}}function Rh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Hr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function _h({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:g,onRequestedMachineConsumed:y,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:m,onOpenRemote:p,onStopCli:x,wsStatus:h,isConnected:S,onShowHiddenConversation:_,onShowAllHiddenConversations:j,onHideConversation:I,onOpenNewSession:k,notificationStateBySessionId:v,liveSessionInboxState:b,onMarkNotificationTargetRead:$}){const[L,T]=o.useState(()=>{var ee;return((ee=e[0])==null?void 0:ee.tabKey)||null}),[P,K]=o.useState(()=>e[0]?"chat":"inbox"),[G,N]=o.useState("chats"),[R,z]=o.useState(null),[C,D]=o.useState("inbox"),O=Hs(),F="0.8.98",X=o.useMemo(()=>e.find(ee=>ee.tabKey===L)||e[0]||null,[e,L]),ne=o.useMemo(()=>X?r.find(ee=>ee.id===X.routeId):void 0,[r,X]),ke=o.useMemo(()=>!X||Ze(X)||!rt(X)?null:Ks(X),[X]),ge=o.useMemo(()=>r.filter(ee=>ee.type==="adhdev-daemon").sort(Ba),[r]),V=o.useMemo(()=>ge.find(ee=>ee.id===R)||null,[ge,R]),pe=yn({sendDaemonCommand:a,activeConv:X||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),W=Th({sendDaemonCommand:a,navigate:O,ides:r,conversations:e}),J=o.useMemo(()=>e.map(ee=>{const je=P==="chat"&&(X==null?void 0:X.tabKey)===ee.tabKey,Te=bn(ee,b,{hideOpenTaskCompleteUnread:!0,isOpenConversation:je,notificationStateBySessionId:v}),Oe=ps(ee),Pe=Tc(ee);return{conversation:ee,timestamp:Oe,preview:Pe,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,b,v,P,X]),{markConversationRead:oe}=Ih({conversations:e,machineEntries:ge,items:J,selectedConversation:X,selectedTabKey:L,screen:P,liveSessionInboxState:b,sendDaemonCommand:a,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:g,onRequestedMachineConsumed:y,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:T,setScreen:K,setSelectedMachineId:z,setSection:N,setMachineBackTarget:D,resetMachineAction:W.resetMachineAction,markNotificationTargetRead:$}),le=Lh({conversations:e,selectedConversation:X,machineBackTarget:C,markConversationRead:oe,resetMachineAction:W.resetMachineAction,setSelectedTabKey:T,setScreen:K,setSelectedMachineId:z,setSection:N,setMachineBackTarget:D}),me=o.useMemo(()=>Hr(J.filter(ee=>ee.requiresAction)),[J]),Ce=o.useMemo(()=>Hr(J.filter(ee=>ee.unread&&!ee.requiresAction)),[J]),ce=o.useMemo(()=>Hr(J.filter(ee=>!ee.unread&&!ee.requiresAction&&ee.isWorking)),[J]),xe=o.useMemo(()=>Hr(J.filter(ee=>!ee.unread&&!ee.requiresAction&&!ee.isWorking)),[J]),te=o.useMemo(()=>V?J.filter(ee=>is(ee.conversation)===V.id):[],[J,V]),ue=o.useMemo(()=>Nh(V,r),[r,V]),se=(V==null?void 0:V.version)||null,Se=!!V&&!!se&&!0&&se!==F,we=o.useMemo(()=>(V==null?void 0:V.availableProviders)||[],[V]),Re=o.useMemo(()=>we.filter(ee=>ee.category==="cli"&&ee.installed!==!1).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[we]),M=o.useMemo(()=>we.filter(ee=>ee.category==="acp"&&ee.installed!==!1).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[we]),he=o.useMemo(()=>Ch(ge,J),[J,ge]),ye=o.useCallback(async ee=>{V&&await W.handleOpenRecent(V.id,ee)},[W,V]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&X?t.jsx(ph,{selectedConversation:X,isAcp:Ze(X),isStandalone:l,selectedIdeEntry:ne,actionLogs:n,userName:u,isSendingChat:pe.isSendingChat,sendFeedbackMessage:pe.sendFeedbackMessage,isFocusingAgent:pe.isFocusingAgent,handleModalButton:pe.handleModalButton,handleRelaunch:pe.handleRelaunch,onBack:le.backFromConversation,onOpenNativeConversation:le.openNativeConversation,onOpenMachine:le.openConversationMachine,onHideConversation:I,onOpenHistory:m,onOpenRemote:p,onStopCli:x,cliViewMode:ke,onSetCliViewMode:async ee=>{if(X&&ke!==ee)try{await a(is(X)||X.routeId,"set_cli_view_mode",{targetSessionId:X.sessionId,cliType:Wt(X),mode:ee})}catch(je){const Te=ao(je);no(je)?console.warn(Te?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",je instanceof Error?je.message:String(je)):console.error("Failed to switch CLI view mode:",je)}},handleSendChat:pe.handleSendChat,handleFocusAgent:pe.handleFocusAgent}):P==="machine"&&V?t.jsx(Sh,{selectedMachineEntry:V,selectedMachineConversations:te,selectedMachineRecentLaunches:ue,cliProviders:Re,acpProviders:M,selectedMachineNeedsUpgrade:Se,appVersion:F,machineAction:W.machineAction,isStandalone:l,section:G,showBottomNav:C==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:ye,onOpenMachineDetails:()=>O(`/machines/${V.id}`),onMachineUpgrade:()=>W.handleMachineUpgrade(V.id),onLaunchDetectedIde:(ee,je)=>W.handleLaunchDetectedIde(V.id,ee,je),onAddWorkspace:(ee,je)=>W.handleAddWorkspace(V.id,ee,je),onBrowseDirectory:ee=>W.handleBrowseDirectory(V.id,ee),onLaunchWorkspaceProvider:(ee,je,Te)=>W.handleLaunchWorkspaceProvider(V.id,ee,je,Te),onListSavedSessions:ee=>W.handleListSavedSessions(V.id,ee)}):t.jsx(hh,{section:G,attentionItems:me,unreadItems:Ce,workingItems:ce,completedItems:xe,hiddenConversations:s,machineCards:he,getAvatarText:Rh,onOpenConversation:le.openConversation,onShowConversation:_,onShowAllHidden:j,onOpenNewSession:k,onOpenMachine:le.openMachine,onOpenSettings:()=>O("/settings"),onSectionChange:N,wsStatus:h,isConnected:S,isStandalone:l})})}function Gn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ph({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),g=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",g),window.addEventListener("drop",g),()=>{window.removeEventListener("dragend",g),window.removeEventListener("drop",g)}),[g]);const y=o.useCallback(p=>{p.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(p=>{if(!p.dataTransfer.types.includes("text/tab-key"))return;if(p.preventDefault(),!Gn(s,r)){d("merge");return}const x=p.currentTarget.getBoundingClientRect(),h=p.clientX-x.left,S=x.width/3;h<S?d("split-left"):h>S*2?d("split-right"):d("merge")},[s,r]),A=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),m=o.useCallback(p=>{c.current=0,u(!1);const x=p.dataTransfer.getData("text/tab-key"),h=x?e.some(_=>_.tabKey===x):!1,S=f;if(d(null),i(),!!x){if(p.preventDefault(),S==="split-left"&&Gn(s,r)){r==null||r(x,"split-left");return}if(S==="split-right"&&Gn(s,r)){r==null||r(x,"split-right");return}if(h){a(x);return}n==null||n(x)}},[e,f,s,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:g,handleDragEnter:y,handleDragOver:w,handleDragLeave:A,handleDrop:m}}function Dh(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 Eh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),g=o.useRef(null),y=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(k=>{const v=Dh(k,e);return v.length===k.length&&v.every((b,$)=>b===k[$])?k:v})},[e]);const m=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const v=new Map(k.map((b,$)=>[b,$]));return[...e].sort((b,$)=>{const L=v.get(b.tabKey)??999,T=v.get($.tabKey)??999;return L-T})},[e,f,l]);o.useEffect(()=>{var v,b;if(m.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&m.some($=>$.tabKey===i))return;const k=m[0].tabKey;k!==i&&(c(k),(b=w.current)==null||b.call(w,k))},[m,i]);const p=o.useMemo(()=>m.find(k=>k.tabKey===i),[m,i]),x=o.useCallback(k=>{var v;c(k),(v=w.current)==null||v.call(w,k)},[]),h=o.useCallback((k,v,b)=>{u($=>{var K;const L=$.filter(G=>G!==k),T=L.indexOf(v);if(T<0)return $;const P=b==="left"?T:T+1;return L.splice(P,0,k),(K=A.current)==null||K.call(A,L),L}),d(null)},[]),S=o.useCallback((k,v,b)=>{const L=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==k),T=L.indexOf(v);if(T<0)return;const P=b==="left"?T:T+1;L.splice(P,0,k),g.current=L,d(L)},[l,e]),_=o.useCallback(()=>{var v;const k=g.current;k&&(u(k),(v=A.current)==null||v.call(A,k))},[]),j=o.useCallback(()=>{g.current=null,d(null)},[]),I=o.useCallback(k=>{u(v=>{var $;const b=v.filter(L=>L!==k);return b.push(k),($=A.current)==null||$.call(A,b),b})},[]);return{activeTabId:i,activeConv:p,sortedConversations:m,previewOrderRef:g,draggingTabRef:y,selectTab:x,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:_,clearPreviewOrder:j,moveTabToEnd:I,setDraggingTabKey:k=>{y.current=k}}}function $h({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 mo({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",f=n?Pc:r?"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.";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:u}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:f}),l&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:qt,"aria-label":qt,children:[t.jsx(Gi,{size:14}),t.jsx("span",{children:qt})]})}),c&&t.jsx(ll,{}),c&&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 fl="adhdev-tab-shortcuts";function hl(){try{return JSON.parse(localStorage.getItem(fl)||"{}")}catch{return{}}}function xl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>hl()),[l,u]=o.useState(null),f=o.useCallback(g=>{const y=[];return g.metaKey&&y.push(a?"⌘":"Meta"),g.ctrlKey&&y.push("Ctrl"),g.altKey&&y.push(a?"⌥":"Alt"),g.shiftKey&&y.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(g.key)?null:(y.push(g.key.length===1?g.key.toUpperCase():g.key),y.join("+"))},[a]),d=o.useCallback(g=>{c(g);try{localStorage.setItem(fl,JSON.stringify(g))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const g=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){u(null);return}const w=f(y);if(!w)return;const A={...i};for(const[m,p]of Object.entries(A))p===w&&delete A[m];A[l]=w,d(A),u(null)};return window.addEventListener("keydown",g,!0),()=>window.removeEventListener("keydown",g,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const g=y=>{if(!(!y.ctrlKey&&!y.metaKey&&!y.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&f(y)===A){y.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e,i,s,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Kh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:g,onReorderTab:y,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:m,onDragTabKeyChange:p,onReceiveTab:x,onOpenContextMenu:h,longPressTimer:S,isGroupActive:_}){const j=Us(s),I=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",k=j.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,p(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,p]),b=o.useCallback(()=>{l.current=null,p(null),w(),A(),m()},[l,p,w,A,m]),$=o.useCallback(R=>{const z=l.current;if(!(!z||z===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const C=R.currentTarget.getBoundingClientRect(),D=R.clientX<C.left+C.width/2?"left":"right";g(z,s.tabKey,D)}},[s.tabKey,l,g]),L=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const z=R.dataTransfer.getData("text/tab-key");if(z&&z!==s.tabKey){const C=R.currentTarget.getBoundingClientRect(),D=R.clientX<C.left+C.width/2?"left":"right";c.includes(z)?y(z,s.tabKey,D):x&&x(z)}A()},[s.tabKey,c,y,x,A]),T=o.useCallback(R=>{R.stopPropagation(),u(),f(s.tabKey),d(s)},[s,d,u,f]),P=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),K=o.useCallback(R=>{const z=R.touches[0];S.current=setTimeout(()=>{h(z.clientX,z.clientY,s.tabKey)},600)},[s.tabKey,S,h]),G=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),N=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:v,onDragEnd:b,onDragOver:$,onDrop:L,onClick:T,onContextMenu:P,onTouchStart:K,onTouchEnd:G,onTouchMove:G,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:j.isGenerating?t.jsx("div",{className:"tab-spinner"}):j.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:ut(s),children:ut(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:fs(s)}):j.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[fs(s),t.jsx("span",{className:"connecting-dots"})]}):fs(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 Bh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:g,onDragStateReset:y,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:m,isGroupActive:p,allowTabShortcuts:x=!0}){const[h,S]=o.useState(null),_=o.useRef(null),j=o.useRef(null),I=o.useMemo(()=>e.map(P=>P.tabKey),[e]);xr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:v,shortcutListening:b,setShortcutListening:$,saveShortcuts:L}=xl({enabled:x,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const P=K=>{const G=document.querySelector("[data-pane-context-menu]");G&&G.contains(K.target)||S(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[h]),o.useEffect(()=>{const P=j.current;if(!P)return;const K=G=>{Math.abs(G.deltaY)<=Math.abs(G.deltaX)||(G.preventDefault(),P.scrollLeft+=G.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const T=o.useCallback((P,K,G)=>{S({x:P,y:K,tabKey:G})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>t.jsx(Kh,{conv:P,isActive:s===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:x?v[P.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:g,onDragStateReset:y,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:T,longPressTimer:_,isGroupActive:p},P.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:[x&&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:P=>{P.stopPropagation(),$(h.tabKey),S(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[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 P={...v};delete P[h.tabKey],L(P),S(null)},children:"✕ Remove shortcut"})]}),m&&t.jsxs(t.Fragment,{children:[x&&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:()=>{m(h.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&b&&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:P=>P.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Oh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:f,groupIndex:d,onFocus:g,isSplitMode:y,numGroups:w,onMoveTab:A,onReceiveTab:m,style:p,onActiveTabChange:x,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:_,onHideTab:j,isFocused:I,allowTabShortcuts:k=!0,onOpenNewSession:v,notificationStateBySessionId:b,liveSessionInboxState:$}){const{sendCommand:L}=Tt(),T=o.useRef(null),{activeTabId:P,activeConv:K,sortedConversations:G,draggingTabRef:N,selectTab:R,handleTabReorder:z,updatePreviewOrder:C,commitPreviewOrder:D,clearPreviewOrder:O,moveTabToEnd:F,setDraggingTabKey:X}=Eh({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:x,onTabOrderChange:_}),ne=yn({sendDaemonCommand:a,activeConv:K,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ke,dropAction:ge,resetDragState:V,handleDragEnter:pe,handleDragOver:W,handleDragLeave:J,handleDrop:oe}=Ph({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:m,onOwnTabDrop:F,onClearPreviewOrder:O}),le=K&&!Ze(K)&&Ks(K)==="terminal",me=o.useMemo(()=>K?s.find(te=>te.id===K.routeId):void 0,[s,K]),Ce=o.useMemo(()=>K?n.filter(te=>te.routeId===K.tabKey):[],[n,K]),ce=o.useMemo(()=>new Set(G.filter(te=>wu(te,$,{isOpenConversation:te.tabKey===P,notificationStateBySessionId:b})).map(te=>te.tabKey)),[P,$,G]);xr("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:P,dragOver:ke});const xe=o.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&L(te.routeId,cl(),{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[L]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:g,style:{...p,outline:ke?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Bh,{conversations:G,activeTabId:P,groupIndex:d,numGroups:w,unreadTabKeys:ce,draggingTabRef:N,onFocus:g,onSelectTab:R,onConversationActivated:xe,onPreviewReorder:C,onReorderTab:z,onCommitPreviewOrder:D,onClearPreviewOrder:O,onDragStateReset:V,onDragTabKeyChange:X,onMoveTab:A,onReceiveTab:m,onHideTab:j,isGroupActive:I??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:pe,onDragOver:W,onDragLeave:J,onDrop:oe,children:[ke&&t.jsx($h,{dropAction:ge,canSplit:!!(w<4&&A)}),K?t.jsx(lo,{activeConv:K,clearToken:r[K.tabKey]||0,isCliTerminal:!!le,ideEntry:me,terminalRef:T,handleModalButton:ne.handleModalButton,handleRelaunch:ne.handleRelaunch,handleSendChat:ne.handleSendChat,isSendingChat:ne.isSendingChat,sendFeedbackMessage:ne.sendFeedbackMessage,handleFocusAgent:ne.handleFocusAgent,isFocusingAgent:ne.isFocusingAgent,actionLogs:Ce,userName:f,isInputActive:!y||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(mo,{conversationsCount:e.length,isSplitMode:y,isStandalone:l,hasRegisteredMachines:u,onOpenNewSession:v})})]})]})}function Wh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:g,hasRegisteredMachines:y,userName:w,focusedGroup:A,setFocusedGroup:m,moveTabToGroup:p,splitTabRelative:x,closeGroup:h,handleResizeStart:S,groupActiveTabIds:_,setGroupActiveTabIds:j,groupTabOrders:I,setGroupTabOrders:k,toggleHiddenTab:v,onOpenNewSession:b,allowTabShortcuts:$=!0,notificationStateBySessionId:L,liveSessionInboxState:T}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,K)=>{const G=s&&n.length===r?`${n[K]}%`:void 0;return t.jsxs(lt.Fragment,{children:[s&&K>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:N=>S(K-1,N),onDoubleClick:()=>h(K),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(Oh,{style:s?{flexBasis:G??`${100/r}%`,flexGrow:G?0:1,flexShrink:G?0:1}:void 0,conversations:P,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:g,hasRegisteredMachines:y,userName:w,groupIndex:K,isFocused:s&&A===K,onFocus:()=>m(K),isSplitMode:s,numGroups:r,onMoveTab:(N,R)=>{R==="left"&&K>0?p(N,K-1):R==="right"&&K<r-1?p(N,K+1):R==="split-left"&&r<4?x(N,K,"left"):R==="split-right"&&r<4&&x(N,K,"right")},onReceiveTab:N=>p(N,K),onActiveTabChange:N=>j(R=>(R[K]??null)===(N??null)?R:{...R,[K]:N}),initialActiveTabId:_[K],initialTabOrder:I[K],onTabOrderChange:N=>k(R=>{const z=R[K]||[];return z.length===N.length&&z.every((C,D)=>C===N[D])?R:{...R,[K]:N}}),onHideTab:v,onOpenNewSession:b,allowTabShortcuts:$,notificationStateBySessionId:L,liveSessionInboxState:T})]},K)})})}function bl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?st.onScreenshot("ide-page",(d,g)=>{if(d!==e)return;const y=new FileReader;y.onload=()=>i(y.result),y.readAsDataURL(g)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=st.onStatus)==null?void 0:d.call(st,(g,y)=>{g===e&&y!=null&&y.screenshotUsage&&l(y.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const f=e?st.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(f,d)=>{const g=e?st.get(e):null;return!g||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):g.sendInput(f,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const gl="adhdev-dashboard-action-shortcuts",Hh=1200,Fh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Uh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ct(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 yl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ct("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ct("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ct("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ct("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ct("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ct("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ct("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:ct("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:ct("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:ct("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ct("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ct("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ct("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ct("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ct("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ct("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ct("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ct("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ct("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ct("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ct("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ct("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ct("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ct("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ct("toggleCliView",e)}]}function Sa(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function un(e){const s=Object.fromEntries(yl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(gl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Fh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function vl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function zh({enabled:e=!0,onTrigger:s}){const r=Uh(),[n,a]=o.useState(()=>un(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(m=>{const p=[];return m.metaKey&&p.push(r?"⌘":"Meta"),m.ctrlKey&&p.push("Ctrl"),m.altKey&&p.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&p.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(p.push(vl(m.key)),p.join("+"))},[r]),g=o.useCallback(m=>{a(m);try{localStorage.setItem(gl,JSON.stringify(m))}catch{}},[]);o.useEffect(()=>{const m=un(r),p=Object.entries(n),x=Object.entries(m);p.length===x.length&&p.every(([h,S])=>m[h]===S)||g(m)},[n,r,g]);const y=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Hh))},[]);o.useEffect(()=>{if(!i)return;const m=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){c(null),u([]);return}const x=d(p);if(!x)return;const S=!(p.metaKey||p.ctrlKey||p.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&S){u([x]);return}const j=[...l,x].slice(0,2).join(" "),I={...n};for(const[k,v]of Object.entries(I))v===j&&delete I[k];I[i]=j,g(I),c(null),u([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,d,g,i,l]),o.useEffect(()=>{if(!e||i)return;const m=p=>{if(p.defaultPrevented)return;const x=d(p);if(!x)return;const h=p.metaKey||p.ctrlKey||p.altKey;if(Sa(p.target)&&!h)return;const S=f.current.parts,_=h?[x]:[...S.slice(-1),x].slice(-2),j=_.join(" "),I=_[_.length-1],k=Object.entries(n).filter(([,T])=>!!T),v=k.find(([,T])=>T===j);if(v){p.preventDefault(),y(),s(v[0]);return}if(k.some(([,T])=>T.startsWith(`${j} `))){p.preventDefault(),f.current.parts=_,w();return}const $=k.find(([,T])=>T===I);if($){p.preventDefault(),y(),s($[0]);return}if(k.some(([,T])=>T.startsWith(`${I} `))){p.preventDefault(),f.current.parts=[I],w();return}y()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,w,e,d,s,y,i]),o.useEffect(()=>()=>y(),[y]);const A=o.useMemo(()=>yl(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:g}}function Vh({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",shortcut:n.setActiveTabShortcut}),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 wl(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function xi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!wl(n):!0}function Gh({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:wl(r)}const jl=o.createContext(null);function Sn(){const e=o.useContext(jl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Qr(e){return ut(e)||e.tabKey}function qh(e){return`remote:${e}`}function Ot(e){return e.startsWith("remote:")}function bi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qn(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 Fr(e,s){e.classList.remove(ia.className,ca.className),e.classList.add(s==="light"?ia.className:ca.className)}function gi(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 Yh(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 Xh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:Qr(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function yi(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Ot(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!==Qr(n)&&a.api.setTitle(Qr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Qr(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 vi(e,s,r){var u,f;const n=r?qh(r):null;for(const d of[...e.panels])Ot(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Ft(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=_c(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)??((f=e.panels.find(d=>!Ot(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Jh({params:e,api:s}){var g;const r=Sn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=yn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const y=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of y)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(y=>y.id===c.routeId):void 0,[r.ides,c]),f=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(mo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ze(c)&&Ks(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(lo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((g=r.scrollToBottomRequest)==null?void 0:g.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Qh({params:e}){var u;const s=Sn(),r=o.useMemo(()=>Ft([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(f=>f.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}=bl({doId:a,targetSessionId:r?hc(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(Ji,{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 Zh(){const e=Sn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(mo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function ex(e){var w,A;Yh(e);const s=Sn(),r=o.useCallback(m=>{"button"in m&&m.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const m=Ft([...s.conversationsByTabKey.values()],e.params.routeId),p=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,x=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(m==null?void 0:m.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:m!=null&&m.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:m.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=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=bn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,g=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:ut(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:m=>{var p;m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey,sourceDocument:((p=m.target)==null?void 0:p.ownerDocument)??document})},children:[g&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):d?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:ut(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:fs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:fs(n)}):t.jsx("span",{children:fs(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 tx({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:f,userName:d,toggleHiddenTab:g,actionShortcuts:y,registerActionHandlers:w,onActiveTabChange:A,onOpenNewSession:m,onRequestScrollToBottom:p,requestedActiveTabKey:x,requestedRemoteIdeId:h,onRequestedActiveTabConsumed:S,scrollToBottomRequest:_,notificationStateBySessionId:j,liveSessionInboxState:I}){var $e,ot,kt;const{theme:k}=Za(),{sendCommand:v}=Tt(),b=o.useRef(null),$=o.useRef(null),L=o.useRef(!1),T=o.useRef(!1),P=o.useRef(!1),K=o.useRef(null),G=o.useRef([]),[N,R]=o.useState(null),[z,C]=o.useState(!1),[D,O]=o.useState(!1),[F,X]=o.useState(0),ne=o.useRef(null),ke=o.useMemo(()=>rl(typeof window<"u"?window.innerWidth:1280),[]),ge=o.useRef(typeof window>"u"?{}:Df(ke)),V=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),pe=o.useMemo(()=>{const B=b.current;return B?B.groups.some(H=>{try{const U=H.model.location.type;return U!=="floating"&&U!=="popout"?!1:H.panels.some(q=>V.has(q.id))}catch{return!1}}):!1},[V,F,e]),W=o.useCallback(()=>{var B;(B=b.current)==null||B.focus()},[]),J=o.useCallback((B,H)=>{p==null||p(B,H)},[p]),oe=o.useCallback(B=>{const H=document,U=B.document;for(const Le of H.querySelectorAll('link[rel="stylesheet"]')){const Be=U.createElement("link");Be.rel="stylesheet",Be.href=Le.href,Le.crossOrigin&&(Be.crossOrigin=Le.crossOrigin),U.head.appendChild(Be)}for(const Le of H.querySelectorAll("style")){const Be=U.createElement("style");Be.textContent=Le.textContent,U.head.appendChild(Be)}const q=[];for(const Le of H.styleSheets)try{for(const Be of Le.cssRules)Be instanceof CSSStyleRule&&(Be.selectorText===":root"||Be.selectorText==="html")&&q.push(Be.cssText)}catch{}if(q.length>0){const Le=U.createElement("style");Le.textContent=q.join(`
44
- `),U.head.appendChild(Le)}const re=H.documentElement.getAttribute("data-theme");re&&U.documentElement.setAttribute("data-theme",re),U.documentElement.style.colorScheme=re==="light"?"light":"dark",U.body.className=H.body.className;const Ne=H.documentElement.getAttribute("style");Ne&&U.documentElement.setAttribute("style",Ne);const Ie=U.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),Fr(Ie,k))},[k]),le=o.useCallback(()=>{var H;const B=b.current;if(B)for(const U of B.groups)try{const q=(H=U.element)==null?void 0:H.ownerDocument;if(!q||q===document)continue;const re=q.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Fr(re,k));const Ne=document.documentElement.getAttribute("data-theme");Ne&&q.documentElement.setAttribute("data-theme",Ne),q.documentElement.style.colorScheme=Ne==="light"?"light":"dark",q.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie?q.documentElement.setAttribute("style",Ie):q.documentElement.removeAttribute("style")}catch{}},[k]),me=o.useCallback(()=>{var H;const B=b.current;if(B)for(const U of B.groups)try{const q=(H=U.element)==null?void 0:H.ownerDocument;if(!q||q===document)continue;const re=q.getElementById("dv-popout-window");if(!(re instanceof HTMLElement))continue;re.classList.add("adhdev-dockview"),Fr(re,k),re.classList.toggle("is-showing-dockview-overlay",D),re.classList.toggle("is-dragging-dockview",z)}catch{}},[z,D,k]),Ce=o.useCallback(B=>{const H=b.current;if(!H)return;const U=H.getPanel(B);U&&H.addPopoutGroup(U,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{oe(q),M();const re=V.get(B);q.document.title=re?`${ut(re)} — ADHDev`:"ADHDev — Popout"}})},[V,oe]),ce=o.useCallback(B=>{const H=b.current,U=H==null?void 0:H.getPanel(B);if(!H||!U)return;const q=H.groups.filter(re=>{var Ne;try{return((Ne=re.element)==null?void 0:Ne.ownerDocument)===document}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),xe=o.useCallback(B=>{var q;const H=b.current;if(!H)return!1;const U=H.getPanel(B);if(!U)return!1;try{return((q=U.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),te=o.useCallback(B=>{xe(B)&&ce(B),g(B)},[xe,ce,g]),ue=o.useCallback(B=>{const H=b.current,U=H==null?void 0:H.getPanel(B);!H||!U||H.addFloatingGroup(U,{width:600,height:500})},[]),se=o.useCallback(B=>{var U;const H=(U=b.current)==null?void 0:U.getPanel(B);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),Se=o.useCallback(()=>{var H,U;const B=(U=(H=b.current)==null?void 0:H.activePanel)==null?void 0:U.id;return!B||Ot(B)?null:V.has(B)?B:null},[V]),we=o.useCallback(B=>{const H=b.current,U=H==null?void 0:H.getPanel(B);if(!H||!U)return;const q=H.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});q.length>0?U.api.moveTo({group:q[0],position:"center"}):U.api.moveTo({position:"center"}),U.api.setActive()},[]),Re=o.useCallback(()=>{var Ne;const B=b.current;if(!B)return;const U=B.groups.filter(Ie=>{var Le;try{return((Le=Ie.element)==null?void 0:Le.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,q=[...B.panels];for(const Ie of q){const Le=(Ne=Ie.group.element)==null?void 0:Ne.ownerDocument,Be=Ie.group.model.location.type;Le===document&&Be==="grid"||(U&&U.id!==Ie.group.id?Ie.api.moveTo({group:U,position:"center"}):Ie.api.moveTo({position:"center"}))}const re=B.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),qn(document)},[]),M=o.useCallback(()=>{var H,U;const B=b.current;if(B)for(const q of B.groups){const re=(H=q.element)==null?void 0:H.ownerDocument;if(!re||re===document)continue;const Ne=re.getElementById("dv-popout-window");if(!(Ne instanceof HTMLElement))continue;let Ie=null,Le=re.title||"ADHDev",Be="Popout workspace";const Q=q.activePanel;if(Q)if(Ie=Q.id,Ot(Q.id)){const E=((U=Q.params)==null?void 0:U.routeId)||Q.id.slice(7),Y=Ft([...V.values()],E);Le=_c(Y),Be=Y!=null&&Y.machineName?`Remote view · ${Y.machineName}`:"Remote view"}else{const E=V.get(Q.id);Le=E?ut(E):Q.title||Q.id,Be=E?fs(E):"Dockview panel"}re.title=`${Le} — ADHDev`;let ve=re.getElementById("adhdev-popout-header");ve instanceof HTMLElement||(ve=re.createElement("div"),ve.id="adhdev-popout-header",re.body.appendChild(ve)),ve.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(";")),ve.innerHTML=`
45
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
47
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${bi(Le)}</div>
48
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${bi(Be)}</div>
49
- </div>
50
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
51
- <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
52
- <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
53
- </div>
54
- `,Ne.style.top="52px",Ne.style.height="calc(100% - 52px)";const tt=ve.querySelector("[data-adhdev-popout-focus]");tt&&(tt.onclick=()=>{window.focus()});const Ue=ve.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!Ie,Ue.style.opacity=Ie?"1":"0.5",Ue.style.cursor=Ie?"pointer":"default",Ue.onclick=()=>{var E;Ie&&ce(Ie),(E=re.defaultView)==null||E.focus()})}},[V,ce]),he=o.useCallback(B=>{var q;const H=b.current,U=H==null?void 0:H.getPanel(B);if(!(!H||!U)){U.group.model.openPanel(U),U.api.setActive(),J(B,"dockview-shortcut");try{const re=U.group.model.location;re.type==="popout"?re.getWindow().focus():qn((q=U.group.element)==null?void 0:q.ownerDocument)}catch{}}},[J]),ye=o.useCallback(B=>{const H=b.current,U=H==null?void 0:H.activePanel,q=(H==null?void 0:H.activeGroup)||(U==null?void 0:U.group);if(!H||!U||!q)return;const re=q.panels||[];if(re.length<=1)return;const Ne=re.findIndex(Be=>Be.id===U.id);if(Ne<0)return;const Ie=(Ne+B+re.length)%re.length,Le=re[Ie];Le&&(Le.group.model.openPanel(Le),Le.api.setActive(),Ot(Le.id)||J(Le.id,"dockview-shortcut"))},[J]),ee=o.useCallback(B=>{var Ue;const H=b.current,U=(H==null?void 0:H.activeGroup)||((Ue=H==null?void 0:H.activePanel)==null?void 0:Ue.group);if(!H||!U)return;const q=H.groups||[],re=q.find(E=>E.id===U.id);if(!re)return;const Ne=re.element.getBoundingClientRect(),Ie=Ne.left+Ne.width/2,Le=Ne.top+Ne.height/2,Be=(E,Y,ie,Ee)=>Math.max(0,Math.min(Y,Ee)-Math.max(E,ie)),Q=E=>{const Y=E.element.getBoundingClientRect(),ie=Y.left+Y.width/2,Ee=Y.top+Y.height/2;let Me=0,Ke=0,qe=0,_e=!1;if(B==="left"?(_e=ie<Ie,Me=Math.max(0,Ne.left-Y.right),Ke=Math.abs(Ee-Le),qe=Be(Ne.top,Ne.bottom,Y.top,Y.bottom)):B==="right"?(_e=ie>Ie,Me=Math.max(0,Y.left-Ne.right),Ke=Math.abs(Ee-Le),qe=Be(Ne.top,Ne.bottom,Y.top,Y.bottom)):B==="above"?(_e=Ee<Le,Me=Math.max(0,Ne.top-Y.bottom),Ke=Math.abs(ie-Ie),qe=Be(Ne.left,Ne.right,Y.left,Y.right)):(_e=Ee>Le,Me=Math.max(0,Y.top-Ne.bottom),Ke=Math.abs(ie-Ie),qe=Be(Ne.left,Ne.right,Y.left,Y.right)),!_e)return Number.POSITIVE_INFINITY;const We=qe>0?0:120;return Me*3+Ke+We};let ve=null,tt=Number.POSITIVE_INFINITY;for(const E of q){if(E.id===re.id)continue;const Y=Q(E);Number.isFinite(Y)&&(Y>=tt||(tt=Y,ve=E))}return ve||void 0},[]),je=o.useCallback(B=>{var q;const H=ee(B);if(!H)return;const U=H.activePanel||H.panels[0];U&&(H.model.openPanel(U),U.api.setActive(),Ot(U.id)||J(U.id,"dockview-focus"),qn((q=H.element)==null?void 0:q.ownerDocument))},[ee,J]),Te=o.useCallback((B,H)=>{const U=b.current,q=U==null?void 0:U.activePanel,re=(U==null?void 0:U.activeGroup)||(q==null?void 0:q.group);if(!U||!q||!re)return;let Ne=ee(B);!Ne&&(H!=null&&H.createGroupIfMissing)&&(Ne=U.addGroup({referenceGroup:re,direction:B})),Ne&&(q.api.moveTo({group:Ne,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Ot(q.id)||J(q.id,H!=null&&H.createGroupIfMissing?"dockview-split":"dockview-move"))},[ee,J]),{isMac:Oe,tabShortcuts:Pe,shortcutListening:Ve,setShortcutListening:Ge,saveShortcuts:ft}=xl({sortedTabKeys:e.map(B=>B.tabKey),onFocus:W,onSelectTab:he}),et=o.useCallback(()=>{var U;const B=b.current;if(!B)return;const H=B.activePanel;if(H){if(Ot(H.id)){const q=((U=H.params)==null?void 0:U.routeId)||H.id.slice(7),re=Ft(e,q);re!=null&&re.tabKey&&Ge(re.tabKey);return}V.has(H.id)&&Ge(H.id)}},[V,he,Ge,e]),it=o.useCallback(B=>{const H=[];return B.metaKey&&H.push(Oe?"⌘":"Meta"),B.ctrlKey&&H.push("Ctrl"),B.altKey&&H.push(Oe?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&H.push(Oe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(H.push(vl(B.key)),H.join("+"))},[Oe]),Qe=o.useCallback(B=>{var H,U;switch(B){case"splitActiveTabRight":Te("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Te("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=Se();q&&ue(q);return}case"popoutActiveTab":{const q=Se();q&&Ce(q);return}case"dockActiveTab":{const q=Se();if(!q)return;xe(q)?ce(q):se(q)&&we(q);return}case"focusLeftPane":je("left");return;case"focusRightPane":je("right");return;case"focusUpPane":je("above");return;case"focusDownPane":je("below");return;case"moveActiveTabToLeftPane":Te("left");return;case"moveActiveTabToRightPane":Te("right");return;case"moveActiveTabToUpPane":Te("above");return;case"moveActiveTabToDownPane":Te("below");return;case"selectPreviousGroupTab":ye(-1);return;case"selectNextGroupTab":ye(1);return;case"setActiveTabShortcut":et();return;case"hideCurrentTab":{const q=(U=(H=b.current)==null?void 0:H.activePanel)==null?void 0:U.id;q&&!Ot(q)&&te(q);return}default:return}},[ye,we,je,ue,Se,te,se,xe,ce,Te,Ce,et]);o.useEffect(()=>{if(!N)return;const B=N.sourceDocument,H=B.defaultView??window,U=q=>{const re=B.querySelector("[data-dockview-tab-context-menu]");re&&re.contains(q.target)||R(null)};return H.addEventListener("mousedown",U,!0),H!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{H.removeEventListener("mousedown",U,!0),H!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[N]);const It=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:V,hasDetachedConversationPanels:pe,ides:r,isStandalone:l,hasRegisteredMachines:u,onOpenNewSession:m,liveSessionInboxState:I,notificationStateBySessionId:j,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:te,userName:d,scrollToBottomRequest:_,tabShortcuts:Pe,openTabContextMenu:({x:B,y:H,tabKey:U,sourceDocument:q})=>R({x:B,y:H,tabKey:U,sourceDocument:q??document}),popoutTab:Ce,moveTabBackToMain:ce,isTabInPopout:xe,floatTab:ue,isTabFloating:se}),[n,s,V,pe,r,l,u,m,I,j,a,c,i,te,d,_,Pe,Ce,ce,xe,ue,se]),ht=N?Vh({isTabInPopout:xe(N.tabKey),isTabFloating:se(N.tabKey),tabShortcut:Pe[N.tabKey],actionShortcuts:y}):[],at=o.useCallback(B=>{var q;const H=b.current;if((((q=H==null?void 0:H.activePanel)==null?void 0:q.id)??null)===B.id){B.group.model.openPanel(B);return}B.group.model.openPanel(B),B.api.setActive()},[]),Ae=o.useCallback((B,H="requested-tab")=>{if(!B)return!1;const U=b.current;if(!U)return!1;const q=U.getPanel(B);return q?(at(q),J(B,H),S==null||S(),!0):!1},[at,S,J]),Xe=o.useCallback(()=>{if(P.current)return!1;const B=Ae(K.current,"stored-layout-restore");return B&&(P.current=!0),B},[Ae]),He=o.useCallback(()=>{var H;const B=b.current;B&&Pf(ke,{activeTabId:((H=B.activePanel)==null?void 0:H.id)??null,layout:B.toJSON()})},[ke]),ze=o.useCallback(()=>{Ef(ke,ge.current)},[ke]),Mt=o.useCallback(B=>{var q,re,Ne,Ie;const H=b.current;if(!H)return{kind:"grid"};const U=H.toJSON();for(const Le of U.floatingGroups||[])if((re=(q=Le.data)==null?void 0:q.views)!=null&&re.includes(B)&&Le.position)return{kind:"floating",position:Le.position};for(const Le of U.popoutGroups||[])if((Ie=(Ne=Le.data)==null?void 0:Ne.views)!=null&&Ie.includes(B))return{kind:"popout",position:Le.position,popoutUrl:Le.url};return{kind:"grid"}},[]),jt=o.useCallback(B=>{const H=b.current;if(!H)return;const U=H.getPanel(B),q=ge.current[B];if(!U||!q||q.kind==="grid")return;if(U.group.model.location.type===q.kind){delete ge.current[B],ze();return}if(q.kind==="floating"){H.addFloatingGroup(U,{x:q.position.left??24,y:q.position.top??24,width:q.position.width,height:q.position.height}),delete ge.current[B],ze();return}delete ge.current[B],ze()},[ze]);o.useEffect(()=>(w==null||w({setShortcutForActiveTab:et,restoreHiddenTabToSavedLocation:jt,activateConversationTab:he,resetAllPanelsToMain:Re,activatePreviousTabInGroup:()=>ye(-1),activateNextTabInGroup:()=>ye(1),floatActiveTab:()=>{const B=Se();B&&ue(B)},popoutActiveTab:()=>{const B=Se();B&&Ce(B)},dockActiveTab:()=>{const B=Se();B&&(xe(B)?ce(B):se(B)&&we(B))},splitActiveTabRight:()=>Te("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Te("below",{createGroupIfMissing:!0}),focusLeftPane:()=>je("left"),focusRightPane:()=>je("right"),focusUpPane:()=>je("above"),focusDownPane:()=>je("below"),moveActiveTabToLeftPane:()=>Te("left"),moveActiveTabToRightPane:()=>Te("right"),moveActiveTabToUpPane:()=>Te("above"),moveActiveTabToDownPane:()=>Te("below")}),()=>w==null?void 0:w(null)),[ye,we,ue,je,Se,se,xe,Te,ce,Ce,w,Re,jt,he,et]);const xt=o.useCallback(()=>{const B=$.current;if(!B)return;const H=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const U of H)U.setAttribute("data-adhdev-force-hidden","true")},[]),bt=o.useCallback(()=>{const B=$.current;if(!B)return;const H=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const U of H)U.removeAttribute("data-adhdev-force-hidden")},[]),Lt=o.useCallback(()=>{const B=$.current;if(!B)return;const H=B.querySelectorAll(".dv-drop-target-container");for(const re of H)re.remove();const U=B.querySelectorAll(".dv-drop-target-dropzone");for(const re of U)re.remove();const q=B.querySelectorAll(".dv-drop-target");for(const re of q)re.classList.remove("dv-drop-target")},[]),yt=o.useCallback(()=>{C(!1),O(!1),bt(),xt(),Lt(),!(typeof window>"u")&&(ne.current!=null&&window.clearTimeout(ne.current),window.requestAnimationFrame(()=>{xt(),Lt()}),ne.current=window.setTimeout(()=>{xt(),Lt(),ne.current=null},80))},[bt,xt,Lt]),Dt=o.useCallback(B=>{var U;b.current=B.api;const H=_f(ke);if(K.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&B.api.fromJSON(H.layout,{reuseExistingPanels:!1}),T.current=xi({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:f,visibleConversationCount:e.length,ides:r}),T.current||(yi(B.api,e),vi(B.api,e,h)),B.api.totalPanels===0&&e.length>0){const q=Xh(B.api,e,x);if(q){const re=B.api.getPanel(q);re&&at(re)}}else!T.current&&!Ae(x)&&Xe();L.current=!0,B.api.onDidActivePanelChange(q=>{var Ne;if(K.current=(q==null?void 0:q.id)??null,P.current=!0,M(),q&&Ot(q.id)){const Ie=((Ne=q.params)==null?void 0:Ne.routeId)||q.id.slice(7),Le=Ft(e,Ie);A((Le==null?void 0:Le.tabKey)??null),He();return}if(A((q==null?void 0:q.id)??null),He(),!q)return;const re=V.get(q.id);(re==null?void 0:re.streamSource)==="agent-stream"&&re.agentType&&v(re.routeId,cl(),{agentType:re.agentType,...re.sessionId&&{targetSessionId:re.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{He(),M(),X(q=>q+1)}),B.api.onWillDragPanel(()=>{C(!0),O(!1),xt()}),B.api.onWillDragGroup(()=>{C(!0),O(!1),xt()}),B.api.onWillShowOverlay(()=>{bt(),O(!0)}),B.api.onDidMovePanel(yt),B.api.onDidDrop(yt),B.api.onDidAddGroup(q=>{requestAnimationFrame(()=>{var re,Ne;try{const Ie=(re=q.element)==null?void 0:re.ownerDocument;if(!Ie||Ie===document)return;(Ne=Ie.getElementById("dv-popout-window"))==null||Ne.classList.add("adhdev-dockview");const Le=document.documentElement.getAttribute("data-theme");Le&&Ie.documentElement.setAttribute("data-theme",Le),Ie.body.className=document.body.className;const Be=document.documentElement.getAttribute("style");Be&&Ie.documentElement.setAttribute("style",Be)}catch{}M(),X(Ie=>Ie+1)})}),A(((U=B.api.activePanel)==null?void 0:U.id)??null)},[at,Ae,yt,bt,V,r,f,ke,xt,A,He,x,h,v,M,e]);o.useLayoutEffect(()=>{const B=b.current;if(!B||!L.current||T.current&&xi({hasStoredLayout:!0,initialDataLoaded:f,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const H=G.current,U=new Set(H),q=e.map(ve=>ve.tabKey),re=new Set(q),Ne=Gh({previousVisibleConversationCount:H.length,visibleConversationCount:e.length,ides:r});let Ie=!1;for(const ve of H)re.has(ve)||Ne||(ge.current[ve]=Mt(ve),Ie=!0);Ie&&ze(),Ne||(yi(B,e),vi(B,e,h));const Le=q.filter(ve=>!U.has(ve));let Be=!1;for(const ve of Le){const tt=B.getPanel(ve),Ue=ge.current[ve];if(!tt||!Ue||Ue.kind==="grid")continue;if(tt.group.model.location.type===Ue.kind){delete ge.current[ve],Be=!0;continue}if(Ue.kind==="floating"){B.addFloatingGroup(tt,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete ge.current[ve],Be=!0;continue}}if(Be&&ze(),G.current=q,x&&Ae(x))return;!B.activePanel&&B.panels[0]&&at(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||Xe()},[at,Ae,Xe,r,f,ze,Mt,x,h,e]),o.useEffect(()=>{L.current&&Ae(x)},[Ae,x]),o.useEffect(()=>{if(!z||typeof window>"u")return;const B=()=>yt();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[yt,z]),o.useEffect(()=>()=>{typeof window>"u"||ne.current!=null&&window.clearTimeout(ne.current)},[]),o.useEffect(()=>{const B=U=>{const q=U.target;if(!q)return;const re=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(re){const Ne=re.getAttribute("data-tab-key");if(Ne&&U.dataTransfer){const Ie=q.closest(".dv-tab")||re.closest(".dv-tab")||re;U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/tab-key",Ne),Ie instanceof HTMLElement&&U.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",B);const H=gi(b.current);for(const U of H)U.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const U of H)U.removeEventListener("dragstart",B)}},[F]),o.useEffect(()=>{var H;const B=(H=$.current)==null?void 0:H.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Fr(B,k),le(),M(),me()},[M,me,le,k]),o.useEffect(()=>{M(),me()},[M,me]),o.useEffect(()=>{const B=H=>{if(H.defaultPrevented||Ve)return;const U=it(H);if(!U)return;const q=H.metaKey||H.ctrlKey||H.altKey;Sa(H.target)&&!q||un(Oe).setActiveTabShortcut!==U||(H.preventDefault(),H.stopPropagation(),et())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[it,Oe,Ve,et]),o.useEffect(()=>{const B=$.current;if(!B)return;const H=U=>{var Le,Be;if(!U.isTrusted)return;const q=(Be=(Le=U.target)==null?void 0:Le.closest)==null?void 0:Be.call(Le,".dv-scrollable");if(!q)return;U.preventDefault(),U.stopPropagation();const re=Math.abs(U.deltaX),Ne=Math.abs(U.deltaY),Ie=re>Ne?U.deltaX:U.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:U.deltaMode,bubbles:!1,cancelable:!0}))};return B.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>B.removeEventListener("wheel",H,{capture:!0})},[]),o.useEffect(()=>{const B=gi(b.current);if(B.length===0)return;const H=B.map(U=>{let q=[],re=null;const Ne=()=>{re!=null&&U.clearTimeout(re),re=null,q=[]},Ie=()=>{re!=null&&U.clearTimeout(re),re=U.setTimeout(()=>{re=null,q=[]},1200)},Le=Q=>{if(!Q.ctrlKey&&!Q.metaKey&&!Q.altKey)return;const ve=it(Q);if(!ve)return;const tt=hl();for(const[Ue,E]of Object.entries(tt))if(e.some(Y=>Y.tabKey===Ue)&&E===ve){Q.preventDefault(),he(Ue);return}},Be=Q=>{if(Q.defaultPrevented||Ve)return;const ve=it(Q);if(!ve)return;const tt=Q.metaKey||Q.ctrlKey||Q.altKey;if(Sa(Q.target)&&!tt)return;const Ue=un(Oe),E=Object.entries(Ue).filter(([We,Ut])=>!!Ut&&(We==="splitActiveTabRight"||We==="splitActiveTabDown"||We==="floatActiveTab"||We==="popoutActiveTab"||We==="dockActiveTab"||We==="focusLeftPane"||We==="focusRightPane"||We==="focusUpPane"||We==="focusDownPane"||We==="moveActiveTabToLeftPane"||We==="moveActiveTabToRightPane"||We==="moveActiveTabToUpPane"||We==="moveActiveTabToDownPane"||We==="selectPreviousGroupTab"||We==="selectNextGroupTab"||We==="setActiveTabShortcut"||We==="hideCurrentTab")),Y=tt?[ve]:[...q.slice(-1),ve].slice(-2),ie=Y.join(" "),Ee=Y[Y.length-1],Me=E.find(([,We])=>We===ie);if(Me){Q.preventDefault(),Ne(),Qe(Me[0]);return}if(E.some(([,We])=>We.startsWith(`${ie} `))){Q.preventDefault(),q=Y,Ie();return}const qe=E.find(([,We])=>We===Ee);if(qe){Q.preventDefault(),Ne(),Qe(qe[0]);return}if(E.some(([,We])=>We.startsWith(`${Ee} `))){Q.preventDefault(),q=[Ee],Ie();return}Ne()};return U.addEventListener("keydown",Le),U.addEventListener("keydown",Be),()=>{Ne(),U.removeEventListener("keydown",Le),U.removeEventListener("keydown",Be)}});return()=>{for(const U of H)U()}},[it,Oe,F,he,Ve,Qe,e]);const Z=k==="light"?ia:ca,De=((kt=(ot=($e=b.current)==null?void 0:$e.activePanel)==null?void 0:ot.group.element)==null?void 0:kt.ownerDocument)??document;return t.jsxs(jl.Provider,{value:It,children:[t.jsx("div",{ref:$,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(hd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${z?" is-dragging-dockview":""}${D?" is-showing-dockview-overlay":""}`,components:{conversation:Jh,remote:Qh},defaultTabComponent:ex,watermarkComponent:Zh,onReady:Dt,singleTabMode:"default",tabAnimation:"smooth",theme:Z,popoutUrl:"/popout.html"})}),N&&cr.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:N.x,top:N.y},children:ht.map(B=>{if(B.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},B.id);let H=t.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),U=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(su,{size:13,className:"shrink-0 opacity-70"}),U=()=>{we(N.tabKey),R(null)};break;case"moveBackToMain":H=t.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ce(N.tabKey),R(null)};break;case"floatAsPanel":H=t.jsx(tu,{size:13,className:"shrink-0 opacity-70"}),U=()=>{ue(N.tabKey),R(null)};break;case"openInNewWindow":H=t.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),U=()=>{Ce(N.tabKey),R(null)};break;case"setShortcut":U=q=>{q.stopPropagation(),Ge(N.tabKey),R(null)};break;case"removeShortcut":H=t.jsx(At,{size:13,className:"shrink-0 opacity-70"}),U=()=>{const q={...Pe};delete q[N.tabKey],ft(q),R(null)};break;case"hideTab":H=t.jsx(zi,{size:13,className:"shrink-0 opacity-70"}),U=()=>{te(N.tabKey),R(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 ${B.tone==="muted"?"text-text-muted":""}`,onClick:U,children:[H,t.jsx("span",{className:"flex-1 min-w-0",children:B.label}),B.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:B.shortcut}):null]},B.id)})}),N.sourceDocument.body),Ve&&cr.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:()=>Ge(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.stopPropagation(),children:[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. ",Oe?"⌘+1":"Ctrl+1",", ",Oe?"⌥+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"})]})}),De.body)]})}const kl="adhdev-recent-launch-args-v1",sx=8;function rx(e){return String(e||"").trim().replace(/\s+/g," ")}function Sl(e,s){return`${e.trim()}::${s.trim()}`}function Nl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(kl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function nx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(kl,JSON.stringify(e))}catch{}}function Cl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Nl().byKey[Sl(r,n)])==null?void 0:i.items)||[]}function Il(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=rx(r);if(!n||!a||!i)return;const c=Nl(),l=Sl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(g=>g!==i)].slice(0,sx);c.byKey[l]={items:f},nx(c)}function ax(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 po(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 Al(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=po((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 Ml(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ps(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 Yn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ox(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function wi(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function ji(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 ix(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function cx(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 lx(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 dx({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var z;const[l,u]=o.useState(n||((z=e[0])==null?void 0:z.id)||null),[f,d]=o.useState(""),[g,y]=o.useState(null),[w,A]=o.useState(!1);o.useEffect(()=>{var C;u(n||((C=e[0])==null?void 0:C.id)||null)},[n,e]);const m=o.useMemo(()=>e.find(C=>C.id===l)||e[0]||null,[l,e]),p=o.useMemo(()=>r.filter(C=>{if(C.type==="adhdev-daemon"||C.transport!=="pty")return!1;const D=ox(C.daemonId||C.id);return!!(m!=null&&m.id)&&D===m.id}),[m==null?void 0:m.id,r]),x=Qc(m==null?void 0:m.id,{enabled:!!(m!=null&&m.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=x.diagnostics,S=x.loading,_=x.applyDiagnostics,j=o.useMemo(()=>{const C=new Map;for(const D of p){const O=s.find(F=>F.sessionId===D.sessionId||F.routeId===D.id);D.sessionId&&O&&C.set(D.sessionId,O)}return C},[p,s]),I=o.useCallback(async()=>{if(m!=null&&m.id){A(!0);try{const C=await a(m.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=Yn(C);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");_(D.diagnostics||D.result||null),d("")}catch(C){const D=C instanceof Error?C.message:"Could not load hosted runtime diagnostics";d(D)}finally{A(!1)}}},[m==null?void 0:m.id,_,a]);o.useEffect(()=>{!(m!=null&&m.id)||h||S||w||I()},[m==null?void 0:m.id,h,S,I,w]);const k=o.useCallback(async(C,D)=>{if(!(m!=null&&m.id)||C==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
55
- This will terminate the hosted runtime.`))return;const O=`${C}:${D.sessionId}`;y(O);try{const F=await a(m.id,C,{sessionId:D.sessionId}),X=Yn(F);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const ne=C==="session_host_resume_session"?"resumed":C==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${ne}: ${D.displayName}`,"success"),await I()}catch(F){const X=F instanceof Error?F.message:"Session host action failed";d(X),nt.showToast(X,"warning")}finally{y(F=>F===O?null:F)}},[m==null?void 0:m.id,I,a]),v=o.useCallback(async()=>{if(!(!(m!=null&&m.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.`))){y("session_host_prune_duplicate_sessions");try{const D=await a(m.id,"session_host_prune_duplicate_sessions",{}),O=Yn(D);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Duplicate prune failed");const F=O.result||{},X=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,ne=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;nt.showToast(`Pruned ${X} duplicate runtime(s) across ${ne} group(s)`,"success"),await I()}catch(D){const O=D instanceof Error?D.message:"Duplicate prune failed";d(O),nt.showToast(O,"warning")}finally{y(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[m==null?void 0:m.id,I,a]),b=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((C,D)=>(D.lastActivityAt||0)-(C.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)||[]}:Al(b),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,b]),L=$.liveRuntimes,T=$.recoverySnapshots,P=$.inactiveRecords,K=o.useMemo(()=>lx(L),[L]),G=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(C=>C.level==="warn"||C.level==="error")||null,[h==null?void 0:h.recentLogs]),N=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),R=(C,D)=>{var J,oe;const O=j.get(C.sessionId),F=p.find(le=>le.sessionId===C.sessionId),X=g===`session_host_resume_session:${C.sessionId}`,ne=g===`session_host_restart_session:${C.sessionId}`,ke=g===`session_host_stop_session:${C.sessionId}`,ge=po(C.meta),V=typeof((J=C.meta)==null?void 0:J.runtimeRecoveryError)=="string"?String(C.meta.runtimeRecoveryError):"",pe=D==="recovery"?"Recover":"Resume",W=Ml(D);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:C.displayName||(F==null?void 0:F.runtimeDisplayName)||(F==null?void 0:F.cliName)||C.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${cx(C.lifecycle)}`,children:C.lifecycle}),ge&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:ge})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:C.workspaceLabel||(F==null?void 0:F.runtimeWorkspaceLabel)||C.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:C.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((oe=C.writeOwner)==null?void 0:oe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ix(C.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(La,{size:11})," ",C.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",ji(C.lastActivityAt),C.osPid?` · pid ${C.osPid}`:"",` · Next: ${W}`]}),V&&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:V})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[O&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(O),c()},children:"Open chat"}),D==="recovery"&&(C.lifecycle==="interrupted"||C.lifecycle==="failed"||C.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!g,onClick:()=>{k("session_host_resume_session",C)},children:X?`${pe}ing…`:pe}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!g,onClick:()=>{k("session_host_restart_session",C)},children:ne?"Restarting…":"Restart"}),D==="live"&&(C.lifecycle==="running"||C.lifecycle==="starting"||C.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:!!g,onClick:()=>{k("session_host_stop_session",C)},children:ke?"Stopping…":"Stop"})]})]},C.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:C=>C.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(es,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(m==null?void 0:m.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:S||w,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Fs,{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(At,{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(C=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${C.id===(m==null?void 0:m.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>u(C.id),children:C.label},C.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[f&&!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(js,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:f})]})]})}),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:ji(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:wi(h.hostStartedAt)})]})]}),G&&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(js,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:G.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(fn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[K>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:g==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:g==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${K}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[p.length," dashboard session",p.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:Ps("live")}),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 live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:L.map(C=>R(C,"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:Ps("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(C=>R(C,"recovery"))})]}),P.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:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:P.map(C=>R(C,"inactive"))})]}),N.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:N.map(C=>{const D=b.find(O=>O.sessionId===C.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(D==null?void 0:D.displayName)||C.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[C.action,C.lifecycle?` · ${C.lifecycle}`:"",C.detail?` · ${C.detail}`:"",C.error?` · ${C.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${C.success===!1?"text-red-300":"text-text-secondary"}`,children:wi(C.timestamp)})]},`${C.sessionId}:${C.timestamp}:${C.action}`)})})]})]})]})]})})}function Tl(e){return!e.hasLoadedInitialResults&&!e.isLoading}function sr({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 Ll({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?ul(n):null;return t.jsxs(sr,{title:"Saved history",description:qa(),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:xp()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Xn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(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 Ur(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ux({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:f,onOpenConversation:d}){var yt,Dt;const g=yr(),y=o.useMemo(()=>[...e].sort(Ba),[e]),[w,A]=o.useState(((yt=y[0])==null?void 0:yt.id)||""),m=o.useMemo(()=>y.find(Z=>Z.id===w)||y[0],[w,y]),p=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[m]),x=(m==null?void 0:m.defaultWorkspaceId)||null,[h,S]=o.useState(""),[_,j]=o.useState(""),[I,k]=o.useState(Xn(y[0])),[v,b]=o.useState(""),[$,L]=o.useState(""),[T,P]=o.useState([]),[K,G]=o.useState(""),[N,R]=o.useState([]),[z,C]=o.useState(!1),[D,O]=o.useState(!1),[F,X]=o.useState(""),[ne,ke]=o.useState(!1),[ge,V]=o.useState(()=>wt()),[pe,W]=o.useState(!1),[J,oe]=o.useState(null),[le,me]=o.useState(!1),[Ce,ce]=o.useState(""),[xe,te]=o.useState(!1),[ue,se]=o.useState(""),[Se,we]=o.useState([]),[Re,M]=o.useState(!1),[he,ye]=o.useState(""),[ee,je]=o.useState(!1),Te=o.useRef(null),Oe=o.useRef(0);o.useEffect(()=>{var Z;!w&&((Z=y[0])!=null&&Z.id)&&A(y[0].id)},[w,y]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||g(m.id,{minFreshMs:3e4}).catch(()=>{})},[g,m]);const Pe=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),Ve=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),Ge=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[m]),ft=o.useMemo(()=>I==="cli"?Pe.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ve.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Ge,[Ve,I,Pe,Ge]);o.useEffect(()=>{var De;if(!m)return;if(Te.current!==m.id){Te.current=m.id,S(x||((De=p[0])==null?void 0:De.id)||"__home__"),j(""),k(Xn(m)),b(""),L(""),G(""),R([]),O(!1),X(""),V(wt()),ce("");return}S($e=>{var ot;return $e==="__custom__"||$e==="__home__"||p.some(kt=>kt.id===$e)?$e:x||((ot=p[0])==null?void 0:ot.id)||"__home__"}),k($e=>$e==="ide"&&Ge.length>0||$e==="cli"&&Pe.length>0||$e==="acp"&&Ve.length>0?$e:Xn(m))},[Ve.length,Pe.length,x,Ge.length,m,p]),o.useEffect(()=>{var Z;I&&(ft.some(De=>De.id===v)||b(((Z=ft[0])==null?void 0:Z.id)||""))},[I,ft,v]);const et=o.useCallback(async(Z,De)=>{const $e=Oe.current+1;return Oe.current=$e,C(!0),X(""),u(Z,De).then(ot=>{Oe.current===$e&&R(ot)}).catch(ot=>{Oe.current===$e&&(R([]),X(ot instanceof Error?ot.message:"Could not load saved sessions"))}).finally(()=>{Oe.current===$e&&(C(!1),O(!0))})},[u]),it=o.useCallback((Z,De)=>{P(Cl(Z,De))},[]);o.useEffect(()=>{Oe.current+=1,G(""),V(wt()),!m||!v||I==="ide"?P([]):it(m.id,v),O(!1),R([]),X(""),C(!1)},[I,it,et,m,v]),o.useEffect(()=>{if(!K)return;const Z=N.find(De=>De.providerSessionId===K);Z!=null&&Z.canResume||G("")},[N,K]);const Qe=h==="__custom__"?_.trim():h==="__home__"?"":((Dt=p.find(Z=>Z.id===h))==null?void 0:Dt.path)||"",It=o.useMemo(()=>m?r.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[r,m]),ht=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),at=o.useCallback(Z=>{const De=String(Z.workspace||"").trim();if(!De)return;const $e=p.find(ot=>Ur(ot.path)===Ur(De));if($e){S($e.id),j("");return}S("__custom__"),j(De)},[p]),Ae=o.useCallback(Z=>{const De=String(Z.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const $e=p.find(ot=>Ur(ot.path)===Ur(De));return $e?{workspaceId:$e.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),Xe=o.useMemo(()=>N.find(Z=>Z.providerSessionId===K)||null,[N,K]),He=o.useMemo(()=>{var De;if(I!=="cli"||!m||!v)return null;const Z=((De=Pe.find($e=>$e.type===v))==null?void 0:De.displayName)||v;return{routeId:m.id,daemonId:m.id,providerSessionId:K||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:v,status:"idle",title:Z,messages:[],ideType:v,workspaceName:Qe,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${v}`,machineName:_t(m,{fallbackId:m.id})}},[I,Pe,Qe,m,K,v]),ze=o.useCallback(()=>{var De;if(!m)return;S("__custom__"),te(!0),ye("");const Z=wn(m.platform,vn(_.trim(),Qe,It,ht,m.defaultWorkspacePath,(De=p.find($e=>$e.id===x))==null?void 0:De.path,p.map($e=>$e.path)));M(!0),a(m.id,Z).then($e=>{se($e.path),j($e.path),we($e.directories)}).catch($e=>{ye($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>M(!1))},[_,x,ht,It,a,Qe,m,p]),Mt=o.useCallback(Z=>{m&&(M(!0),ye(""),a(m.id,Z).then(De=>{se(De.path),j(De.path),we(De.directories)}).catch(De=>{ye(De instanceof Error?De.message:"Could not load folder")}).finally(()=>M(!1)))},[a,m]),jt=o.useCallback(async()=>{if(!m||!Qe)return;je(!0),ce("");const Z=await i(m.id,Qe);if(je(!1),!Z.ok){ce(Z.error||"Could not save workspace");return}ce("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Qe,m]),xt=o.useCallback(async()=>{if(!m||!I||!v)return;me(!0),ce("");const Z=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],De=I==="ide"?await c(m.id,v,{workspacePath:Qe||null}):await l(m.id,I,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Qe||null,resumeSessionId:I==="cli"&&K?K:null,cliArgs:Z});if(me(!1),!De.ok){ce(De.error||"Could not start session");return}I!=="ide"&&$.trim()&&(Il(m.id,v,$),it(m.id,v)),n()},[I,$,it,n,c,l,Qe,m,K,v,h]),bt=I?Ec(I,I==="cli"&&!!K):"Start",Lt=I?$c(I,I==="cli"&&!!K):"Starting…";return m?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(At,{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(sr,{title:"Machine",children:t.jsx("select",{value:m.id,onChange:Z=>A(Z.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:le,children:y.map(Z=>t.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))})}),I==="cli"&&t.jsx(sr,{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:le||!m,onClick:()=>W(!0),children:[t.jsx(es,{size:14}),fp()]})}),t.jsxs(sr,{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:ze,disabled:le,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:Z=>{const De=Z.target.value;S(De),De==="__custom__"?ze():ce("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),p.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===x?"⭐ ":"",gn(Z.path,Z.label)||Z.path]},Z.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.":Qe||"Select a workspace folder."}),h==="__custom__"&&Qe&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ze,disabled:le,children:[t.jsx(Es,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:jt,disabled:le||ee,children:ee?"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:Pe.length>0},{id:"ide",label:"IDE",enabled:Ge.length>0},{id:"acp",label:"ACP",enabled:Ve.length>0}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>k(Z.id),disabled:!Z.enabled||le,children:Z.label},Z.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:[ft.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>b(Z.id),disabled:le,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.meta})]},Z.id)),ft.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(sr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:Z=>L(Z.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:le}),T.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:T.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(Z),disabled:le,title:Z,children:Z},Z))})]}),I==="cli"&&t.jsx(Ll,{busy:le,savedSessionsLoading:z,savedSessionsError:F,selectedSession:Xe,onRefresh:()=>{!m||!v||et(m.id,v)},onOpenHistory:()=>{!m||!v||(ke(!0),Tl({hasLoadedInitialResults:D,isLoading:z})&&et(m.id,v))},onClearSelection:()=>G("")}),Ce&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Ce.includes("saved")||Ce.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Ce})]}),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:le,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:xt,disabled:le||!I||!v||h==="__custom__"&&!Qe,children:[t.jsx(_a,{size:14}),le?Lt:bt]})]})]})}),xe&&t.jsx(kn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:ue,directories:Se,busy:Re,error:he,onClose:()=>te(!1),onNavigate:Mt,onConfirm:Z=>{j(Z),se(Z),S("__custom__"),te(!1)}}),ne&&He&&t.jsx(Ja,{activeConv:He,ides:[],isCreatingChat:!1,isRefreshingHistory:z,savedSessions:N,isSavedSessionsLoading:z,isResumingSavedSessionId:J,savedHistoryFilters:ge,onSavedHistoryFiltersChange:V,onClose:()=>ke(!1),onNewChat:()=>{G(""),ke(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!v||et(m.id,v)},onResumeSavedSession:Z=>{if(!m||!v||J||!Z.canResume)return;const De=Ae(Z);G(Z.providerSessionId),at(Z),oe(Z.providerSessionId),ke(!1),me(!0),ce(""),l(m.id,"cli",v,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:Z.providerSessionId}).then($e=>{if(!$e.ok){ce($e.error||"Could not resume session");return}n()}).finally(()=>{me(!1),oe($e=>$e===Z.providerSessionId?null:$e)})}}),pe&&m&&t.jsx(dx,{machineCards:[{id:m.id,label:_t(m,{fallbackId:m.id}),subtitle:[m.platform||"machine",pl(m)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:m.id,sendDaemonCommand:f,onOpenConversation:Z=>{W(!1),n(),d(Z)},onClose:()=>W(!1)})]}):null}function mx(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 px(e){return e instanceof Error?e.message:String(e||"")}function fx(e){const s=px(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function hx({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:f,mobileChatConversations:d,hiddenConversations:g,ides:y,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,initialDataLoaded:h,userName:S,requestedMobileTabKey:_,onRequestedMobileTabConsumed:j,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:b,containerRef:$,isSplitMode:L,numGroups:T,groupSizes:P,groupedConvs:K,clearedTabs:G,focusedGroup:N,setFocusedGroup:R,moveTabToGroup:z,splitTabRelative:C,closeGroup:D,handleResizeStart:O,groupActiveTabIds:F,setGroupActiveTabIds:X,groupTabOrders:ne,setGroupTabOrders:ke,toggleHiddenTab:ge,visibleConversations:V,requestedDesktopTabKey:pe,onRequestedDesktopTabConsumed:W,onDesktopActiveTabChange:J,onRequestScrollToBottom:oe,onHideConversation:le,onShowHiddenConversation:me,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ce,machineEntries:xe,onBrowseMachineDirectory:te,onSaveMachineWorkspace:ue,onLaunchMachineIde:se,onLaunchMachineProvider:Se,onListMachineSavedSessions:we,notifications:Re,notificationUnreadCount:M,notificationStateBySessionId:he,liveSessionInboxState:ye,onMarkNotificationRead:ee,onMarkNotificationUnread:je,onDeleteNotification:Te,onMarkNotificationTargetRead:Oe}){const Pe=lt.useRef(null),[Ve,Ge]=lt.useState(!1),[ft,et]=lt.useState(!1),[it,Qe]=lt.useState(!1),[It,ht]=lt.useState(!1),at=lt.useCallback(Q=>{var ve;cr.flushSync(()=>{me(Q)}),(ve=Pe.current)==null||ve.restoreHiddenTabToSavedLocation(Q.tabKey)},[me]),Ae=lt.useCallback(Q=>{var tt;const ve=d.find(Ue=>ur(Ue,Q))||g.find(Ue=>ur(Ue,Q));ve&&(g.some(Ue=>Ue.tabKey===ve.tabKey)&&at(ve),J(ve.tabKey),(tt=Pe.current)==null||tt.activateConversationTab(ve.tabKey),oe(ve.tabKey,"notification-open")),ee(Q.id),(Q.sessionId||Q.providerSessionId||Q.tabKey||Q.routeId)&&Oe({sessionId:Q.sessionId,providerSessionId:Q.providerSessionId,tabKey:Q.tabKey,routeId:Q.routeId}),Ge(!1)},[at,g,d,J,ee,Oe,oe]),[Xe,He]=lt.useState(!1),[ze,Mt]=lt.useState("quickstart"),[jt,xt]=lt.useState("workspace"),bt=!e&&!s,Lt=lt.useCallback(Q=>{Ge(Q),Q&&et(!1)},[]),yt=lt.useCallback(Q=>{et(Q),Q&&Ge(!1)},[]),Dt=lt.useCallback(()=>{var ve;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((ve=Pe.current)==null||ve.resetAllPanelsToMain(),et(!1))},[]),Z=lt.useCallback(()=>{Mt(V.length===0?"quickstart":"shortcuts"),xt("workspace"),Qe(!0),Ge(!1),et(!1)},[V.length]),De=lt.useCallback(async Q=>{var Y;if(!r)return;const ve=(Y=r.modalButtons)==null?void 0:Y[Q];if(!ve)return;const tt=pr(r);if(!tt)return;const Ue=ve.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),E=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ue);try{await A(tt,"resolve_action",{button:ve,action:E?"approve":"reject",buttonIndex:Q,..._s(r)})}catch(ie){fx(ie)||console.error("[Shortcut approval] Failed:",ie)}},[r,A]),{isMac:$e,actionDefinitions:ot,actionShortcuts:kt,shortcutListening:B,shortcutListeningDraft:H,setShortcutListening:U,setShortcutListeningDraft:q,saveShortcuts:re}=zh({enabled:bt&&!it,onTrigger:Q=>{var ve,tt,Ue,E,Y,ie,Ee,Me,Ke,qe,_e,We,Ut,zs,Vs,jr;if(Q==="openShortcutHelp"){Z();return}if(Q==="hideCurrentTab"){r&&le(r);return}if(Q==="toggleHiddenTabs"){yt(!ft);return}if(Q==="openHistoryForActiveTab"){r&&!Ze(r)&&i(r);return}if(Q==="openRemoteForActiveTab"){r&&!rt(r)&&!Ze(r)&&c(r);return}if(Q==="splitActiveTabRight"){(ve=Pe.current)==null||ve.splitActiveTabRight();return}if(Q==="splitActiveTabDown"){(tt=Pe.current)==null||tt.splitActiveTabDown();return}if(Q==="floatActiveTab"){(Ue=Pe.current)==null||Ue.floatActiveTab();return}if(Q==="popoutActiveTab"){(E=Pe.current)==null||E.popoutActiveTab();return}if(Q==="dockActiveTab"){(Y=Pe.current)==null||Y.dockActiveTab();return}if(Q==="focusLeftPane"){(ie=Pe.current)==null||ie.focusLeftPane();return}if(Q==="focusRightPane"){(Ee=Pe.current)==null||Ee.focusRightPane();return}if(Q==="focusUpPane"){(Me=Pe.current)==null||Me.focusUpPane();return}if(Q==="focusDownPane"){(Ke=Pe.current)==null||Ke.focusDownPane();return}if(Q==="moveActiveTabToLeftPane"){(qe=Pe.current)==null||qe.moveActiveTabToLeftPane();return}if(Q==="moveActiveTabToRightPane"){(_e=Pe.current)==null||_e.moveActiveTabToRightPane();return}if(Q==="moveActiveTabToUpPane"){(We=Pe.current)==null||We.moveActiveTabToUpPane();return}if(Q==="moveActiveTabToDownPane"){(Ut=Pe.current)==null||Ut.moveActiveTabToDownPane();return}if(Q==="triggerPrimaryApprovalAction"){De(0);return}if(Q==="triggerSecondaryApprovalAction"){De(1);return}if(Q==="triggerTertiaryApprovalAction"){De(2);return}if(Q==="setActiveTabShortcut"){(zs=Pe.current)==null||zs.setShortcutForActiveTab();return}if(Q==="selectPreviousGroupTab"){(Vs=Pe.current)==null||Vs.activatePreviousTabInGroup();return}if(Q==="selectNextGroupTab"){(jr=Pe.current)==null||jr.activateNextTabInGroup();return}!r||!rt(r)||Ze(r)||Q==="toggleCliView"&&f(u==="chat"?"terminal":"chat")}}),Ne=lt.useCallback(()=>{Qe(!1),U(null),q([])},[U,q]),Ie=lt.useMemo(()=>jt==="all"?ot:ot.filter(Q=>mx(Q)===jt),[ot,jt]),Le=lt.useCallback(()=>{const Q=Object.fromEntries(ot.map(ve=>[ve.id,""]));re(Q)},[ot,re]),Be=lt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Q=Object.fromEntries(ot.map(ve=>[ve.id,ve.defaultShortcut]));re(Q)},[ot,re]);return lt.useEffect(()=>{const Q=ve=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?ve.metaKey&&ve.key.toLowerCase()==="w":ve.ctrlKey&&ve.key.toLowerCase()==="w")&&(ve.preventDefault(),r&&le&&le(r))};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[r,le]),lt.useEffect(()=>{if(!it||B)return;const Q=ve=>{ve.key==="Escape"&&(ve.preventDefault(),Ne())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[Ne,it,B]),lt.useEffect(()=>{if(!bt){He(!1);return}He(!0);const Q=window.setTimeout(()=>{He(!1)},1e4);return()=>window.clearTimeout(Q)},[bt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(lp,{activeConv:r,wsStatus:n,isConnected:a,conversations:V,hiddenConversations:g,onOpenHistory:i,onHideConversation:le,onShowConversation:at,onShowAllHidden:Ce,onResetPanelsToMain:Dt,notifications:Re,notificationUnreadCount:M,onOpenNotification:Ae,onMarkNotificationRead:ee,onMarkNotificationUnread:je,onDeleteNotification:Te,inboxOpen:Ve,onInboxOpenChange:Lt,hiddenOpen:ft,onHiddenOpenChange:yt,onOpenNewSession:s?void 0:()=>ht(!0),actionShortcuts:kt,onOpenRemote:()=>{!r||rt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f}),e?t.jsx(_h,{conversations:d,hiddenConversations:g,ides:y,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,userName:S,requestedActiveTabKey:_,onRequestedActiveTabConsumed:j,requestedMachineId:I,onRequestedMachineConsumed:k,requestedMobileSection:v,onRequestedMobileSectionConsumed:b,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:at,onShowAllHiddenConversations:Ce,onOpenNewSession:()=>ht(!0),notificationStateBySessionId:he,liveSessionInboxState:ye,onMarkNotificationTargetRead:Oe}):s?t.jsx(Wh,{containerRef:$,isSplitMode:L,numGroups:T,groupSizes:P,groupedConvs:K,clearedTabs:G,ides:y,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,hasRegisteredMachines:xe.length>0,userName:S,focusedGroup:N,setFocusedGroup:R,moveTabToGroup:z,splitTabRelative:C,closeGroup:D,handleResizeStart:O,groupActiveTabIds:F,setGroupActiveTabIds:X,groupTabOrders:ne,setGroupTabOrders:ke,toggleHiddenTab:ge,onOpenNewSession:()=>ht(!0),allowTabShortcuts:!1,notificationStateBySessionId:he,liveSessionInboxState:ye}):t.jsx(tx,{visibleConversations:V,clearedTabs:G,ides:y,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,hasRegisteredMachines:xe.length>0,initialDataLoaded:h,userName:S,toggleHiddenTab:ge,actionShortcuts:kt,registerActionHandlers:Q=>{Pe.current=Q},onActiveTabChange:J,requestedActiveTabKey:pe,onRequestedActiveTabConsumed:W,onRequestScrollToBottom:oe,scrollToBottomRequest:ce,onOpenNewSession:()=>ht(!0),notificationStateBySessionId:he,liveSessionInboxState:ye}),It&&t.jsx(ux,{machines:xe,conversations:d,ides:y,onClose:()=>ht(!1),onBrowseDirectory:te,onSaveWorkspace:ue,onLaunchIde:se,onLaunchProvider:Se,onListSavedSessions:we,sendDaemonCommand:A,onOpenConversation:Q=>{ht(!1),me(Q),J(Q.tabKey),oe(Q.tabKey,"conversation-open")}}),it&&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:Ne,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:Q=>Q.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:Ne,"aria-label":"Close dashboard guide",children:t.jsx(At,{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(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${ze===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>Mt(Q.id),children:Q.label},Q.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 ",$e?"⌥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(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${jt===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>xt(Q.id),children:Q.label},Q.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,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:Be,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ie.map(Q=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${B===Q.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:Q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Q.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:B===Q.id?H.length>0?`${H.join(" ")} ...`:"Listening...":kt[Q.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{U(Q.id),q([])},children:B===Q.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const ve={...kt};ve[Q.id]="",re(ve)},children:"Disable"})]})]})},Q.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",$e?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Z,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 ${Xe?"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:"?"}),Xe&&t.jsx("span",{children:"Guide"})]})]})}const Jn=[{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 xx({onClose:e}){const[s,r]=o.useState(0),n=Jn[s],a=s===Jn.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.stopPropagation()},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(At,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Jn.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.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
57
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
58
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
59
- `})]})}function bx({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 gx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Bc(s),[s]),f=o.useMemo(()=>e?Qa(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),d=o.useMemo(()=>f.find(p=>p.streamSource==="native"),[f]),g=o.useMemo(()=>f.filter(p=>p.streamSource==="agent-stream"),[f]),y=o.useMemo(()=>e?Ft(f,e.id):null,[f,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!y)return;const p=y.streamSource==="native"?"native":y.tabKey;!p||c===p||c==="native"&&l(p)},[c,y,i]),o.useEffect(()=>{var p;c!=="native"&&(g.some(x=>x.tabKey===c)||l(((p=g[0])==null?void 0:p.tabKey)||"native"))},[c,g]),o.useEffect(()=>{c==="native"&&(d||g[0]&&l(g[0].tabKey))},[c,d,g]);const w=o.useMemo(()=>c==="native"&&d?d:g.find(p=>p.tabKey===c)||y||d||g[0],[c,d,y,g]),A=o.useMemo(()=>g.map(p=>({tabKey:p.tabKey,title:Rc(p)||a,status:p.status})),[g,a]),m=o.useCallback(p=>{if(p)return f.find(x=>ur(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[f]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:f,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:m}}function yx({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:f,userName:d,onOpenHistory:g,onConversationChange:y,onClose:w}){const[A,m]=o.useState("split"),[p,x]=o.useState(()=>ns(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(C=>C.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>dt((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:j,extensionTabs:I,hasExtensions:k}=gx({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:ns(e)?void 0:e.tabKey}),v=o.useMemo(()=>S?Ft(j,S.id):null,[S,j]);o.useEffect(()=>{const C=h.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(C&&C.routeId===D.routeId&&C.tabKey===D.tabKey&&C.streamSource===D.streamSource)){if(ns(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(p==="native"){if(j.some(C=>C.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&x(v.tabKey);return}if(!j.some(C=>C.tabKey===p)){if((v==null?void 0:v.streamSource)==="agent-stream"){x(v.tabKey);return}x("native")}},[j,p,v]);const b=o.useMemo(()=>p==="native"?j.find(C=>C.streamSource==="native")||e:j.find(C=>C.tabKey===p)||e,[e,j,p]),$=Zc(b),L=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...b,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:b,[b,$]),T=gr(L),P=yn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:f}),{connScreenshot:K,screenshotUsage:G,handleRemoteAction:N}=bl({doId:T,targetSessionId:hc(L),connState:L.connectionState||"new",viewMode:A}),R=o.useMemo(()=>a.filter(C=>C.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{y==null||y(L)},[L,y]),o.useEffect(()=>{const C=D=>{D.key==="Escape"&&w()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[w]);const z=o.useCallback(C=>{C.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:w,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:z,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(Pt,{size:16})}),t.jsx("span",{className:"truncate",children:Ha(b)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,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(C=>{const D=A===C;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${D?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>m(C),title:C==="split"?"Split view":"Remote only",children:C==="split"?t.jsx(Od,{size:15}):t.jsx(Pt,{size:15})},C)})}),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:()=>g(b),title:"Chat History",children:[t.jsx(Ra,{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:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${A==="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:[A!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${A==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(bx,{hasExtensions:k,ideName:_||"IDE",activeChatTab:p,extensionTabs:I,onSelectTab:x}),t.jsx(tc,{activeConv:L,onModalButton:P.handleModalButton}),t.jsx(ba,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:P.handleSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:R,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${A==="split"?"order-1 md:order-2":""}`,children:t.jsx(Ji,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:K,screenshotUsage:G,transportType:L.transport,onAction:N})})]})]})})}function vx({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=np(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 wx({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:f,onSwitchHistorySession:d,onRefreshHistory:g,onResumeSavedHistorySession:y,remoteDialogConv:w,remoteDialogIdeEntry:A,connectionStates:m,actionLogs:p,localUserMessages:x,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:j,userName:I,onOpenRemoteHistory:k,onRemoteConversationChange:v,onCloseRemoteDialog:b,cliStopDialogOpen:$,cliStopTargetConv:L,onCancelCliStop:T,onStopCliNow:P,onSaveCliAndStop:K,toasts:G,onDismissToast:N,onClickToast:R,showOnboarding:z,onCloseOnboarding:C}){var F;const[D,O]=lt.useState(()=>wt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(Ja,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:O,onClose:u,onNewChat:f,onSwitchSession:d,onRefreshHistory:g,onResumeSavedSession:y}),w&&t.jsx(yx,{activeConv:w,ideEntry:A,ides:r,connectionStates:m,actionLogs:p,localUserMessages:x,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:j,userName:I,onOpenHistory:k,onConversationChange:v,onClose:b}),$&&L&&(rt(L)||Ze(L))&&t.jsx(vx,{activeConv:L,canSaveAndStop:rt(L)&&!Ze(L)&&!!((F=L.resume)!=null&&F.supported),onCancel:T,onStopNow:P,onSaveAndStop:K}),t.jsx(Kc,{toasts:G,onDismiss:N,onClickToast:R}),z&&t.jsx(xx,{onClose:C})]})}function jx({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(Fs,{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=_t(c,{fallbackId:c.id}),u=n[c.id],f=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),d&&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:d?"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:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"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(At,{size:16})})]})}function kx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Sx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":return!0;case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function Nx(e,s,r=Date.now()){return!e||!Sx(s)?null:{tabKey:e,nonce:r}}function Cx(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Ix(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Ax(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ki(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Mx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Tx(){var wo,jo,ko,So,No;const{sendCommand:e}=Tt(),s=yr(),r=Jc(),n=Ma(),a=Hs(),[i,c]=xd(),l=i.get("activeTab"),u=((wo=n.state)==null?void 0:wo.openRemoteForTabKey)||null,f=((jo=n.state)==null?void 0:jo.openMachineId)||null,d=((ko=n.state)==null?void 0:ko.mobileSection)||null,g=Cc(),y=g.ides||[],w=g.initialLoaded??!0,{updateRouteChats:A,setToasts:m}=g,[p,x]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=g.toasts||[],S=g.wsStatus||"connected",_=g.isConnected??!0,j=g.connectionStates||{},I=g.showReconnected||!1,{groupAssignments:k,setGroupAssignments:v,focusedGroup:b,setFocusedGroup:$,groupActiveTabIds:L,setGroupActiveTabIds:T,groupTabOrders:P,setGroupTabOrders:K,groupSizes:G,setGroupSizes:N,isMobile:R,hasHydratedStoredLayout:z,hydrateStoredLayout:C}=Kf(),[D,O]=o.useState(!1),[F,X]=o.useState(!1),[ne,ke]=o.useState(null),[ge,V]=o.useState([]),[pe,W]=o.useState(!1),[J,oe]=o.useState(null),[le,me]=o.useState(()=>so());o.useEffect(()=>sf(me),[]);const Ce=o.useMemo(()=>kx({isMobile:R,mobileViewMode:le}),[R,le]),[ce,xe]=o.useState([]),[te,ue]=o.useState({}),[se,Se]=o.useState({}),[we,Re]=o.useState({}),[M,he]=o.useState(null),[ye,ee]=o.useState(null),[je,Te]=o.useState(null),Oe=o.useRef(null);xr("Dashboard",{ideCount:y.length,toastCount:h.length,focusedGroup:b,groupCount:Object.keys(k).length,localMessageTabs:Object.keys(te).length,actionLogCount:ce.length});const Pe=o.useMemo(()=>y.filter(ae=>ae.type==="adhdev-daemon").sort(Ba),[y]),Ve=Pe[0],Ge=!!Ve;o.useEffect(()=>{for(const ae of Pe){(!ae.detectedIdes||!ae.availableProviders||!ae.recentLaunches||!ae.workspaces)&&s(ae.id,{minFreshMs:3e4}).catch(()=>{});const be=ae.machine;(typeof(be==null?void 0:be.cpus)!="number"||typeof(be==null?void 0:be.totalMem)!="number"||typeof(be==null?void 0:be.arch)!="string"||typeof(be==null?void 0:be.release)!="string")&&r(ae.id,{minFreshMs:3e4}).catch(()=>{})}},[s,r,Pe]);const ft=(Ve==null?void 0:Ve.terminalBackend)||null,et=Ve?_t(Ve,{fallbackId:Ve.id}):null,it=(Ve==null?void 0:Ve.id)||null,Qe=o.useMemo(()=>pf(y,se),[y,se]),{hiddenTabs:It,hideTab:ht,toggleTab:at,showTab:Ae,showAllTabs:Xe}=mf(),{conversations:He,visibleConversations:ze,visibleTabKeys:Mt,resolveConversationBySessionId:jt,resolveConversationByTarget:xt}=Nf({ides:Qe,connectionStates:j,localUserMessages:te,clearedTabs:we,hiddenTabs:It}),bt=o.useMemo(()=>new Map(He.map(ae=>[ae.tabKey,$r(ae)])),[He]),Lt=o.useCallback(ae=>{const fe=bt.get(ae)||$r({tabKey:ae});ht(fe)},[bt,ht]),yt=o.useCallback(ae=>{const fe=bt.get(ae)||$r({tabKey:ae});at(fe)},[bt,at]),Dt=o.useCallback(ae=>{const fe=bt.get(ae)||$r({tabKey:ae});Ae(fe)},[bt,Ae]);Gm(ze,Ce),o.useEffect(()=>{Object.keys(se).length!==0&&Se(ae=>ff(ae,y))},[y,se]);const Z=o.useMemo(()=>vu(y),[y]),{notifications:De,unreadCount:$e,notificationStateBySessionId:ot,markRead:kt,markUnread:B,markTargetRead:H,deleteNotification:U}=lh({conversations:He,liveSessionInboxState:Z}),q=o.useCallback(ae=>{const fe=De.find(de=>de.id===ae),be=Math.max(Date.now(),(fe==null?void 0:fe.updatedAt)||0);kt(ae,be),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_session_seen",{sessionId:fe.sessionId,seenAt:be}).catch(()=>{})},[kt,De,e]),re=o.useCallback(ae=>{const fe=De.find(be=>be.id===ae);B(ae),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_notification_unread",{sessionId:fe.sessionId,notificationId:fe.id}).catch(()=>{})},[B,De,e]),Ne=o.useCallback(ae=>{const fe=De.find(be=>be.id===ae);U(ae),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"delete_notification",{sessionId:fe.sessionId,notificationId:fe.id}).catch(()=>{})},[U,De,e]),Ie=o.useRef(null),Le=o.useRef(null),Be=o.useRef(null),Q=o.useRef(null),ve=o.useRef(null),{containerRef:tt,normalizedGroupAssignments:Ue,numGroups:E,isSplitMode:Y,groupedConvs:ie,moveTabToGroup:Ee,closeGroup:Me,handleResizeStart:Ke,splitTabRelative:qe}=Vf({groupAssignments:k,setGroupAssignments:v,setFocusedGroup:$,setGroupActiveTabIds:T,setGroupTabOrders:K,groupSizes:G,setGroupSizes:N,isMobile:R,visibleConversations:ze,visibleTabKeys:Mt}),_e=o.useMemo(()=>{var fe,be;if(!R){if(M){const de=He.find(Je=>Je.tabKey===M);if(de)return de}return ze[0]}const ae=L[b];if(ae){const de=He.find(Je=>Je.tabKey===ae);if(de)return de}return((fe=ie[b])==null?void 0:fe[0])||((be=ie[0])==null?void 0:be[0])},[M,R,L,b,He,ie,ze]);o.useEffect(()=>{const ae=()=>{Be.current&&(clearTimeout(Be.current),Be.current=null),Q.current&&(clearTimeout(Q.current),Q.current=null),ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null),Le.current=null};if(R){ae(),Ie.current=null;return}if(!(_e!=null&&_e.sessionId)){ae(),Ie.current=null;return}const fe=nn(_e,Z),be=Ix({tabKey:_e.tabKey,historySessionId:br(_e)||"",lastMessageHash:_e.lastMessageHash||"",lastMessageAt:Number(_e.lastMessageAt||0),timestamp:ps(_e),liveState:fe}),de=be.autoReadKey,Je=Cx({autoReadKey:de,shouldMarkSeen:be.shouldMarkSeen,completedKey:Ie.current,pendingKey:Le.current});if(!be.shouldMarkSeen){Je.shouldCancelPending&&ae(),Ie.current=de;return}if(!Je.shouldSchedule)return;Je.shouldCancelPending&&ae();const pt=Zi(_e),Et=()=>{if(document.visibilityState!=="visible"||Ie.current===de)return;Ie.current=de,Le.current=null,Be.current=null,Q.current=null,ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null);const gt=be.readAt;H({...pt},gt),e(_e.daemonId||_e.routeId,"mark_session_seen",{sessionId:_e.sessionId,seenAt:gt}).catch(()=>{})};if(Le.current=Je.nextPendingKey,document.visibilityState==="visible"){Be.current=setTimeout(Et,1500);const gt=()=>{document.visibilityState!=="visible"&&Be.current&&(clearTimeout(Be.current),Be.current=null)};ve.current=gt,document.addEventListener("visibilitychange",gt);return}const Xt=()=>{document.visibilityState==="visible"&&(Q.current&&clearTimeout(Q.current),Q.current=setTimeout(Et,800),ve.current&&(document.removeEventListener("visibilitychange",ve.current),ve.current=null))};ve.current=Xt,document.addEventListener("visibilitychange",Xt)},[_e,R,Z,H,e]),o.useEffect(()=>()=>{Be.current&&clearTimeout(Be.current),Q.current&&clearTimeout(Q.current),ve.current&&document.removeEventListener("visibilitychange",ve.current)},[]);const{requestedDesktopTabKey:We,requestedMobileTabKey:Ut,consumeRequestedActiveTab:zs}=Cf({isMobile:R,urlActiveTab:l,resolveConversationBySessionId:jt,setSearchParams:c}),{remoteDialogConv:Vs,remoteDialogIdeEntry:jr,remoteDialogActiveConv:$l,setRemoteDialogActiveConv:In,openRemoteDialog:Kl,closeRemoteDialog:Bl}=Wf({isMobile:R,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:We,conversations:He,ides:y,resolveConversationByTarget:xt}),mt=$l||Vs||_e,zt=!!mt&&rt(mt)&&!Ze(mt),kr=o.useMemo(()=>{if(!mt||!zt)return null;const ae=mt.daemonId||mt.routeId||"",fe=Wt(mt);return`${ae}:${fe}`},[mt,zt]),Ol=o.useMemo(()=>ze,[ze]),Sr=R&&le==="chat",Wl=o.useMemo(()=>He.filter(ae=>ro(It,ae)),[He,It]),Nr=o.useCallback(ae=>{const fe=new URLSearchParams(i);fe.set("activeTab",ae),c(fe,{replace:!0})},[i,c]),Hl=o.useCallback(async(ae,fe)=>jn(e,ae,fe),[e]),Fl=o.useCallback(async(ae,fe)=>{if(!fe.trim())return{ok:!1,error:"Choose a workspace path first."};try{const be=await e(ae,"workspace_add",{path:fe.trim()});return be!=null&&be.success?{ok:!0}:{ok:!1,error:(be==null?void 0:be.error)||"Could not save workspace"}}catch(be){return{ok:!1,error:be instanceof Error?be.message:"Could not save workspace"}}},[e]),Ul=o.useCallback(async(ae,fe,be)=>{var de;try{const Je={ideType:fe,enableCdp:!0};(de=be==null?void 0:be.workspacePath)!=null&&de.trim()&&(Je.workspace=be.workspacePath.trim());const pt=await e(ae,"launch_ide",Je);return!(pt!=null&&pt.success)&&(pt==null?void 0:pt.success)!==void 0?{ok:!1,error:(pt==null?void 0:pt.error)||"Could not launch IDE"}:(Te({machineId:ae,kind:"ide",providerType:fe,workspacePath:(be==null?void 0:be.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Je){return{ok:!1,error:Je instanceof Error?Je.message:"Could not launch IDE"}}},[e]),zl=o.useCallback(async(ae,fe,be,de)=>{var pt,Et,Xt;const Je=Date.now();try{const gt={cliType:be};(pt=de==null?void 0:de.workspacePath)!=null&&pt.trim()?gt.dir=de.workspacePath.trim():de!=null&&de.workspaceId&&(gt.workspaceId=de.workspaceId),(Et=de==null?void 0:de.resumeSessionId)!=null&&Et.trim()&&(gt.resumeSessionId=de.resumeSessionId.trim()),Array.isArray(de==null?void 0:de.cliArgs)&&de.cliArgs.length>0&&(gt.cliArgs=de.cliArgs),(Xt=de==null?void 0:de.initialModel)!=null&&Xt.trim()&&(gt.initialModel=de.initialModel.trim());const vt=await e(ae,"launch_cli",gt),$t=(vt==null?void 0:vt.result)||vt,Gs=($t==null?void 0:$t.sessionId)||($t==null?void 0:$t.id);return vt!=null&&vt.success&&Gs?(Nr(Gs),{ok:!0}):vt!=null&&vt.success?(Te({machineId:ae,kind:fe,providerType:be,workspacePath:(de==null?void 0:de.workspacePath)||null,resumeSessionId:(de==null?void 0:de.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||($t==null?void 0:$t.error)||`Could not launch ${fe.toUpperCase()} session`}}catch(gt){return Mx(gt)?(Te({machineId:ae,kind:fe,providerType:be,workspacePath:(de==null?void 0:de.workspacePath)||null,resumeSessionId:(de==null?void 0:de.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:gt instanceof Error?gt.message:`Could not launch ${fe.toUpperCase()} session`}}},[Nr,e]),Vl=o.useCallback(async(ae,fe)=>{if(!ae||!fe)return[];try{const be=await e(ae,"list_saved_sessions",{providerType:fe,kind:"cli",limit:30}),de=(be==null?void 0:be.result)??be;return Array.isArray(de==null?void 0:de.sessions)?de.sessions:[]}catch(be){return console.error("List saved sessions failed",be),[]}},[e]);o.useEffect(()=>{if(!je)return;const ae=ki(je.workspacePath),fe=y.find(de=>{var gt,vt,$t,Gs;if(!de||de.type==="adhdev-daemon"||Ax(de.daemonId||de.id)!==je.machineId||(mr(de)?"cli":Ls(de)?"acp":"ide")!==je.kind||String(de.agentType||de.type||"")!==je.providerType)return!1;if(je.resumeSessionId)return String(de.providerSessionId||"")===je.resumeSessionId;if(ae){const Mn=ki(de.workspace||de.runtimeWorkspaceLabel);return Mn?Mn===ae:!1}return Number(de.lastUpdated||de._lastUpdate||de.timestamp||((Gs=($t=(vt=(gt=de.activeChat)==null?void 0:gt.messages)==null?void 0:vt.at)==null?void 0:$t.call(vt,-1))==null?void 0:Gs.timestamp)||0)>=je.startedAt-5e3});if(!fe)return;const be=gc({entrySessionId:fe.sessionId,entryInstanceId:fe.instanceId,entryRouteId:fe.id,conversations:He});be&&(Te(null),Nr(be))},[He,Nr,y,je]),o.useEffect(()=>{if(!je)return;const ae=window.setTimeout(()=>{Te(fe=>!fe||fe.startedAt!==je.startedAt?fe:null)},45e3);return()=>window.clearTimeout(ae)},[je]),hf({visibleConversations:ze,clearedTabs:we,setClearedTabs:Re,setActionLogs:xe}),If({ides:y,sendDaemonCommand:e,setToasts:m,setLocalUserMessages:ue,resolveConversationByTarget:xt});const{isRefreshingHistory:Gl,handleRefreshHistory:ql}=ri({sendDaemonCommand:e,activeConv:_e,chats:(So=y.find(ae=>ae.id===(_e==null?void 0:_e.routeId)))==null?void 0:So.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:ue,setClearedTabs:Re}),{isCreatingChat:Yl,isRefreshingHistory:Xl,handleSwitchSession:Jl,handleNewChat:Ql,handleRefreshHistory:Zl}=ri({sendDaemonCommand:e,activeConv:mt,chats:(No=y.find(ae=>ae.id===(mt==null?void 0:mt.routeId)))==null?void 0:No.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:ue,setClearedTabs:Re}),An=o.useCallback(async()=>{if(!(!mt||!zt||pe)){W(!0);try{const ae=mt.daemonId||mt.routeId,fe=Wt(mt),be=await e(ae,"list_saved_sessions",{agentType:fe,providerType:fe,kind:"cli",limit:50}),de=(be==null?void 0:be.result)??be;V(Array.isArray(de==null?void 0:de.sessions)?de.sessions:[])}catch(ae){console.error("Refresh saved sessions failed",ae),V([])}finally{W(!1)}}},[mt,pe,zt,e]);o.useEffect(()=>{if(!D){Oe.current=null;return}if(!zt){Oe.current=null,V([]),W(!1);return}!kr||pe||Oe.current!==kr&&(Oe.current=kr,An())},[An,D,pe,zt,kr]);const ed=o.useCallback(async ae=>{if(!mt||!zt||!ae.providerSessionId||!ae.workspace)return;const fe=mt.daemonId||mt.routeId,be=Wt(mt);try{oe(ae.providerSessionId);const de=await e(fe,"launch_cli",{cliType:be,dir:ae.workspace,resumeSessionId:ae.providerSessionId,initialModel:oc(ae.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Je=(de==null?void 0:de.result)??de,pt=typeof(Je==null?void 0:Je.sessionId)=="string"?Je.sessionId:typeof(Je==null?void 0:Je.id)=="string"?Je.id:"";pt&&c(Et=>{const Xt=new URLSearchParams(Et);return Xt.set("activeTab",pt),Xt},{replace:!0}),O(!1)}catch(de){console.error("Resume saved session failed",de)}finally{oe(null)}},[mt,zt,e,c]);Of({urlActiveTab:R&&!Sr?l:null,conversations:He,resolveConversationBySessionId:jt,normalizedGroupAssignments:Ue,hasHydratedStoredLayout:R&&!Sr?z:!0,hydrateStoredLayout:R&&!Sr?C:()=>{},setGroupActiveTabIds:T,setFocusedGroup:$,setSearchParams:c,historyModalOpen:D,activeConv:_e,isRefreshingHistory:Gl,ides:y,handleRefreshHistory:ql});const xo=o.useCallback(async(ae,fe)=>{const be=fe||ne||_e;if(!be||!rt(be)&&!Ze(be))return;const de=Wt(be),Je=be.routeId||be.daemonId||"";try{await e(Je,"stop_cli",{cliType:de,targetSessionId:be.sessionId,mode:ae})}catch(pt){console.error("Stop CLI failed:",pt)}},[_e,ne,e]),td=o.useCallback(async ae=>{const fe=ae||_e;!fe||!rt(fe)&&!Ze(fe)||(ke(fe),X(!0))},[_e]),sd=o.useMemo(()=>!_e||!rt(_e)||Ze(_e)?null:Ks(_e),[_e]),rd=o.useCallback(async ae=>{if(!_e||!rt(_e)||Ze(_e))return;const fe=Ks(_e);if(fe===ae)return;const be=_e.sessionId;be&&Se(de=>({...de,[be]:ae}));try{await e(is(_e)||_e.routeId,"set_cli_view_mode",{targetSessionId:_e.sessionId,cliType:Wt(_e),mode:ae})}catch(de){const Je=ao(de);be&&!Je&&Se(pt=>{const Et={...pt};return fe===sl(y,be)?delete Et[be]:Et[be]=fe,Et}),no(de)?console.warn(Je?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",de instanceof Error?de.message:String(de)):console.error("Failed to switch CLI view mode:",de)}},[_e,y,e]),{versionMismatchDaemons:nd,hasRequiredVersionDaemons:bo,appVersion:ad,versionBannerDismissed:od,setVersionBannerDismissed:id,upgradingDaemons:cd,handleBannerUpgrade:ld}=Gf({ides:y,sendDaemonCommand:e}),go=o.useCallback(ae=>{he(ae.tabKey),c(fe=>{const be=new URLSearchParams(fe),de=fm(ae);return de?be.set("activeTab",de):be.delete("activeTab"),be},{replace:!0})},[c]),yo=o.useCallback(ae=>{Dt(ae.tabKey),go(ae)},[go,Dt]),dd=o.useCallback(ae=>{Lt(ae.tabKey)},[Lt]),vo=o.useCallback((ae,fe)=>{const be=Nx(ae,fe);be&&ee(be)},[]);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(op,{wsStatus:S,showReconnected:I}),t.jsx(ip,{terminalBackend:ft,isStandalone:Ge,machineLabel:et,machineKey:it}),(!od||bo)&&t.jsx(jx,{daemons:nd,targetVersion:ad,required:bo,upgradingDaemons:cd,onUpgrade:ld,onDismiss:()=>id(!0)}),t.jsx(hx,{showMobileChatMode:Sr,isMobile:R,activeConv:_e,wsStatus:S,isConnected:_,onOpenHistory:ae=>{ae&&In(ae),O(!0)},onOpenRemote:Kl,onStopCli:td,activeCliViewMode:sd,onSetActiveCliViewMode:rd,mobileChatConversations:Ol,ides:y,actionLogs:ce,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:xe,isStandalone:Ge,initialDataLoaded:w,userName:g.userName,requestedMobileTabKey:Ut,onRequestedMobileTabConsumed:zs,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:tt,isSplitMode:Y,numGroups:E,groupSizes:G,groupedConvs:ie,clearedTabs:we,focusedGroup:b,setFocusedGroup:$,moveTabToGroup:Ee,splitTabRelative:qe,closeGroup:Me,handleResizeStart:Ke,groupActiveTabIds:L,setGroupActiveTabIds:T,groupTabOrders:P,setGroupTabOrders:K,toggleHiddenTab:yt,visibleConversations:ze,hiddenConversations:Wl,requestedDesktopTabKey:We,onRequestedDesktopTabConsumed:zs,onDesktopActiveTabChange:he,onRequestScrollToBottom:vo,onHideConversation:dd,onShowHiddenConversation:yo,onShowAllHiddenConversations:Xe,scrollToBottomRequest:ye,machineEntries:Pe,onBrowseMachineDirectory:Hl,onSaveMachineWorkspace:Fl,onLaunchMachineIde:Ul,onLaunchMachineProvider:zl,onListMachineSavedSessions:Vl,notifications:De,notificationUnreadCount:$e,notificationStateBySessionId:ot,liveSessionInboxState:Z,onMarkNotificationRead:q,onMarkNotificationUnread:re,onDeleteNotification:Ne,onMarkNotificationTargetRead:H}),t.jsx("style",{children:`
60
- body { overflow: hidden; overscroll-behavior: none; }
61
- `}),t.jsx(wx,{historyModalOpen:D,historyTargetConv:mt,ides:y,isHistoryCreatingChat:Yl,isHistoryRefreshingHistory:zt?!1:Xl,savedHistorySessions:ge,isSavedHistoryLoading:pe,isResumingSavedHistorySessionId:J,onCloseHistory:()=>O(!1),onNewHistoryChat:Ql,onSwitchHistorySession:Jl,onRefreshHistory:zt?An:Zl,onResumeSavedHistorySession:ed,remoteDialogConv:Vs,remoteDialogIdeEntry:jr,connectionStates:j,actionLogs:ce,localUserMessages:te,sendDaemonCommand:e,setLocalUserMessages:ue,setActionLogs:xe,isStandalone:Ge,userName:g.userName,onOpenRemoteHistory:ae=>{ae&&In(ae),O(!0)},onRemoteConversationChange:In,onCloseRemoteDialog:Bl,cliStopDialogOpen:F,cliStopTargetConv:ne,onCancelCliStop:()=>{X(!1),ke(null)},onStopCliNow:async()=>{X(!1),await xo("hard",ne),ke(null)},onSaveCliAndStop:async()=>{X(!1),await xo("save",ne),ke(null)},toasts:h,onDismissToast:ae=>m(fe=>fe.filter(be=>be.id!==ae)),onClickToast:ae=>{if(ae.targetKey){const fe=xt(ae.targetKey);fe&&($(Ue.get(fe.tabKey)??0),yo(fe),vo(fe.tabKey,"toast-open"))}},showOnboarding:p,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}})]})}function Lx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[f,d]=o.useState(null),[g,y]=o.useState(!1),[w,A]=o.useState(null),[m,p]=o.useState(!1),[x,h]=o.useState(""),S=o.useRef(null),_=o.useCallback(C=>{S.current=C},[]),j=o.useCallback((C,D,O=!1)=>{c(F=>[...F.slice(-100),{timestamp:Date.now(),level:C,message:D}]),setTimeout(()=>{var F;return(F=a.current)==null?void 0:F.scrollIntoView({behavior:"smooth"})},100),O&&nt.showToast(D,C==="error"||C==="warn"?"warning":"success")},[a]),I=o.useCallback(C=>{const D=C instanceof Error?C.message:String(C||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),k=o.useCallback(async(C,D)=>{var O;if(!e||l)return!1;u(C),j("info",`Launching ${dt(C)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const F={ideType:C,enableCdp:!0};(O=D==null?void 0:D.workspace)!=null&&O.trim()?F.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(F.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",F);return j(X!=null&&X.success?"info":"error",X!=null&&X.success?`${dt(C)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(F){return j("error",`Launch error: ${F.message}`,!0),!1}finally{u(null)}},[e,l,j,r]),v=o.useCallback(async C=>{if(!e)return{success:!1};const{cliType:D,dir:O,workspaceId:F,useDefaultWorkspace:X,useHome:ne,argsStr:ke,model:ge,resumeSessionId:V}=C;if(!D)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const pe=ke?ke.split(/\s+/).filter(Boolean):void 0,W=(O==null?void 0:O.trim())||(F?"(saved id)":X?"(default workspace)":ne?"(home)":"");j("info",`Launching ${D}${W?` in ${W}`:""}${ge?` (model: ${ge})`:""}...`),d(D);try{const J={cliType:D,cliArgs:pe,initialModel:ge||void 0};O!=null&&O.trim()?J.dir=O.trim():F?J.workspaceId=F:X?J.useDefaultWorkspace=!0:ne&&(J.useHome=!0),V&&(J.resumeSessionId=V);const oe=await r(e,"launch_cli",J),le=(oe==null?void 0:oe.result)||oe;return oe!=null&&oe.success?(j("info",`${D} launched`,!0),(le==null?void 0:le.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(le==null?void 0:le.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:le==null?void 0:le.sessionId}):(j("error",`Failed: ${(oe==null?void 0:oe.error)||(le==null?void 0:le.error)}`,!0),(oe==null?void 0:oe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&A({cliType:D,argsStr:ke,model:ge}),{success:!1,sessionId:le==null?void 0:le.sessionId})}catch(J){return I(J)?(j("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${J.message}`,!0),{success:!1})}finally{d(null)}},[e,j,I,r]),b=o.useCallback(async(C,D,O,F)=>e?C?D.trim()?v({cliType:C,dir:D,argsStr:O,model:F}):(A({cliType:C,argsStr:O,model:F}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,v]),$=o.useCallback(async(C,D,O)=>{if(e&&window.confirm(`Stop ${C}?
62
- This will terminate the process.`))try{const F=await r(e,"stop_cli",{cliType:C,dir:D,targetSessionId:O});F!=null&&F.success?j("info",`${C} stopped`,!0):j("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){j("error",`Stop failed: ${F.message}`,!0)}},[e,j,r]),L=o.useCallback(async C=>{try{await r(C.daemonId,"restart_ide",{ideType:C.type}),j("info",`${dt(C.type)} restart initiated`,!0)}catch(D){j("error",`Restart failed: ${D.message}`,!0)}},[j,r]),T=o.useCallback(async C=>{if(window.confirm(`Stop ${dt(C.type)}?
63
- This will disconnect CDP and optionally kill the process.`))try{const D=await r(C.daemonId,"stop_ide",{ideType:C.type,killProcess:!0});D!=null&&D.success?j("info",`${dt(C.type)} stopped`,!0):j("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){j("error",`Stop failed: ${D.message}`,!0)}},[j,r]),P=o.useCallback(async()=>{if(e)try{const C=await r(e,"detect_ides",{});j("info",`Found ${((C==null?void 0:C.result)||[]).length} IDE(s)`,!0)}catch(C){j("error",`Detection failed: ${C.message}`,!0)}},[e,j,r]),K=o.useCallback(async C=>{if(!e||!C.trim())return!1;y(!0);try{const D=await r(e,"workspace_add",{path:C.trim()});return D!=null&&D.success?(j("info",`Workspace added: ${C.trim()}`),!0):(j("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return j("error",D.message),!1}finally{y(!1)}},[e,j,r]),G=o.useCallback(async C=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const D=await r(e,"workspace_remove",{id:C});D!=null&&D.success?j("info","Workspace removed",!0):j("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){j("error",D.message,!0)}finally{y(!1)}}},[e,j,r]),N=o.useCallback(async C=>{var D;if(e){y(!0);try{const O=await r(e,"workspace_set_default",C===null?{clear:!0}:{id:C});if(O!=null&&O.success){j("info",C?"Default workspace updated":"Default workspace cleared",!0);const F=typeof O.defaultWorkspacePath=="string"?O.defaultWorkspacePath:"";F&&((D=S.current)==null||D.call(S,F))}else j("error",(O==null?void 0:O.error)||"workspace_set_default failed",!0)}catch(O){j("error",O.message,!0)}finally{y(!1)}}},[e,j,r]),R=o.useCallback(async C=>{var O;if(!e||!C.trim())return;const D=C.trim();y(!0);try{const F=await r(e,"workspace_set_default",{path:D});F!=null&&F.success?(j("info","Default workspace set from history"),(O=S.current)==null||O.call(S,D)):j("error",(F==null?void 0:F.error)||"Could not set default (path missing on disk?)")}catch(F){j("error",F.message)}finally{y(!1)}},[e,j,r]),z=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:x})}catch(C){j("warn",`Live nickname updated, but account sync failed: ${C.message}`)}j("info",`Nickname set to "${x||"(cleared)"}"`),p(!1)}catch(C){j("error",`Failed: ${C.message}`)}},[e,x,s,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:g,launchPick:w,setLaunchPick:A,editingNickname:m,setEditingNickname:p,nicknameInput:x,setNicknameInput:h,addLog:j,handleLaunchIde:k,runLaunchCliCore:v,handleLaunchCli:b,handleStopCli:$,handleRestartIde:L,handleStopIde:T,handleDetectIdes:P,handleWorkspaceAdd:K,handleWorkspaceRemove:G,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:R,handleSaveNickname:z,setOnDefaultWorkspaceChanged:_}}function Rx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:f,handleWorkspaceSetDefault:d}=i,[g,y]=o.useState(!1),[w,A]=o.useState(""),[m,p]=o.useState([]),[x,h]=o.useState(!1),[S,_]=o.useState(""),j=o.useCallback(async T=>{h(!0),_("");try{const P=await jn(c,e,T);A(P.path),p(P.directories)}catch(P){_(P instanceof Error?P.message:"Could not load folder")}finally{h(!1)}},[e,c]),I=o.useCallback(()=>{y(!0);const T=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],P=wn(s.platform,vn(T,s.defaultWorkspacePath,(s.workspaces||[]).map(K=>K.path)));j(P)},[a,n,r,j,s.defaultWorkspacePath,s.platform,s.workspaces]),k=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,b=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,$=((L=s.loadavg)==null?void 0:L[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(Mr,{icon:t.jsx(Vi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Su(s.uptime):"Waiting…"}),t.jsx(Mr,{icon:t.jsx(Pt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Mr,{icon:t.jsx(fn,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Mr,{icon:t.jsx(Hd,{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(Do,{value:k?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Do,{value:b,max:100,label:"Memory",color:"#3b82f6",detail:k?`${Pn(s.totalMem-v)} / ${Pn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Pn(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(Es,{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 d(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:gn(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 f(T.id),children:"Remove"})]},T.id))})]}),g&&t.jsx(kn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:m,busy:x,error:S,confirmLabel:"Add workspace",onClose:()=>y(!1),onNavigate:T=>{j(T)},onConfirm:T=>{(async()=>{if(!T)return;await u(T)&&y(!1)})()}})]})}function _x(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 Px(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 Qn(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 Si(e){if(!e||typeof e!="object")return null;if(Qn(e))return e;const s=e,r=s.result;return Qn(r)?r:Qn(s.sourceConfig)?s.sourceConfig:null}function Dx(e){const s=e.trim();return s||null}const Ni=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Ex=[{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 $x({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,f]=o.useState([]),[d,g]=o.useState(""),[y,w]=o.useState([]),[A,m]=o.useState(""),p=o.useRef(null),x=o.useRef(null),h=v=>{f(b=>b.includes(v)?b.filter($=>$!==v):[...b,v])},S=()=>f([...Ni]),_=()=>f([]);o.useEffect(()=>{var v;(v=p.current)==null||v.scrollIntoView({behavior:"smooth"})},[y]),o.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const j=o.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&a==="running"&&(i("done"),w(b=>[...b,`
64
- ✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),m("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(w(b=>[...b,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),m((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),m((v==null?void 0:v.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(v=>[...v,`
65
- ⚠️ Auto-fix cancelled.`]),i("done"),x.current&&clearInterval(x.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:v=>v.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:Ex.map(v=>t.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.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:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ni.map(v=>t.jsxs("button",{onClick:()=>h(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),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:d,onChange:v=>g(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(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((v,b)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},b)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:p})]}),A&&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:A})]})]}),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:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),w([]),m("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Kx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((j=i[0])==null?void 0:j.type)||""),[u,f]=o.useState(""),[d,g]=o.useState(""),[y,w]=o.useState(!1),[A,m]=o.useState(""),[p,x]=o.useState(!1),h=I=>{const k=I.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!d||d===S(u))&&g(S(k))},S=I=>I.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),_=async()=>{if(!(!u||!d||!c)){w(!0),m("");try{const I=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(x(!0),a==null||a(u)):m((I==null?void 0:I.error)||"Failed to create provider")}catch(I){m((I==null?void 0:I.message)||"Connection failed")}w(!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:p?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:d,onChange:I=>g(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"})]}),A&&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:A})]})}),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:p?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:!u||!d||y,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||y?.4:1},children:y?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Bx({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[f,d]=o.useState("all"),[g,y]=o.useState(null),[w,A]=o.useState(!1),[m,p]=o.useState(null),[x,h]=o.useState("normal"),[S,_]=o.useState(""),[j,I]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const T=await r(e,"get_provider_source_config",{}),P=Si(T);P&&(p(P),h(P.sourceMode),_(P.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const T=await r(e,"get_provider_settings",{}),P=_x(T);if(P){const K=Px(P,s);K.sort((G,N)=>G.category.localeCompare(N.category)||G.displayName.localeCompare(N.displayName)),a(K)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),m||k()},[]);const b=async(T,P,K)=>{u(`${T}.${P}`),a(G=>G.map(N=>N.type===T?{...N,values:{...N.values,[P]:K}}:N));try{const G=await r(e,"set_provider_setting",{providerType:T,key:P,value:K});G!=null&&G.success||v()}catch{v()}u(null)},$=async()=>{I(!0);try{const T=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:Dx(S)}),P=Si(T);P?(p(P),h(P.sourceMode),_(P.explicitProviderDir||"")):await k(),await v()}catch{await k()}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:()=>d(T),className:`machine-btn text-[10px] px-2 py-0.5 ${f===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:()=>A(!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:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:x,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:S,onChange:T=>_(T.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:j?"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:"})," ",(m==null?void 0:m.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(m==null?void 0:m.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((L=m==null?void 0:m.providerRoots)==null?void 0:L.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(T=>T.category===f).length>1&&(()=>{const T=n.filter(N=>N.category===f),P=new Map;for(const N of T)for(const R of N.schema){if(R.type!=="boolean")continue;const z=P.get(R.key),C=!!(N.values[R.key]??R.default);z?(z.onCount+=C?1:0,z.total+=1):P.set(R.key,{label:R.label||R.key,onCount:C?1:0,total:1})}const K=[...P.entries()].filter(([,N])=>N.total===T.length);if(K.length===0)return null;const G=async(N,R)=>{for(const z of T)await b(z.type,N,R)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",f.toUpperCase()," providers (",T.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([N,R])=>{const z=R.onCount===R.total,C=R.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:R.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),t.jsx("button",{onClick:()=>void G(N,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void G(N,!1),disabled:C,className:`machine-btn text-[9px] px-1.5 py-px ${C?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),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=>f==="all"||T.category===f).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:()=>y(s.find(P=>P.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(P=>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:[P.label||P.key,l===`${T.type}.${P.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),P.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:P.description})]}),t.jsx("div",{className:"shrink-0",children:P.type==="boolean"?t.jsx("button",{onClick:()=>b(T.type,P.key,!(T.values[P.key]??P.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:T.values[P.key]??P.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[P.key]??P.default?21:3}})}):P.type==="number"?t.jsx("input",{type:"number",value:Number(T.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:K=>{const G=parseInt(K.target.value)||0;P.min!==void 0&&G<P.min||P.max!==void 0&&G>P.max||b(T.type,P.key,G)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?t.jsx("select",{value:String(T.values[P.key]??P.default??""),onChange:K=>b(T.type,P.key,K.target.value),className:"machine-input text-[11px]",children:P.options.map(K=>t.jsx("option",{value:K,children:K},K))}):t.jsx("input",{type:"text",value:String(T.values[P.key]??P.default??""),onBlur:K=>b(T.type,P.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},T.type))}),g&&t.jsx($x,{machineId:e,provider:g,sendDaemonCommand:r,onClose:()=>y(null)}),w&&t.jsx(Kx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),v()}})]})}const Ox=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Wx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Hx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Fx(e){return e.trim().toLowerCase()}function Nn(e,s){const r=Fx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function fo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function fr(e,s=220){const r=fo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Ux(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Rl(e,s){return e.filter(r=>Nn([r.level,r.message],s))}function zx(e,s){return e.split(`
66
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Nn([r],s))}function _l(e,s){return e.filter(r=>Nn([r.level,r.category,r.stage,r.interactionId,fo(r.payload)],s))}function Pl(e,s){return e.filter(r=>Nn([r.kind,r.topic,r.interactionId,fo(r.payload)],s))}function Ci(e){return e==="warn"||e==="error"}function Vx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Ci(a.level)).length+r.filter(a=>Ci(a.level)).length}}function Gx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
67
- `)):s.length>0&&a.push(["[daemon logs]",...s].join(`
68
- `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${fr(i.payload,500)}`.trim())].join(`
69
- `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${fr(i.payload,500)}`.trim())].join(`
70
- `)),a.join(`
71
-
72
- `)}function qx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Rl(e,c),u=_l(s,c),f=Pl(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),g=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:fr(w.payload,320)||`${w.category}.${w.stage}`})),y=[...d,...g].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:y.length,latestIssue:y[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function Ii(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ai(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Zn(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function Yx({machineId:e,sendDaemonCommand:s}){var we,Re;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,g]=o.useState([]),[y,w]=o.useState(0),[A,m]=o.useState(0),[p,x]=o.useState(null),[h,S]=o.useState(!0),[_,j]=o.useState("info"),[I,k]=o.useState("info"),[v,b]=o.useState("all"),[$,L]=o.useState(""),[T,P]=o.useState(!0),[K,G]=o.useState(!0),[N,R]=o.useState(""),[z,C]=o.useState(""),[D,O]=o.useState(0),[F,X]=o.useState({daemon:!0,trace:!1,web:!1}),ne=o.useRef(null),ke=o.useRef(!1),ge=o.useMemo(()=>Hx(u,v),[u,v]),V=o.useMemo(()=>Rl(r,$),[r,$]),pe=o.useMemo(()=>zx(c,$),[c,$]),W=o.useMemo(()=>_l(ge,$),[ge,$]),J=o.useMemo(()=>Pl(d,$),[d,$]),oe=o.useMemo(()=>I==="issues"?V.filter(M=>M.level==="warn"||M.level==="error"):I==="info"?V.filter(M=>M.level!=="debug"):V,[V,I]),le=o.useMemo(()=>I==="all"?pe:[],[pe,I]),me=o.useMemo(()=>I==="issues"?W.filter(M=>M.level==="warn"||M.level==="error"):I==="info"?W.filter(M=>M.level!=="debug"):W,[W,I]),Ce=o.useMemo(()=>I==="issues"?[]:J,[J,I]),ce=o.useMemo(()=>Vx({daemonLogs:V,daemonRawLines:pe,trace:W,webEvents:J}),[V,pe,W,J]),xe=o.useMemo(()=>qx({daemonLogs:r,trace:ge,webEvents:d,daemonLogKind:a,daemonFetchError:N,traceFetchError:z,searchQuery:$}),[N,a,r,ge,$,z,d]),te=o.useCallback(async()=>{if(!e)return;const[M,he]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:_,since:y}),s(e,"get_debug_trace",Wx({count:120,since:A,category:v}))]);if(M.status==="fulfilled"){const ye=M.value,ee=(ye==null?void 0:ye.result)||ye,je=Ux(ee);if(P(!1),R((ye==null?void 0:ye.success)===!1?String((ye==null?void 0:ye.error)||"Could not load daemon logs"):""),i(je.kind),l(je.rawText),je.entries.length>0){n(Oe=>(y>0?[...Oe,...je.entries]:je.entries).slice(-300));const Te=je.entries.reduce((Oe,Pe)=>Math.max(Oe,Number(Pe.timestamp||0)),y);Te>y&&w(Te)}else je.kind!=="structured"&&y===0&&n([])}else P(!1),R(M.reason instanceof Error?M.reason.message:"Could not load daemon logs");if(he.status==="fulfilled"){const ye=he.value,ee=(ye==null?void 0:ye.result)||ye;if((ye==null?void 0:ye.success)===!1)C(String((ye==null?void 0:ye.error)||"Could not load daemon trace"));else if(Array.isArray(ee==null?void 0:ee.trace)){C(""),f(ee.trace.slice(-120));const je=ee.trace.reduce((Te,Oe)=>Math.max(Te,Number(Oe.ts||0)),A);je>A&&m(je)}else C(""),f([]);G(!1)}else G(!1),C(he.reason instanceof Error?he.reason.message:"Could not load daemon trace");g(Ds.list({limit:120})),x(Date.now())},[y,A,_,e,s,v]);o.useEffect(()=>{if(!e||(te(),!h))return;const M=setInterval(()=>{te()},3e3);return()=>clearInterval(M)},[h,te,e,D]),o.useEffect(()=>{if(h&&(oe.length>0||le.length>0||me.length>0||Ce.length>0)){const M=ke.current?"smooth":"instant";setTimeout(()=>{var he;(he=ne.current)==null||he.scrollIntoView({behavior:M}),ke.current=!0},50)}},[oe.length,le.length,me.length,Ce.length,h]),o.useEffect(()=>{f([]),m(0),G(!0)},[v]);const ue=((we=xe.latestIssue)==null?void 0:we.level)==="error"?"danger":((Re=xe.latestIssue)==null?void 0:Re.level)==="warn"?"warning":"good",se=N||z?"danger":h?"good":"neutral",Se=o.useCallback(async()=>{var he;const M=Gx({daemonLogs:oe,daemonRawLines:le,trace:me,webEvents:Ce});if(!M.trim()){nt.showToast("복사할 visible logs가 없습니다.","info");return}try{await((he=navigator.clipboard)==null?void 0:he.writeText(M)),nt.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(ye){nt.showToast(ye instanceof Error?ye.message:"Could not copy visible logs","warning")}},[oe,le,me,Ce]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(M=>t.jsx("button",{onClick:()=>{j(M),n([]),l(""),i("empty"),w(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${_===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Ox.map(M=>t.jsx("button",{onClick:()=>b(M.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===M.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.label},M.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ce.info})`},{id:"issues",label:`Issues (${ce.issues})`},{id:"all",label:`All (${ce.all})`}].map(M=>t.jsx("button",{type:"button",onClick:()=>k(M.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===M.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:M.label},M.id))}),t.jsx("input",{value:$,onChange:M=>L(M.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{Se()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>S(M=>!M),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>O(M=>M+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),g([]),w(0),m(0),x(null),R(""),C(""),P(!0),G(!0),Ds.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(xe.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",oe.length+le.length," · trace ",me.length," · web ",Ce.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:$.trim()?`Filtered by “${$.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(ue)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),xe.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[xe.latestIssue.source," · ",xe.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:xe.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[xe.issueCount," warn/error signal(s) · ",Ii(xe.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(se)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:N||z?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Ii(p)]}),(N||z)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[N&&t.jsxs("div",{children:["Daemon logs: ",N]}),z&&t.jsxs("div",{children:["Daemon trace: ",z]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>X(M=>({...M,daemon:!M.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${le.length} visible raw line(s) from file fallback`:`${oe.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:F.daemon?"Hide":"Show"})]}),F.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[T&&!xe.hasAnyData&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!T&&N&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:N}),!T&&a==="empty"&&!N&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&le.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&oe.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&le.map((M,he)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:M},`raw-${he}`)),a!=="text"&&oe.map((M,he)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ai(M.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(M.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:M.level==="error"?"ERR":M.level==="warn"?"WRN":M.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:M.message})]},`log-${he}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>X(M=>({...M,trace:!M.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[me.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:F.trace?"Hide":"Show"})]}),F.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[K&&me.length===0&&!z&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!K&&z&&me.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:z}),!K&&me.length===0&&!z&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:$.trim()?"No trace entries match the current search.":v==="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."}),me.map(M=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ai(M.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),t.jsx("span",{children:M.level.toUpperCase()}),t.jsxs("span",{children:[M.category,".",M.stage]}),M.interactionId&&t.jsxs("span",{children:["ix=",M.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:fr(M.payload,360)||"No payload"})]},M.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>X(M=>({...M,web:!M.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[Ce.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:F.web?"Hide":"Show"})]}),F.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[Ce.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:$.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),Ce.map(M=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(M.ts).toLocaleTimeString()}),t.jsx("span",{children:M.kind}),M.topic&&t.jsxs("span",{children:["topic=",M.topic]}),M.interactionId&&t.jsxs("span",{children:["ix=",M.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:fr(M.payload,360)||"No payload"})]},M.id))]})]})]}),t.jsx("div",{ref:ne})]})}function ea(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ta(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Mi(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 Xx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Jx(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 Qx(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 Zx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=Qc(e,{enabled:!!e,includeSessions:!0,limit:Fo,intervalMs:Am}),d=f.diagnostics,g=f.loading,y=f.applyDiagnostics,w=o.useMemo(()=>ax({diagnostics:d,loading:g,refreshing:l,error:n}),[d,g,l,n]),A=o.useMemo(()=>new Map(s.map(L=>[L.sessionId||L.id,L])),[s]),m=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Fo}),T=ea(L);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");y(T.diagnostics||T.result||null),a("")}catch(L){const T=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(T)}finally{u(!1)}}},[y,e,r]);o.useEffect(()=>{!e||d||g||l||m()},[d,g,e,m,l]);const p=o.useCallback(async(L,T)=>{const P=`${L}:${T.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
73
- This will terminate the hosted runtime.`))){c(P);try{const K=await r(e,L,{sessionId:T.sessionId}),G=ea(K);if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Session host action failed");const N=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${N}: ${T.displayName}`,"success"),await m()}catch(K){const G=K instanceof Error?K.message:"Session host action failed";nt.showToast(G,"warning"),a(G)}finally{c(K=>K===P?null:K)}}},[e,m,r]),x=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
74
- 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",{}),P=ea(T);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},G=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,N=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;nt.showToast(`Pruned ${G} duplicate runtime(s) across ${N} group(s)`,"success"),await m()}catch(T){const P=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(P,"warning"),a(P)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,m,r]),h=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,T)=>(T.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Al(h),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,h]),_=S.liveRuntimes,j=S.recoverySnapshots,I=S.inactiveRecords,k=o.useMemo(()=>Qx(_),[_]),v=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),b=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),$=(L,T)=>{var O;const P=i===`session_host_resume_session:${L.sessionId}`,K=i===`session_host_restart_session:${L.sessionId}`,G=i===`session_host_stop_session:${L.sessionId}`,N=po(L.meta),R=A.get(L.sessionId),z=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,C=T==="recovery"?"Recover":"Resume",D=Ml(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:L.displayName||(R==null?void 0:R.cliName)||L.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Jx(L.lifecycle)}`,children:L.lifecycle}),N&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),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:L.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((O=L.writeOwner)==null?void 0:O.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Xx(L.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(La,{size:11})," ",z]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Mi(L.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{p("session_host_resume_session",L)},children:P?`${C}ing…`:C}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{p("session_host_restart_session",L)},children:K?"Restarting…":"Restart"}),T==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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:()=>{p("session_host_stop_session",L)},children:G?"Stopping…":"Stop"})]})]})},L.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(es,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:hp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{m()},disabled:g||l,children:[t.jsx(Fs,{size:13}),g||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&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(js,{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})]})]})}),d&&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:d.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:j.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:d.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:Mi(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ta(d.hostStartedAt)})]})]}),b&&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(js,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:b.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ta(b.timestamp),b.sessionId?` · ${b.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(fn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("live")}),_.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:_.map(L=>$(L,"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(es,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ps("recovery")}),j.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:j.map(L=>$(L,"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:Ps("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(L=>$(L,"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"}),v.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:v.map(L=>{var P;const T=h.find(K=>K.sessionId===L.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)||((P=A.get(L.sessionId))==null?void 0:P.cliName)||L.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:ta(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function eb({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 sa({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 ra({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 tb({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),d=ar(e,"0.8.98");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(sa,{icon:t.jsx(ts,{size:13}),children:"Current Chats"}),t.jsx(ra,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(g=>{const y=fa(g);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(g),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:ut(g)}),y>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:xn(y)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Ss(g)})]},g.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(sa,{icon:t.jsx(Vi,{size:13}),children:"Recent Launches"}),t.jsx(ra,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(g=>{const{metaText:y,updatedLabel:w}=ml(g);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(g),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:g.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:y})]},g.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(sa,{icon:t.jsx(js,{size:13}),children:"Daemon Update"}),t.jsx(ra,{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:d?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"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(Fs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function sb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const rb={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 zr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function na({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Hs(),{handleLaunchIde:g,handleStopCli:y,handleRestartIde:w,handleStopIde:A,handleDetectIdes:m,launchingIde:p,launchingAgentType:x,addLog:h}=c,[S,_]=o.useState(null),j=o.useCallback(E=>{E&&d(as(E))},[d]),I=rb[e],k=e==="ide",v=e==="acp",b=o.useMemo(()=>n.filter(E=>E.category===e&&(e==="ide"||E.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(b.map(E=>[E.type,E.displayName||E.type])),[b]),[L,T]=o.useState(""),[P,K]=o.useState(""),[G,N]=o.useState([]),[R,z]=o.useState(""),[C,D]=o.useState(""),[O,F]=o.useState([]),[X,ne]=o.useState(!1),[ke,ge]=o.useState(!1),[V,pe]=o.useState(""),[W,J]=o.useState(!1),[oe,le]=o.useState(()=>wt()),[me,Ce]=o.useState(null),[ce,xe]=o.useState(f?"__custom__":u||s.defaultWorkspaceId||""),[te,ue]=o.useState(f||""),[se,Se]=o.useState([]),[we,Re]=o.useState(!1),[M,he]=o.useState(""),[ye,ee]=o.useState([]),[je,Te]=o.useState(!1),[Oe,Pe]=o.useState(""),Ve=o.useRef(null),[Ge,ft]=o.useState(null),et=o.useRef("__home__"),[it,Qe]=o.useState("__home__"),[It,ht]=o.useState(!1),at=o.useRef(0),Ae=se.filter(E=>!a.some(Y=>Y.type===E&&Nt(Y.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ce&&xe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(f){xe("__custom__"),ue(f);return}u&&(xe(u),ue(""))},[u,f]),o.useEffect(()=>{k||L&&(b.some(E=>E.type===L)||(T(""),D("")))},[b,k,L]);const He=(()=>{if(ce==="__custom__")return te.trim();if(!ce)return"";const E=(s.workspaces||[]).find(Y=>Y.id===ce);return(E==null?void 0:E.path)||""})(),ze=o.useCallback(E=>{const Y=Xe.current[E];Y&&(clearTimeout(Y),delete Xe.current[E]),Se(ie=>ie.includes(E)?ie.filter(Ee=>Ee!==E):ie)},[]),Mt=o.useRef(new Set),jt=o.useCallback(async E=>{if(l){Te(!0),Pe("");try{const Y=await jn(l,r,E);he(Y.path),ue(Y.path),ee(Y.directories)}catch(Y){Pe(Y instanceof Error?Y.message:"Could not load folder")}finally{Te(!1)}}},[r,l]),xt=o.useCallback(()=>{if(!l)return;xe("__custom__"),Re(!0);const E=a.map(ie=>ie.workspace),Y=wn(s.platform,vn(te.trim(),He,f,E,s.defaultWorkspacePath,(s.workspaces||[]).map(ie=>ie.path)));jt(Y)},[te,f,jt,s.defaultWorkspacePath,s.platform,s.workspaces,a,He,l]),bt=o.useCallback(E=>{const Y=String(E.workspace||"").trim();if(!Y)return;const ie=(s.workspaces||[]).find(Ee=>zr(Ee.path)===zr(Y));if(ie){xe(ie.id),ue("");return}xe("__custom__"),ue(Y)},[s.workspaces]),Lt=o.useCallback(E=>{const Y=String(E.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const ie=(s.workspaces||[]).find(Ee=>zr(Ee.path)===zr(Y));return ie?{workspaceId:ie.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),yt=o.useCallback(async E=>{if(!l||!E||e!=="cli"){F([]),ne(!1),ge(!1),pe("");return}const Y=at.current+1;at.current=Y,ne(!0),pe("");try{const ie=await l(r,"list_saved_sessions",{providerType:E,kind:"cli",limit:30});if(at.current!==Y)return;const Ee=(ie==null?void 0:ie.result)??ie;F(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(ie){if(at.current!==Y)return;F([]),pe(ie instanceof Error?ie.message:"Could not load saved sessions")}finally{at.current===Y&&(ne(!1),ge(!0))}},[e,r,l]),Dt=o.useMemo(()=>{if(e!=="cli"||!L)return null;const E=$.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:C||void 0,transport:"pty",mode:"chat",agentName:E,agentType:L,status:"idle",title:E,messages:[],ideType:L,workspaceName:He,displayPrimary:E,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,$,He,C,L]),Z=o.useCallback(E=>{if(e==="ide"||!E){N([]);return}N(Cl(r,E))},[e,r]);o.useEffect(()=>{at.current+=1,D(""),Z(L),ge(!1),F([]),pe(""),ne(!1)},[e,Z,yt,L]);const De=o.useMemo(()=>O.find(E=>E.providerSessionId===C)||null,[O,C]);o.useEffect(()=>{if(!C)return;const E=O.find(Y=>Y.providerSessionId===C);E!=null&&E.canResume||D("")},[O,C]);const $e=o.useCallback((E,Y)=>{Ve.current=Y,et.current=E.selectedWorkspaceKey||"__home__",Qe(E.selectedWorkspaceKey||"__home__"),ft(E)},[]),ot=o.useCallback(()=>{Ve.current&&(ht(!0),Ve.current().finally(()=>{Ve.current=null,ht(!1),ft(null)}))},[]),kt=o.useCallback(E=>{if(!E)return;Se(ie=>ie.includes(E)?ie:[...ie,E]);const Y=Xe.current[E];Y&&clearTimeout(Y),Xe.current[E]=setTimeout(()=>{Se(ie=>ie.includes(E)?ie.filter(Ee=>Ee!==E):ie),delete Xe.current[E]},2e4)},[]);o.useEffect(()=>{for(const Y of a)Nt(Y.status)!=="stopped"&&(se.includes(Y.type)&&!Mt.current.has(Y.type)&&(Mt.current.add(Y.type),h("info",`${$.get(Y.type)||Y.type} launched`,!0)),ze(Y.type));const E=new Set(a.filter(Y=>Nt(Y.status)!=="stopped").map(Y=>Y.type));Mt.current.forEach(Y=>{!se.includes(Y)&&!E.has(Y)&&Mt.current.delete(Y)})},[h,ze,a,se,$]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[B,H]=o.useState({}),[U,q]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),ie=(Y==null?void 0:Y.result)||Y;ie!=null&&ie.success&&(ie!=null&&ie.ideExtensions)&&H(ie.ideExtensions)}catch{}})()},[k,r,l]);const re=E=>k?dt(E.type):e==="cli"?E.cliName:E.acpName,Ne=k?s.detectedIdes||[]:[],Ie=o.useCallback(async E=>{const Y=(E==null?void 0:E.type)||L,ie=(E==null?void 0:E.workspacePath)??He;if(k){await g(Y,ie?{workspace:ie}:void 0)&&kt(Y);return}const Ee=await c.runLaunchCliCore({cliType:Y,dir:E!=null&&E.workspaceId?void 0:ie||void 0,workspaceId:(E==null?void 0:E.workspaceId)||void 0,useHome:(E==null?void 0:E.useHome)||!(E!=null&&E.workspaceId)&&!ie,argsStr:(E==null?void 0:E.argsStr)??(P||void 0),model:(E==null?void 0:E.model)??(v&&R||void 0),resumeSessionId:(E==null?void 0:E.resumeSessionId)||!v&&e==="cli"&&Y===L&&C||void 0});if(Ee.success||Ee.pending){const Me=(E==null?void 0:E.argsStr)??P;!k&&(Me!=null&&Me.trim())&&(Il(r,Y,Me),Z(Y)),kt(Y),Ee.success&&Ee.sessionId&&j(Ee.sessionId)}},[c,g,v,k,P,R,Z,kt,r,j,He,C,L]),Le=Ec(k?"ide":v?"acp":"cli",!k&&!v&&!!C),Be=$c(k?"ide":v?"acp":"cli",!k&&!v&&!!C),Q=()=>{var Me;const E=k?dt(L):$.get(L)||L,Y=!k&&!v&&!!C,{options:ie,selectedKey:Ee}=ys({machine:s,currentWorkspaceId:ce&&ce!=="__custom__"?ce:null,currentWorkspacePath:He});$e({title:Y?Ya(E):hs("start-fresh",E),description:Y?Xa():xs("start-fresh"),confirmLabel:Le,busyLabel:Be,workspaceOptions:ie,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:E},...!k&&e==="cli"&&C?[{label:"Resume",value:((Me=O.find(Ke=>Ke.providerSessionId===C))==null?void 0:Me.title)||C}]:[],...!k&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ke=ie.find(qe=>qe.key===et.current);Ke!=null&&Ke.workspaceId?(xe(Ke.workspaceId),ue("")):Ke!=null&&Ke.workspacePath?(xe("__custom__"),ue(Ke.workspacePath)):(xe(""),ue("")),await Ie({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},ve=E=>{k?A(E):y(E.type,E.workspace,E.id)},tt=o.useCallback(async(E,Y,ie=!1)=>{if(E.mode===Y){ie&&E.sessionId&&j(E.sessionId);return}if(!l||!E.sessionId){ie&&E.sessionId&&j(E.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:E.sessionId,cliType:E.type,mode:Y}),ie&&j(E.sessionId)}catch(Ee){const Me=ao(Ee);no(Ee)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,j,l]),Ue=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ce,onChange:E=>{const Y=E.target.value;if(xe(Y),Y==="__custom__"&&l){xt();return}Y!=="__custom__"&&ue("")},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(E=>t.jsxs("option",{value:E.id,children:[E.id===s.defaultWorkspaceId?"⭐ ":"",gn(E.path,E.label)]},E.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…"})]})}),ce==="__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:xt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:te,onChange:E=>ue(E.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:ce==="__custom__"?He?t.jsx("span",{className:"font-mono truncate block",title:He,children:He}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":He?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ce===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:He,children:He})]}):"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:k?Ne.length>0?Ne.map(E=>{const Y=a.find(qe=>(qe.type||"").toLowerCase()===(E.type||"").toLowerCase()&&Nt(qe.status)!=="stopped"),ie=E.running||!!Y,Ee=!!Y&&Y.cdpConnected,Me=se.includes(E.type||E.id||""),Ke=L===(E.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&Y){const qe=Y.sessionId;qe?d(as(qe),{state:{openRemoteForTabKey:qe}}):d("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Me||T(qe=>qe===(E.type||"")?"":E.type||"")},disabled:!!p||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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:p&&p!==E.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(E.type)}),ie&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"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:E.name||dt(E.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ee?"text-green-400":Me?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Me?"Starting...":Ke?"Configure":"Select"})]})]},E.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:m,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(Kd,{size:14})," Scan System"]})]}):b.length>0?b.map(E=>{const Y=L===E.type,ie=se.includes(E.type),Me=!!a.find(Ke=>Ke.type===E.type&&Nt(Ke.status)!=="stopped");return t.jsxs("button",{onClick:()=>T(Ke=>Ke===E.type?"":E.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:E.icon}),Me&&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:E.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ie?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:ie?"Starting...":Y?"Configure":"Select"})]})]},E.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."})]})}),L&&(k?Ne.find(E=>E.type===L):b.find(E=>E.type===L))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:k?dt(L):$.get(L)||L})]}),Ue,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Ll,{busy:!!x||!!p||se.includes(L),savedSessionsLoading:X,savedSessionsError:V,selectedSession:De,onRefresh:()=>void yt(L),onOpenHistory:()=>{L&&(J(!0),Tl({hasLoadedInitialResults:ke,isLoading:X})&&yt(L))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&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:R,onChange:E=>z(E.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:P,onChange:E=>K(E.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"}),G.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:G.map(E=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(E),title:E,children:E},E))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Q,disabled:!!x||!!p||se.includes(L),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:x===L||p===L?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+se.filter(E=>!a.some(Y=>Y.type===E&&Nt(Y.status)!=="stopped")).length,")"]}),a.length===0&&Ae.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:[Ae.map(E=>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(E)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?dt(E):$.get(E)||E}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===E?"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:${E}`)),a.map(E=>{const Y=k?E:null,ie=!k&&!v?E:null,Ee=Nt(E.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(E.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[re(E),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:E.workspace||"—"}),(ie==null?void 0:ie.mode)&&t.jsx("span",{className:ie.mode==="chat"?"text-violet-400":"text-text-secondary",children:ie.mode==="chat"?"Chat view":"Terminal view"})]}),ie&&(ie.runtimeKey||ie.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ie.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 ",ie.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 Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${ie.runtimeKey}`),_(ie.runtimeKey||null),window.setTimeout(()=>{_(Ke=>Ke===ie.runtimeKey?null:Ke)},1200)},children:S===ie.runtimeKey?"Copied":"Copy"})]}),ie.runtimeWriteOwner&&t.jsx("span",{style:{color:ie.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ie.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:sb(ie.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 ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Me=E.sessionId;if(Me){d(as(Me),{state:{openRemoteForTabKey:Me}});return}d("/dashboard",{state:{openRemoteForTabKey:E.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(Pt,{size:13})}),t.jsx("button",{onClick:()=>{const Me=E.workspace||"",{options:Ke,selectedKey:qe}=ys({machine:s,currentWorkspacePath:Me});$e({title:hs("restart-ide",dt(E.type)),description:xs("restart-ide"),confirmLabel:Os("restart-ide"),busyLabel:Ws("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:qe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:dt(E.type)}]},async()=>{const _e=Ke.find(Ut=>Ut.key===et.current),We=(_e==null?void 0:_e.workspacePath)??"";if(We&&We!==Me){await Ie({type:E.type,workspacePath:We});return}await w(E)})},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(Fs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Me=E.sessionId;Me&&j(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!E.sessionId,children:t.jsx(ts,{size:14})}),ie&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[ie.mode&&t.jsx(Va,{mode:ie.mode,onChange:Me=>void tt(ie,Me,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Me=E.sessionId;Me&&j(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!E.sessionId,children:ie.mode==="chat"?t.jsx(ts,{size:14}):t.jsx(Pt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Me=E.workspace||"",Ke=k?dt(E.type):re(E),{options:qe,selectedKey:_e}=ys({machine:s,currentWorkspacePath:Me});$e({title:hs("restart-stopped",Ke),description:xs("restart-stopped"),confirmLabel:Os("restart-stopped"),busyLabel:Ws("restart-stopped"),workspaceOptions:qe,selectedWorkspaceKey:_e,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ke}]},async()=>{const We=qe.find(Ut=>Ut.key===et.current);await Ie({type:E.type,workspaceId:(We==null?void 0:We.workspaceId)??null,workspacePath:(We==null?void 0:We.workspacePath)??"",useHome:!(We!=null&&We.workspaceId)&&!(We!=null&&We.workspacePath)})})},disabled:se.includes(E.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:se.includes(E.type)?"⏳":t.jsx(_a,{size:14})}):t.jsx("button",{onClick:()=>ve(E),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(At,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Me=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${rc(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",Nt(Me.status)]},Me.id))}),Y&&(B[Y.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(B[Y.type]||[]).map(Me=>t.jsxs("button",{disabled:U===`${Y.type}.${Me.type}`,onClick:async()=>{const Ke=`${Y.type}.${Me.type}`;q(Ke);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Me.type,enabled:!Me.enabled}),H(qe=>({...qe,[Y.type]:(qe[Y.type]||[]).map(_e=>_e.type===Me.type?{..._e,enabled:!_e.enabled}:_e)}))}catch(qe){console.error("Extension toggle failed:",qe)}finally{q(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,t.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},E.id)})]}),we&&l&&t.jsx(kn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:M,directories:ye,busy:je,error:Oe,confirmLabel:"Use this folder",onClose:()=>Re(!1),onNavigate:E=>{jt(E)},onConfirm:E=>{ue(E),xe("__custom__"),Re(!1)}}),Ge&&t.jsx(uo,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:it,onWorkspaceChange:E=>{et.current=E,Qe(E)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:It,onConfirm:ot,onCancel:()=>{Ve.current=null,ft(null)}}),W&&Dt&&t.jsx(Ja,{activeConv:Dt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:O,isSavedSessionsLoading:X,isResumingSavedSessionId:me,savedHistoryFilters:oe,onSavedHistoryFiltersChange:le,onClose:()=>J(!1),onNewChat:()=>{D(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{yt(L)},onResumeSavedSession:E=>{if(!E.canResume||me)return;const Y=Lt(E);D(E.providerSessionId),bt(E),Ce(E.providerSessionId),J(!1),Ie({type:E.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:E.providerSessionId}).finally(()=>{Ce(ie=>ie===E.providerSessionId?null:ie)})}})]})}const Ti=[{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 nb({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:g}){var m;const[y,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const A=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:Ti.map(p=>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===p.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(p.id),children:[t.jsx("span",{children:p.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${y===p.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[p.id]})]},p.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(m=Ti.find(p=>p.id===y))==null?void 0:m.helper})]}),y==="ide"&&t.jsx(na,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:f,initialWorkspacePath:d}),y==="cli"&&t.jsx(na,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:f,initialWorkspacePath:d}),y==="acp"&&t.jsx(na,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:g,initialWorkspaceId:f,initialWorkspacePath:d})]})}function ab({onNicknameSynced:e}={}){var Ce,ce,xe,te,ue,se,Se,we,Re;const{id:s}=bd(),r=Hs(),n=Ma(),{sendCommand:a}=Tt(),i=yr(),c=Jc(),l=Cc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(M=>M.id===s&&M.type==="adhdev-daemon"),g=u.some(M=>M.type==="adhdev-daemon"),[y,w]=o.useState("workspace"),[A,m]=o.useState("ide"),p=o.useRef(null),[x,h]=o.useState(null),S=o.useRef("__home__"),[_,j]=o.useState("__home__"),[I,k]=o.useState(!1),v=o.useRef(null);o.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),o.useEffect(()=>{if(!s||!d||y!=="overview")return;const M=d.machine;(typeof(M==null?void 0:M.cpus)!="number"||typeof(M==null?void 0:M.totalMem)!="number"||typeof(M==null?void 0:M.arch)!="string"||typeof(M==null?void 0:M.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[y,c,d,s]),lf(s&&y==="overview"?[s]:[],{enabled:y==="overview",intervalMs:Sm});const b=()=>{if(g){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=Lx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>nt.onToast(he=>{l.setToasts(ee=>{if(ee.some(Oe=>Oe.message===he.message&&he.timestamp-Oe.timestamp<3e3))return ee;const Te={id:he.id,message:he.message,type:he.type,timestamp:he.timestamp,targetKey:he.targetKey,actions:he.actions};return[...ee.slice(-4),Te]});const ye=he.duration||5e3;setTimeout(()=>l.setToasts(ee=>ee.filter(je=>je.id!==he.id)),ye)}),[l]);const L=(d==null?void 0:d.availableProviders)||[],T={};for(const M of L)T[M.type]=M.icon;const P=M=>T[M]||"",K=d?{id:d.id,hostname:nc(d,{fallbackId:d.id}),platform:((Ce=d.machine)==null?void 0:Ce.platform)||"unknown",arch:((ce=d.machine)==null?void 0:ce.arch)||"",cpus:((xe=d.machine)==null?void 0:xe.cpus)||0,totalMem:((te=d.machine)==null?void 0:te.totalMem)||0,freeMem:(ue=d.machine)==null?void 0:ue.freeMem,availableMem:(se=d.machine)==null?void 0:se.availableMem,loadavg:(Se=d.machine)==null?void 0:Se.loadavg,uptime:(we=d.machine)==null?void 0:we.uptime,release:((Re=d.machine)==null?void 0:Re.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,G=u.filter(M=>M.daemonId===s&&M.type!=="adhdev-daemon").filter(M=>!mr(M)&&!Ls(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,version:M.version||"",instanceId:M.instanceId||"",status:M.status,workspace:M.workspace||null,terminals:M.terminals||0,aiAgents:Lu(M.aiAgents||(M.agents||[]).map(he=>({id:he.name,name:he.name,status:he.status,version:he.version}))),activeChat:M.activeChat||null,chats:M.chats||[],childSessions:M.childSessions||[],cdpConnected:M.cdpConnected||!1,daemonId:s})),N=u.filter(M=>M.daemonId===s&&mr(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,cliName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,mode:M.mode,runtimeKey:M.runtimeKey,runtimeDisplayName:M.runtimeDisplayName,runtimeWorkspaceLabel:M.runtimeWorkspaceLabel,runtimeWriteOwner:M.runtimeWriteOwner||null,runtimeAttachedClients:M.runtimeAttachedClients||[],daemonId:s})),R=u.filter(M=>M.daemonId===s&&Ls(M)).map(M=>({id:M.id,sessionId:M.sessionId,type:M.type,acpName:M.cliName||M.type,status:M.status,workspace:M.workspace||"",activeChat:M.activeChat||null,providerSessionId:M.providerSessionId,daemonId:s})),z=d?_t(d,{fallbackId:s}):"",C="workspace",D=n.state,O=D==null?void 0:D.initialMachineTab,F=D==null?void 0:D.initialWorkspaceCategory,X=D==null?void 0:D.initialWorkspaceId,ne=D==null?void 0:D.initialWorkspacePath,ke=O==="ides"||O==="clis"||O==="acps"?"workspace":O||C,ge=O==="ides"?"ide":O==="clis"?"cli":O==="acps"?"acp":F,V=[...G.map(M=>{var he,ye,ee,je,Te;return{id:`ide:${M.type}:${M.workspace||""}`,label:((he=M.activeChat)==null?void 0:he.title)||M.type,kind:"ide",providerType:M.type,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Te=(je=(ee=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:ee.at)==null?void 0:je.call(ee,-1))==null?void 0:Te.timestamp)||0}}),...N.map(M=>{var he,ye,ee,je,Te;return{id:`cli:${M.type}:${M.workspace||""}`,label:((he=M.activeChat)==null?void 0:he.title)||M.cliName,kind:"cli",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Te=(je=(ee=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:ee.at)==null?void 0:je.call(ee,-1))==null?void 0:Te.timestamp)||0}}),...R.map(M=>{var he,ye,ee,je,Te;return{id:`acp:${M.type}:${M.workspace||""}`,label:((he=M.activeChat)==null?void 0:he.title)||M.acpName,kind:"acp",providerType:M.type,providerSessionId:M.providerSessionId,subtitle:ks(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace||void 0,lastLaunchedAt:((Te=(je=(ee=(ye=M.activeChat)==null?void 0:ye.messages)==null?void 0:ee.at)==null?void 0:je.call(ee,-1))==null?void 0:Te.timestamp)||0}})].sort((M,he)=>(he.lastLaunchedAt||0)-(M.lastLaunchedAt||0)),pe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(M=>({id:M.id,label:M.title||M.providerName||M.providerType,kind:M.kind,providerType:M.providerType,providerSessionId:M.providerSessionId,subtitle:ks(M.summaryMetadata)||M.workspace||void 0,workspace:M.workspace,summaryMetadata:M.summaryMetadata,lastLaunchedAt:M.lastLaunchedAt})):V,W=o.useMemo(()=>{var he;const M=((he=l.connectionStates)==null?void 0:he[s||""])||void 0;return u.filter(ye=>ye.daemonId===s&&ye.type!=="adhdev-daemon").flatMap(ye=>Qa(ye,{},{connectionStates:s&&M?{[s]:M}:void 0,defaultConnectionState:M})).filter(ye=>!(ye.transport==="pty"&&ye.mode==="terminal")).sort((ye,ee)=>fa(ee)-fa(ye))},[u,l.connectionStates,s]),J=o.useCallback(M=>{const he=Fa(M);he&&r(as(he))},[r]),oe=o.useCallback(()=>{p.current&&(k(!0),p.current().finally(()=>{p.current=null,k(!1),h(null)}))},[]),le=o.useCallback(M=>{if(!K)return;const{options:he,selectedKey:ye}=ys({machine:K,currentWorkspacePath:M.workspace}),ee=async()=>{m(M.kind),w("workspace")};p.current=async()=>{const je=he.find(Pe=>Pe.key===S.current),Te=(je==null?void 0:je.workspacePath)??null,Oe=(je==null?void 0:je.workspaceId)??null;if(M.kind==="ide"&&M.providerType){await $.handleLaunchIde(M.providerType,Te?{workspace:Te}:void 0);return}if((M.kind==="cli"||M.kind==="acp")&&M.providerType){await $.runLaunchCliCore({cliType:M.providerType,dir:Oe?void 0:Te||"",workspaceId:Oe||void 0,model:M.kind==="acp"&&oc(M.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:M.providerSessionId});return}await ee()},S.current=ye,j(ye),h({title:M.kind==="ide"?hs("restart-ide",M.label):M.providerSessionId?Ya(M.label):hs("start-fresh",M.label),description:M.kind==="ide"?xs("restart-ide"):M.providerSessionId?Xa():xs("start-fresh"),confirmLabel:M.kind==="ide"?Os("restart-ide"):M.providerSessionId?cn(!0):Os("start-fresh"),busyLabel:M.kind==="ide"?Ws("restart-ide"):M.providerSessionId?Ga(!0):Ws("start-fresh"),workspaceOptions:he,details:[{label:"Mode",value:M.kind.toUpperCase()},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]})},[$,K]);if(o.useEffect(()=>{w(ke)},[C,ke,s]),o.useEffect(()=>{ge&&m(ge)},[ge,s]),!K)return f?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:b,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 me=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:14})," Workspace"]}),count:G.length+N.length+R.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(es,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(pn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{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:b,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:[$.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:$.nicknameInput,onChange:M=>$.setNicknameInput(M.target.value),onKeyDown:M=>{M.key==="Enter"&&$.handleSaveNickname(),M.key==="Escape"&&$.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:$.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:()=>$.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:()=>{$.setEditingNickname(!0),$.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:z}),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:[K.platform," · ",K.arch]}),t.jsxs("span",{children:[K.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),K.p2p.available&&t.jsxs("span",{children:["P2P ",K.p2p.state==="connected"?"connected":K.p2p.state]}),K.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:K.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:me.map(M=>t.jsxs("button",{onClick:()=>w(M.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===M.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[M.label,M.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===M.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:M.count})]},M.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:[y==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(tb,{machineEntry:d,providers:L,recentLaunches:pe,currentConversations:W,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:le,onOpenConversation:J}),t.jsx(nb,{machine:K,machineId:s,providers:L,ideSessions:G,cliSessions:N,acpSessions:R,actions:$,getIcon:P,initialCategory:A,initialWorkspaceId:X,initialWorkspacePath:ne,sendDaemonCommand:a})]}),y==="providers"&&t.jsx(Bx,{machineId:s,providers:L,sendDaemonCommand:a}),y==="overview"&&t.jsx(Rx,{machineId:s,machine:K,ideSessions:G,cliSessions:N,acpSessions:R,actions:$,sendDaemonCommand:a}),y==="session-host"&&t.jsx(Zx,{machineId:s,cliSessions:N,sendDaemonCommand:a}),y==="logs"&&t.jsx(Yx,{machineId:s,sendDaemonCommand:a})]})})}),$.launchPick&&K&&t.jsx(eb,{machine:K,launchPick:$.launchPick,actions:$}),x&&t.jsx(uo,{title:x.title,description:x.description,details:x.details,workspaceOptions:x.workspaceOptions,selectedWorkspaceKey:_,onWorkspaceChange:M=>{S.current=M,j(M)},confirmLabel:x.confirmLabel,busyLabel:x.busyLabel,busy:I,onConfirm:oe,onCancel:()=>{p.current=null,h(null)}}),t.jsx(Kc,{toasts:l.toasts||[],onDismiss:M=>l.setToasts(he=>he.filter(ye=>ye.id!==M)),onClickToast:M=>{M.targetKey&&r(as(M.targetKey))}}),t.jsx("style",{children:`
75
- @keyframes toast-in {
76
- from { opacity: 0; transform: translateX(40px); }
77
- to { opacity: 1; transform: translateX(0); }
78
- }
79
- `})]})}function ho(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ob(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=ho();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Vt(e,s){return await fetch(ob(e),{credentials:"same-origin",...s})}function Dl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class ib{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(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,i,c){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:i,rows:c})}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 Vt(`/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 Jt=new ib;function cb(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=ho();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Vr=cb(),Li=3e3,lb=3e4;let Gt=null,db=0;const mn=new Map;let ds=null,ir=null;function Ri(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Zs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function ub(e){return e==="connected"?"connected":e}async function Zr(e,s,r){const n=Ip(e,r||{}),a=Gt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++db}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{mn.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);mn.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Na(e,s){const r=Gt;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 mb{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN}get connectionState(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Zr(this.daemonId,s,r)}async sendInput(s,r){return Zr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ds&&(clearInterval(ds),ds=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Zr(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());Jt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ds=setInterval(r,2e3)}stopScreenshots(s){ds&&(clearInterval(ds),ds=null)}}let Bt=null;function pb(e){return(!Bt||Bt.daemonId!==e)&&(Bt=new mb(e)),Bt}function fb({children:e}){const s=o.useRef(lr()),r=lr();s.current=r;const{setUserName:n}=ws(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((m,p)=>{l(m),ir==null||ir(m,p)},[]),f=o.useRef(null),d=o.useRef(),g=o.useRef(Li),y=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{y.current=!0,w.current=!1;function m(){var h,S;if(!y.current||((h=f.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=f.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Vr}...`),Zs("connect_attempt",{url:Vr,reason:A.current,delayMs:g.current});let x;try{x=new WebSocket(Vr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),p();return}f.current=x,x.onopen=()=>{if(!y.current){x.close();return}u("connected"),g.current=Li,Zs("open",{url:Vr,reason:A.current}),os.resubscribeAll({sendData:Na}),console.log("[Standalone WS] Connected")},Gt=x,x.onmessage=_=>{var j,I;try{const k=JSON.parse(_.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const v=mn.get(k.requestId);v&&(mn.delete(k.requestId),k.type==="error"?v.reject(new Error(((j=k.data)==null?void 0:j.message)||"Command failed")):v.resolve(k.data));return}if(k.type==="session_output"){const v=k.sessionId||k.cliId||k.cliType;v&&Jt.emitSessionOutput(v,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Jt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated,typeof k.cols=="number"?k.cols:void 0,typeof k.rows=="number"?k.rows:void 0);return}if(k.type==="topic_update"){const v=k.update;v&&os.publish(v);return}if(k.type==="status"||k.type==="initial_state"){const v=k.data;if(!v)return;const{injectEntries:b,markLoaded:$,getIdes:L}=s.current,T=v.instanceId||"standalone",P=L().find(N=>N.id===T),K=pb(T);Jt.register(T,K),Jt.setState(T,"connected"),u("connected",T),Jt.emitStatus(T,v);const G=on(v,{daemonId:T,existingDaemon:P,existingEntries:L()});Ri("ws_status",{type:k.type,daemonId:T,sessions:(v.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(v.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Ri("entries",{daemonId:T,entries:G.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),G.length>0&&b(G,{authoritativeDaemonIds:[T]}),$(),c.current!==T&&((I=i.current)==null||I.call(i),c.current=T,i.current=os.subscribe({sendData:Na},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const R=s.current.getIdes(),z=R.find(D=>D.id===T),C=on(N.status,{daemonId:T,existingDaemon:z,existingEntries:R,timestamp:N.timestamp});C.length>0&&s.current.injectEntries(C),N.userName&&a.current&&a.current(N.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},x.onclose=_=>{y.current&&(Bt==null||Bt.stopScreenshots(),Bt&&Jt.setState(Bt.daemonId,"disconnected"),u("disconnected"),f.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Zs("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),p())},x.onerror=_=>{w.current||!y.current||(A.current="error",Zs("error",{message:_ instanceof Event?"event":String(_),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function p(){if(!y.current)return;clearTimeout(d.current);const x=g.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Zs("schedule_reconnect",{reason:A.current,delayMs:x}),d.current=setTimeout(()=>{g.current=Math.min(g.current*1.5,lb),m()},x)}return m(),()=>{var x;y.current=!1,w.current=!0,(x=i.current)==null||x.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Gt=null),Bt&&(Bt.stopScreenshots(),Jt.unregister(Bt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function hb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(ir=(c,l)=>{r(c),l&&a(l)},()=>{ir=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=ub(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Cd,{connectionOverrides:i,children:t.jsx(fb,{children:e})})}const El="adhdev_standalone_font_preferences",vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Cn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],hr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],xb=new Set(Cn.map(e=>e.id)),bb=new Set(hr.map(e=>e.id));function Yt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:en("chat",s.chat),code:en("code",s.code),terminal:en("terminal",s.terminal)}}function en(e,s){const r=vs[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?xb:bb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function tn(e,s){var a;const r=en(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Cn:hr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function gb(e){const s=Yt(e),r=tn("chat",s.chat),n=tn("code",s.code),a=tn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ms(e,s=document.documentElement){const r=Yt(e),n=gb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function Ca(e){const s=Yt(e);try{localStorage.setItem(El,JSON.stringify(s))}catch{}return s}function yb(){try{const e=localStorage.getItem(El);if(e)return Yt(JSON.parse(e))}catch{}return vs}function vb(){return ms(yb())}function er(e,s){var n;const r=e==="chat"?Cn:hr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const wb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Wi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(es,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(pn,{}),label:"Settings"}];function jb({children:e}){const s=Hs(),r=Ma(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=d=>{s(d),a(!1)},u=()=>{c(d=>{const g=!d;try{localStorage.setItem("sidebar-collapsed",g?"1":"0")}catch{}return g})},f=d=>`nav-item${r.pathname.startsWith(d)?" 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:d=>d.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(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:wb.map(d=>t.jsxs("div",{className:f(d.path),id:`nav-${d.id}`,onClick:()=>l(d.path),title:i?d.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:d.icon}),!i&&d.label]},d.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(Hi,{})}),!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(Fi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.98"]}),t.jsx(Bp,{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 kb=[{icon:t.jsx(es,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(ts,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ui,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Pt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(dr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Hi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Sb=[{icon:t.jsx(Wd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Wi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Dd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(La,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx($d,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Nb=[{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 Cb(){return t.jsxs(Uc,{icon:t.jsx(Fi,{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.98"]}),children:[t.jsx(Rt,{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(Rt,{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:kb.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(Rt,{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:Wc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Fc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Hc.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(Rt,{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:Sb.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(Rt,{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:Nb.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(zc,{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(Jd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function aa(e,s,r){return{...e,[s]:r}}function oa({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:tn(e,n)})]})]})]})}function Ib({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(oa,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Cn,onChange:d=>i(aa(e,"chat",d))}),t.jsx(oa,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:hr,onChange:d=>i(aa(e,"code",d))}),t.jsx(oa,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:hr,onChange:d=>i(aa(e,"terminal",d))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",er("chat",e.chat.preset)," · Code: ",er("code",e.code.preset)," · Terminal: ",er("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",er("chat",vs.chat.preset)," / ",er("code",vs.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Ab(){const{ides:e}=ws(),s=e.find(W=>W.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Tt(),{userName:a}=ws(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[g,y]=o.useState(vs),[w,A]=o.useState(!1),[m,p]=o.useState(""),[x,h]=o.useState(""),[S,_]=o.useState("127.0.0.1"),[j,I]=o.useState(""),[k,v]=o.useState(""),[b,$]=o.useState(""),[L,T]=o.useState(""),[P,K]=o.useState(""),[G,N]=o.useState(!1),R=async()=>{const J=await(await Vt("/auth/session")).json();u(J)},z=async()=>{const J=await(await Vt("/api/v1/standalone/preferences")).json();d(J),_(J.standaloneBindHost);const oe=Yt(J.standaloneFontPreferences);y(oe),ms(oe),Ca(oe)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),z()]).catch(W=>{T(W instanceof Error?W.message:String(W))})},[]),o.useEffect(()=>{ms(g)},[g]);const C=W=>{const J=W.target.value.trim();s!=null&&s.id&&J!==a&&n(s.id,"set_user_name",{userName:J}).catch(console.error)},[D,O]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=W=>{O(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},X=async()=>{p(""),h(""),A(!0);try{const W=Yt(g),J=await Vt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),oe=await J.json();if(!J.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone font preferences");const le=Yt(oe.standaloneFontPreferences);d(oe),y(le),ms(le),Ca(le),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(W){p(W instanceof Error?W.message:String(W))}finally{A(!1)}},ne=()=>{const W=Yt(f==null?void 0:f.standaloneFontPreferences);p(""),h(""),y(W),ms(W)},ke=()=>{p(""),h(""),y(vs),ms(vs)},ge=async()=>{T(""),K(""),N(!0);try{const W=await Vt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),J=await W.json();if(!W.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone network preference");d(J),_(J.standaloneBindHost),K(J.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(W){T(W instanceof Error?W.message:String(W))}finally{N(!1)}},V=async()=>{if(T(""),K(""),k.trim().length<4){T("Password must be at least 4 characters.");return}if(k!==b){T("New password and confirmation do not match.");return}N(!0);try{const W=await Vt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:k})}),J=await W.json();if(!W.ok)throw new Error((J==null?void 0:J.error)||"Failed to save password");u(J),await z(),I(""),v(""),$(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Dl()}catch(W){T(W instanceof Error?W.message:String(W))}finally{N(!1)}},pe=async()=>{T(""),K(""),N(!0);try{const W=await Vt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),J=await W.json();if(!W.ok)throw new Error((J==null?void 0:J.error)||"Failed to clear password");u(J),await z(),I(""),v(""),$(""),K("Standalone password disabled.")}catch(W){T(W instanceof Error?W.message:String(W))}finally{N(!1)}};return t.jsxs(Uc,{icon:t.jsx(pn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Dr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(Dr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Rt,{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.98"]}),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:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Rt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>_("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>_("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{ge()},disabled:G,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:G?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Rt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&t.jsx(Dr,{variant:"error",children:L}),P&&t.jsx(Dr,{variant:"success",children:P}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:j,onChange:W=>I(W.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:k,onChange:W=>v(W.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:b,onChange:W=>$(W.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{V()},disabled:G,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:G?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{pe()},disabled:G,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Rt,{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(W=>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 ${W.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:W.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:W.type})]},W.type))})}),t.jsx(Rt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Fp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Rt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",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(Gp,{})]}),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(tf,{})]}),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:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(Ib,{value:g,savedValue:Yt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:m,notice:x,onChange:y,onSave:()=>{X()},onResetToSaved:ne,onResetToDefaults:ke})]}),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(nf,{})]})]})}),t.jsx(Rt,{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(Op,{}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:F})]})}),t.jsx(Rt,{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(Pd,{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:W=>c(W.target.value),onBlur:C,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}Kp();Zp();vb();const Mb=Ki({baseUrl:"",getToken:ho});function Tb({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),g=async()=>{a(!0),u("");try{const A=await(await Vt("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{g()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const A=await Vt("/api/v1/standalone/preferences");if(!A.ok)return;const m=await A.json();if(w)return;const p=Yt(m.standaloneFontPreferences);ms(p),Ca(p)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const y=async w=>{w.preventDefault(),d(!0),u("");try{const A=await Vt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),m=await A.json();if(!A.ok)throw new Error((m==null?void 0:m.error)||"Login failed");r(m),c(""),Dl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{d(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:y,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:f||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function _i(){const{ides:e,initialLoaded:s}=ws();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(la,{to:`/machines/${r.id}`,replace:!0}):t.jsx(la,{to:"/dashboard",replace:!0})}function Lb(){const e=o.useMemo(()=>({sendCommand:Zr,sendData:Na}),[]);return t.jsx(gd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Md,{client:Mb,children:t.jsx(Tb,{children:t.jsx(hb,{children:t.jsx(Ld,{value:e,children:t.jsx(jb,{children:t.jsxs(yd,{children:[t.jsx(cs,{path:"/dashboard",element:t.jsx(Tx,{})}),t.jsx(cs,{path:"/machine",element:t.jsx(_i,{})}),t.jsx(cs,{path:"/machines/:id",element:t.jsx(ab,{})}),t.jsx(cs,{path:"/machines",element:t.jsx(_i,{})}),t.jsx(cs,{path:"/about",element:t.jsx(Cb,{})}),t.jsx(cs,{path:"/settings",element:t.jsx(Ab,{})}),t.jsx(cs,{path:"*",element:t.jsx(la,{to:"/dashboard",replace:!0})})]})})})})})})})}Zm({connectionManager:Jt});vd(document.getElementById("root")).render(t.jsx(Lb,{}));